code
stringlengths
3
1.05M
repo_name
stringlengths
5
104
path
stringlengths
4
251
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
3
1.05M
# Copyright 2020 The FedLearner 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. # coding: utf-8 import atexit import datetime import json import os import threading import time import logging from functools import wraps import elasticsearch as es7 import elasticsearch6 as es6 import pytz from elasticsearch import helpers as helpers7 from elasticsearch6 import helpers as helpers6 from .common import Config, INDEX_NAME, INDEX_TYPE, get_es_template from . import fl_logging class Handler(object): def __init__(self, name): self._name = name def emit(self, name, value, tags=None, index_type='metrics'): """ Do whatever it takes to actually log the specified logging record. This version is intended to be implemented by subclasses and so raises a NotImplementedError. """ raise NotImplementedError('emit must be implemented ' 'by Handler subclasses') def get_name(self): return self._name def flush(self): pass class LoggingHandler(Handler): def __init__(self): super(LoggingHandler, self).__init__('logging') def emit(self, name, value, tags=None, index_type='metrics'): fl_logging.debug('[metrics] name[%s] value[%s] tags[%s]', name, value, str(tags)) class ElasticSearchHandler(Handler): """ Emit documents to ElasticSearch """ def __init__(self, ip, port): super(ElasticSearchHandler, self).__init__('elasticsearch') self._es = es7.Elasticsearch([ip], port=port, http_auth=(Config.ES_USERNAME, Config.ES_PASSWORD)) self._helpers = helpers7 self._version = int(self._es.info()['version']['number'].split('.')[0]) # ES 6.8 has differences in APIs compared to ES 7.6, # These `put_template`s is supposed to be done during deployment, here # is for old clients. if self._version == 6: self._es = es6.Elasticsearch([ip], port=port) self._helpers = helpers6 for index_type, index_name in INDEX_NAME.items(): if not self._es.indices.exists_template( '{}-template'.format(index_name) ): self._create_template_and_index(index_type) # suppress ES logger logging.getLogger('elasticsearch').setLevel(logging.CRITICAL) self._emit_batch = [] self._batch_size = Config.ES_BATCH_SIZE self._lock = threading.RLock() def emit(self, name, value, tags=None, index_type='metrics'): assert index_type in INDEX_TYPE if tags is None: tags = {} document = self._produce_document(name, value, tags, index_type) if not Config.METRICS_TO_STDOUT: # if filebeat not yet refurbished, directly emit to ES action = {'_index': INDEX_NAME[index_type], '_source': document} if self._version == 6: action['_type'] = '_doc' with self._lock: # emit when there are enough documents self._emit_batch.append(action) if len(self._emit_batch) >= self._batch_size: self.flush() else: # if filebeat refurbished, # print to std out and use filebeat to ship to ES document['index_type__'] = index_type print(json.dumps(document)) def flush(self): emit_batch = [] with self._lock: if self._emit_batch: emit_batch = self._emit_batch self._emit_batch = [] if emit_batch: fl_logging.info('Emitting %d documents to ES', len(emit_batch)) self._helpers.bulk(self._es, emit_batch) @staticmethod def _produce_document(name, value, tags, index_type): application_id = os.environ.get('APPLICATION_ID', '') if application_id: tags['application_id'] = str(application_id) if index_type == 'metrics': tags['process_time'] = datetime.datetime.now(tz=pytz.utc) \ .isoformat(timespec='microseconds') document = { "name": name, "value": value, "tags": tags } else: document = { "tags": tags } return document def _create_template_and_index(self, index_type): """ Args: index_type: ES index type. Creates a template and an index on ES. """ assert index_type in INDEX_TYPE self._es.indices.put_template( name='{}-template'.format(INDEX_NAME[index_type]), body=get_es_template(index_type, self._version) ) try: self._es.indices.create(index=INDEX_NAME[index_type]) return # index may have been created by other jobs except (es6.exceptions.RequestError, es7.exceptions.RequestError) as e: # if due to other reasons, re-raise exception if e.info['error']['type'] != 'resource_already_exists_exception': raise e class Metrics(object): def __init__(self): self.handlers = [] self._lock = threading.RLock() self.handler_initialized = False atexit.register(self.flush_handler) def init_handlers(self): with self._lock: if self.handler_initialized: return logging_handler = LoggingHandler() self.add_handler(logging_handler) es_host = os.environ.get('ES_HOST', '') es_port = os.environ.get('ES_PORT', '') if es_host and es_port: es_handler = ElasticSearchHandler(es_host, es_port) self.add_handler(es_handler) self.handler_initialized = True def add_handler(self, hdlr): """ Add the specified handler to this logger. """ with self._lock: if hdlr not in self.handlers: self.handlers.append(hdlr) def remove_handler(self, hdlr): """ Remove the specified handler from this logger. """ with self._lock: if hdlr in self.handlers: self.handlers.remove(hdlr) def emit(self, name, value, tags=None, index_type='metrics'): self.init_handlers() if not self.handlers or len(self.handlers) == 0: fl_logging.info('No handlers. Not emitting.') return for hdlr in self.handlers: try: hdlr.emit(name, value, tags, index_type) except Exception as e: # pylint: disable=broad-except fl_logging.warning('Handler [%s] emit failed. Error repr: [%s]', hdlr.get_name(), repr(e)) def flush_handler(self): for hdlr in self.handlers: try: hdlr.flush() except Exception as e: # pylint: disable=broad-except fl_logging.warning('Handler [%s] flush failed. ' 'Some metrics might not be emitted. ' 'Error repr: %s', hdlr.get_name(), repr(e)) _metrics_client = Metrics() def emit(name, value, tags=None, index_type='metrics'): _metrics_client.emit(name, value, tags, index_type) # Currently no actual differences among the methods below emit_counter = emit emit_store = emit emit_timer = emit def timer(func_name, tags=None): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): time_start = time.time() result = func(*args, **kwargs) time_end = time.time() time_spend = time_end - time_start emit(func_name, time_spend, tags) return result return wrapper return decorator
bytedance/fedlearner
fedlearner/common/metrics.py
Python
apache-2.0
8,599
"""Create a pseudo statistics to initialize HMM/GMM operating in latent space.""" import logging import argparse import glob import importlib import ast import pickle import numpy as np import amdtk # Logger. logger = logging.getLogger('amdtk') # Possible log-level. LOG_LEVELS = { 'error': logging.ERROR, 'warning': logging.WARNING, 'info': logging.INFO, 'debug': logging.DEBUG } def main(): # Argument parser. parser = argparse.ArgumentParser(description=__doc__) # Group of options for the logger. group = parser.add_argument_group('Logging') group.add_argument('--log_level', choices=['debug', 'info', 'warning'], default='info', help='file format of the features ' '(info)') # Mandatory arguments.. parser.add_argument('fea_dim', type=int, help='dimensionality of the features') parser.add_argument('mean', type=float, help='mean of the output statistics') parser.add_argument('var', type=float, help='variance of the output statistics') parser.add_argument('stats', help='output statistics') # Parse the command line. args = parser.parse_args() # Set the logging level. logging.getLogger('amdtk').setLevel(LOG_LEVELS[args.log_level]) # Create the pseudo statistics. data_stats = { 'mean': args.mean * np.ones(args.fea_dim), 'var': args.var * np.ones(args.fea_dim), 'count': 1, 'mv_norm': False } # Store the statistics. with open(args.stats, 'wb') as fid: pickle.dump(data_stats, fid) if __name__ == '__main__': main() else: print('This script cannot be imported') exit(1)
amdtkdev/amdtk
recipe/utils/create_stats.py
Python
mit
1,759
# -*- coding: utf-8 -*- from docutils import nodes, utils from docutils.parsers.rst import directives, roles, Directive from pygments.formatters import HtmlFormatter from pygments import highlight from pygments.lexers import get_lexer_by_name, TextLexer import re INLINESTYLES = False DEFAULT = HtmlFormatter(noclasses=INLINESTYLES) VARIANTS = { 'linenos': HtmlFormatter(noclasses=INLINESTYLES, linenos=True), } class Pygments(Directive): """ Source code syntax hightlighting. """ required_arguments = 1 optional_arguments = 0 final_argument_whitespace = True option_spec = dict([(key, directives.flag) for key in VARIANTS]) has_content = True def run(self): self.assert_has_content() try: lexer = get_lexer_by_name(self.arguments[0]) except ValueError: # no lexer found - use the text one instead of an exception lexer = TextLexer() # take an arbitrary option if more than one is given formatter = self.options and VARIANTS[self.options.keys()[0]] \ or DEFAULT parsed = highlight(u'\n'.join(self.content), lexer, formatter) return [nodes.raw('', parsed, format='html')] directives.register_directive('code-block', Pygments) directives.register_directive('sourcecode', Pygments) class YouTube(Directive): """ Embed YouTube video in posts. Courtesy of Brian Hsu: https://gist.github.com/1422773 VIDEO_ID is required, with / height are optional integer, and align could be left / center / right. Usage: .. youtube:: VIDEO_ID :width: 640 :height: 480 :align: center """ def align(argument): """Conversion function for the "align" option.""" return directives.choice(argument, ('left', 'center', 'right')) required_arguments = 1 optional_arguments = 2 option_spec = { 'width': directives.positive_int, 'height': directives.positive_int, 'align': align } final_argument_whitespace = False has_content = False def run(self): videoID = self.arguments[0].strip() width = 420 height = 315 align = 'left' if 'width' in self.options: width = self.options['width'] if 'height' in self.options: height = self.options['height'] if 'align' in self.options: align = self.options['align'] url = 'http://www.youtube.com/embed/%s' % videoID div_block = '<div class="youtube" align="%s">' % align embed_block = '<iframe width="%s" height="%s" src="%s" '\ 'frameborder="0"></iframe>' % (width, height, url) return [ nodes.raw('', div_block, format='html'), nodes.raw('', embed_block, format='html'), nodes.raw('', '</div>', format='html')] directives.register_directive('youtube', YouTube) _abbr_re = re.compile('\((.*)\)$') class abbreviation(nodes.Inline, nodes.TextElement): pass def abbr_role(typ, rawtext, text, lineno, inliner, options={}, content=[]): text = utils.unescape(text) m = _abbr_re.search(text) if m is None: return [abbreviation(text, text)], [] abbr = text[:m.start()].strip() expl = m.group(1) return [abbreviation(abbr, abbr, explanation=expl)], [] roles.register_local_role('abbr', abbr_role)
Natim/pelican
pelican/rstdirectives.py
Python
agpl-3.0
3,381
""" This is the single point of entry to generate the sample configuration file for Arias. """ import collections from asciipic.config import base as conf_base from asciipic.config import factory as conf_factory def get_options(): """Collect all the options info from the other modules.""" options = collections.defaultdict(list) for opt_class in conf_factory.get_options(): if not issubclass(opt_class, conf_base.Options): continue config_options = opt_class(None) options[config_options.group_name].extend(config_options.list()) return [(key, value) for key, value in options.items()]
micumatei/asciipic
asciipic/config/options.py
Python
mit
643
# Copyright 2012 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2012 Nebula, 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.conf.urls import patterns from django.conf.urls import url from openstack_dashboard.dashboards.admin.flavors import views urlpatterns = patterns( 'openstack_dashboard.dashboards.admin.flavors.views', url(r'^$', views.IndexView.as_view(), name='index'), url(r'^create/$', views.CreateView.as_view(), name='create'), url(r'^(?P<id>[^/]+)/update_metadata/$', views.UpdateMetadataView.as_view(), name='update_metadata'), url(r'^(?P<id>[^/]+)/update/$', views.UpdateView.as_view(), name='update'), )
kfox1111/horizon
openstack_dashboard/dashboards/admin/flavors/urls.py
Python
apache-2.0
1,302
#!/usr/bin/env python # # Electrum - lightweight Bitcoin client # Copyright (C) 2011 thomasv@gitorious # # 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 time, sys, socket, os import threading import urllib2 import json import Queue import sqlite3 import electrum_doge as electrum electrum.set_verbosity(False) import ConfigParser config = ConfigParser.ConfigParser() config.read("merchant.conf") my_password = config.get('main','password') my_host = config.get('main','host') my_port = config.getint('main','port') database = config.get('sqlite3','database') received_url = config.get('callback','received') expired_url = config.get('callback','expired') cb_password = config.get('callback','password') wallet_path = config.get('electrum','wallet_path') xpub = config.get('electrum','xpub') pending_requests = {} num = 0 def check_create_table(conn): global num c = conn.cursor() c.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='electrum_payments';") data = c.fetchall() if not data: c.execute("""CREATE TABLE electrum_payments (address VARCHAR(40), amount FLOAT, confirmations INT(8), received_at TIMESTAMP, expires_at TIMESTAMP, paid INT(1), processed INT(1));""") conn.commit() c.execute("SELECT Count(address) FROM 'electrum_payments'") num = c.fetchone()[0] print "num rows", num def row_to_dict(x): return { 'id':x[0], 'address':x[1], 'amount':x[2], 'confirmations':x[3], 'received_at':x[4], 'expires_at':x[5], 'paid':x[6], 'processed':x[7] } # this process detects when addresses have received payments def on_wallet_update(): for addr, v in pending_requests.items(): h = wallet.history.get(addr, []) requested_amount = v.get('requested') requested_confs = v.get('confirmations') value = 0 for tx_hash, tx_height in h: tx = wallet.transactions.get(tx_hash) if not tx: continue if wallet.verifier.get_confirmations(tx_hash) < requested_confs: continue for o in tx.outputs: o_address, o_value = o if o_address == addr: value += o_value s = (value)/1.e8 print "balance for %s:"%addr, s, requested_amount if s>= requested_amount: print "payment accepted", addr out_queue.put( ('payment', addr)) stopping = False def do_stop(password): global stopping if password != my_password: return "wrong password" stopping = True return "ok" def process_request(amount, confirmations, expires_in, password): global num if password != my_password: return "wrong password" try: amount = float(amount) confirmations = int(confirmations) expires_in = float(expires_in) except Exception: return "incorrect parameters" account = wallet.default_account() addr = account.get_address(0, num) num += 1 out_queue.put( ('request', (addr, amount, confirmations, expires_in) )) return addr def do_dump(password): if password != my_password: return "wrong password" conn = sqlite3.connect(database); cur = conn.cursor() # read pending requests from table cur.execute("SELECT oid, * FROM electrum_payments;") data = cur.fetchall() return map(row_to_dict, data) def getrequest(oid, password): oid = int(oid) conn = sqlite3.connect(database); cur = conn.cursor() # read pending requests from table cur.execute("SELECT oid, * FROM electrum_payments WHERE oid=%d;"%(oid)) data = cur.fetchone() return row_to_dict(data) def send_command(cmd, params): import jsonrpclib server = jsonrpclib.Server('http://%s:%d'%(my_host, my_port)) try: f = getattr(server, cmd) except socket.error: print "Server not running" return 1 try: out = f(*params) except socket.error: print "Server not running" return 1 print json.dumps(out, indent=4) return 0 def db_thread(): conn = sqlite3.connect(database); # create table if needed check_create_table(conn) while not stopping: cur = conn.cursor() # read pending requests from table cur.execute("SELECT address, amount, confirmations FROM electrum_payments WHERE paid IS NULL;") data = cur.fetchall() # add pending requests to the wallet for item in data: addr, amount, confirmations = item if addr in pending_requests: continue else: with wallet.lock: print "subscribing to %s"%addr pending_requests[addr] = {'requested':float(amount), 'confirmations':int(confirmations)} wallet.synchronizer.subscribe_to_addresses([addr]) wallet.up_to_date = False try: cmd, params = out_queue.get(True, 10) except Queue.Empty: cmd = '' if cmd == 'payment': addr = params # set paid=1 for received payments print "received payment from", addr cur.execute("update electrum_payments set paid=1 where address='%s'"%addr) elif cmd == 'request': # add a new request to the table. addr, amount, confs, minutes = params sql = "INSERT INTO electrum_payments (address, amount, confirmations, received_at, expires_at, paid, processed)"\ + " VALUES ('%s', %f, %d, datetime('now'), datetime('now', '+%d Minutes'), NULL, NULL);"%(addr, amount, confs, minutes) print sql cur.execute(sql) # set paid=0 for expired requests cur.execute("""UPDATE electrum_payments set paid=0 WHERE expires_at < CURRENT_TIMESTAMP and paid is NULL;""") # do callback for addresses that received payment or expired cur.execute("""SELECT oid, address, paid from electrum_payments WHERE paid is not NULL and processed is NULL;""") data = cur.fetchall() for item in data: oid, address, paid = item paid = bool(paid) headers = {'content-type':'application/json'} data_json = { 'address':address, 'password':cb_password, 'paid':paid } data_json = json.dumps(data_json) url = received_url if paid else expired_url if not url: continue req = urllib2.Request(url, data_json, headers) try: response_stream = urllib2.urlopen(req) print 'Got Response for %s' % address cur.execute("UPDATE electrum_payments SET processed=1 WHERE oid=%d;"%(oid)) except urllib2.HTTPError: print "cannot do callback", data_json except ValueError, e: print e print "cannot do callback", data_json conn.commit() conn.close() print "database closed" if __name__ == '__main__': if len(sys.argv) > 1: cmd = sys.argv[1] params = sys.argv[2:] + [my_password] ret = send_command(cmd, params) sys.exit(ret) # start network c = electrum.SimpleConfig({'wallet_path':wallet_path}) daemon_socket = electrum.daemon.get_daemon(c,True) network = electrum.NetworkProxy(daemon_socket,config) network.start() # wait until connected while network.is_connecting(): time.sleep(0.1) if not network.is_connected(): print_msg("daemon is not connected") sys.exit(1) # create watching_only wallet storage = electrum.WalletStorage(c) if not storage.file_exists: print "creating wallet file" wallet = electrum.wallet.Wallet.from_xpub(xpub, storage) else: wallet = electrum.wallet.Wallet(storage) wallet.synchronize = lambda: None # prevent address creation by the wallet wallet.start_threads(network) network.register_callback('updated', on_wallet_update) threading.Thread(target=db_thread, args=()).start() out_queue = Queue.Queue() # server thread from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer server = SimpleJSONRPCServer(( my_host, my_port)) server.register_function(process_request, 'request') server.register_function(do_dump, 'dump') server.register_function(getrequest, 'getrequest') server.register_function(do_stop, 'stop') server.socket.settimeout(1) while not stopping: try: server.handle_request() except socket.timeout: continue
electrumalt/electrum-doge
scripts/merchant/merchant.py
Python
gpl-3.0
9,336
from graphviz import Digraph class Node: def __init__(self, label, weight, comp3, comp5): self.label = label self.weight = weight self.comp3 = comp3 self.comp5 = comp5 def increment(self, w): self.weight+=w def decrement(self, w): self.weight-=w if self.weight < 0: self.weight = 0 class SplicingGraph: #1-based def __init__(self): self.labels = [] self.nodes = {} self.newNodes = [] self.edges = {} self.new_edges = {} self.fake_edges = {} def addNode(self, label, w=0, comp3=0, comp5=0): if label != "" and label not in self.labels: self.labels.append(label) self.nodes.update({len(self.labels):Node(label, w, comp3, comp5)}) if comp3 != 0 or comp5 != 0: self.newNodes.append(len(self.labels)) def splitNode(self, node_index, side, offset, coverage): self.decrementNode(node_index, coverage) off1 = 0 if side else offset off2 = offset if side else 0 new_label = "{}-{}-{}".format(self.labels[node_index - 1], off1, off2) self.addNode(new_label, coverage, 0, offset) new_index = self.labels.index(new_label) + 1 self.addEdge(node_index, new_index, 'f') return new_index def addEdge(self, n1, n2, t, w=0): if t == 'e': if (n1,n2) not in self.edges: self.edges.update({(n1,n2):w}) elif t == 'n': if (n1,n2) not in self.new_edges: self.new_edges.update({(n1,n2):w}) elif t == 'f': if (n1,n2) not in self.fake_edges: self.fake_edges.update({(n1,n2):w}) def buildOutLists(self): self.outLists = {} for (n1,n2),c in self.edges.items(): if n1 not in self.outLists: self.outLists.update({n1:{}}) self.outLists[n1].update({n2: c}) for (n1,n2),c in self.new_edges.items(): if n1 not in self.outLists: self.outLists.update({n1:{}}) self.outLists[n1].update({n2: c}) def getAdjMatrix(self): A = [[0 for x in range(0, len(self.labels)-len(self.newNodes))] for y in range(0, len(self.labels)-len(self.newNodes))] for (n1,n2) in self.edges: if n1 in self.newNodes: n1 = self.labels.index(self.labels[n1-1].split("-")[0])+1 if n2 in self.newNodes: n2 = self.labels.index(self.labels[n2-1].split("-")[0])+1 if n1 != n2: A[n1-1][n2-1] = 1 for (n1,n2) in self.new_edges: if n1 in self.newNodes: n1 = self.labels.index(self.labels[n1-1].split("-")[0])+1 if n2 in self.newNodes: n2 = self.labels.index(self.labels[n2-1].split("-")[0])+1 if n1 != n2: A[n1-1][n2-1] = 1 return A ''' def getAdjMatrix(self): A = [[0 for x in range(0, len(self.nodes))] for y in range(0, len(self.nodes))] for (n1,n2) in self.edges: if n1 != n2: A[n1-1][n2-1] = 1 for (n1,n2) in self.new_edges: if n1 != n2: A[n1-1][n2-1] = 1 for (n1,n2) in self.fake_edges: if n1 != n2: A[n1-1][n2-1] = 1 return A ''' def incrementNode(self, n1, w=1): if n1 in self.nodes: self.nodes[n1].increment(w) #print("Nodes {} incremented".format(self.nodes[n1-1])) def decrementNode(self, n1, w=1): if n1 in self.nodes: self.nodes[n1].decrement(w) #print("Nodes {} decremented".format(self.nodes[n1-1])) def incrementEdge(self, n1, n2, w=1): if (n1,n2) in self.edges: self.edges[(n1,n2)] += w elif (n1,n2) in self.new_edges: self.new_edges[(n1,n2)] += w elif (n1,n2) in self.fake_edges: self.fake_edges[(n1,n2)] += w def decrementEdge(self, n1, n2, w=1): if (n1,n2) in self.edges: if self.edges[(n1,n2)] > 0: self.edges[(n1,n2)] -= w elif (n1,n2) in self.new_edges: if self.new_edges[(n1,n2)] > 0: self.new_edges[(n1,n2)] -= w elif (n1,n2) in self.fake_edges: if self.fake_edges[(n1,n2)] > 0: self.fake_edges[(n1,n2)] -= w def isEdge(self, n1, n2): if (n1,n2) in self.edges: return True elif (n1,n2) in self.new_edges: return True elif (n1,n2) in self.fake_edges: return True return False def isSource(self, n): for (n1,n2),c in self.edges.items(): if n2 == n: return False for (n1,n2),c in self.new_edges.items(): if n2 == n: return False for (n1,n2),c in self.fake_edges.items(): if n2 == n: return False return True def isSink(self, n): for (n1,n2),c in self.edges.items(): if n1 == n: return False for (n1,n2),c in self.new_edges.items(): if n1 == n: return False for (n1,n2),c in self.fake_edges.items(): if n1 == n: return False return True def getFakeSons(self, n): fake_sons = {} for (n1,n2),c in self.fake_edges.items(): if n == n1: fake_sons.update({n2:c}) return fake_sons def getParents(self, n): parents = {} for (n1,n2),c in self.edges.items(): if n2 == n: parents.update({n1:c}) for (n1,n2),c in self.new_edges.items(): if n2 == n: parents.update({n1:c}) return parents def getNodeWeight(self, n): return self.nodes[n].weight def getNodeLabel(self, i): return self.nodes[i].label def getEdgeType(self, n1, n2): if (n1,n2) in self.edges: return 'e' elif (n1,n2) in self.new_edges: return 'n' elif (n1,n2) in self.fake_edges: return 'f' def getEdgeWeight(self, n1, n2): if (n1,n2) in self.edges: return self.edges[(n1, n2)] elif (n1,n2) in self.new_edges: return self.new_edges[(n1, n2)] else: return 0 def getIndex(self, label): #Not handled exception!!! return self.labels.index(label)+1 def clean(self, nodes_min, edges_min): edges_to_remove = [] for label in self.labels: if label == "": continue index = self.labels.index(label)+1 has_fake = False if self.nodes[index].weight <= nodes_min: for (n1,n2),cov in self.fake_edges.items(): if index == n1 or index == n2: has_fake = True if has_fake: continue #print("Removing node {}".format(self.labels[index-1])) self.labels[index-1] = "" self.nodes.pop(index) for (n1,n2),cov in self.edges.items(): if index == n1 or index == n2: edges_to_remove.append((n1,n2)) for (n1,n2),cov in self.new_edges.items(): if index == n1 or index == n2: edges_to_remove.append((n1,n2)) for (n1,n2),cov in self.edges.items(): if cov <= edges_min: edges_to_remove.append((n1,n2)) for (n1,n2),cov in self.new_edges.items(): if cov <= edges_min: edges_to_remove.append((n1,n2)) for edge in edges_to_remove: try: #print("Removing edge {}->{}".format(edge[0], edge[1])) self.edges.pop(edge) continue except KeyError: pass try: #print("Removing edge {}->{}".format(edge[0], edge[1])) self.new_edges.pop(edge) continue except KeyError: pass def print(self): print("### NODES ###") for label in self.labels: if label != "": index = self.labels.index(label)+1 print("{} {}: {}".format(index, label, self.nodes[index].weight)) print("### EDGES ###") for (n1,n2),c in self.edges.items(): print("{}->{}: {}".format(n1, n2, c)) print("### NEW EDGES ###") for (n1,n2),c in self.new_edges.items(): print("{}->{}: {}".format(n1, n2, c)) print("### FAKE EDGES ###") for (n1,n2),c in self.fake_edges.items(): print("{}->{}: {}".format(n1, n2, c)) def save(self, name): g = Digraph('G', filename="{}.gv".format(name))#os.path.join(OUT, "graph.gv")) g.attr('node', shape='circle') for label in self.labels: if label != "": index = self.labels.index(label) n_label = "{} ({})".format(label, self.nodes[index+1].weight) g.node(n_label) for (n1,n2),cov in self.edges.items(): n1_label = "{} ({})".format(self.labels[n1-1], self.nodes[n1].weight) n2_label = "{} ({})".format(self.labels[n2-1], self.nodes[n2].weight) g.edge(n1_label, n2_label, label=str(cov), color = "black") for (n1,n2),cov in self.new_edges.items(): n1_label = "{} ({})".format(self.labels[n1-1], self.nodes[n1].weight) n2_label = "{} ({})".format(self.labels[n2-1], self.nodes[n2].weight) g.edge(n1_label, n2_label, label=str(cov), color = "red") for (n1,n2),cov in self.fake_edges.items(): n1_label = "{} ({})".format(self.labels[n1-1], self.nodes[n1].weight) n2_label = "{} ({})".format(self.labels[n2-1], self.nodes[n2].weight) g.edge(n1_label, n2_label, label=str(cov), color = "black", style="dashed") g.render()
AlgoLab/galig
scripts/SplicingGraph.py
Python
gpl-3.0
10,173
#!/usr/bin/env python # # test_moderna.py # # unit tests for moderna interface # # http://iimcb.genesilico.pl/moderna/ # __author__ = "Magdalena Rother, Tomasz Puton, Kristian Rother" __copyright__ = "Copyright 2008, The Moderna Project" __credits__ = ["Janusz Bujnicki"] __license__ = "GPL" __maintainer__ = "Magdalena Rother" __email__ = "[email protected]" __status__ = "Production" from unittest import main, TestCase from moderna.Template import Template from moderna.sequence.ModernaSequence import Sequence from test_data import * from moderna.Constants import MODULE_PATH import os import tempfile this_dir = os.getcwd() class CommandlineTests(TestCase): """ Command-line-interface tests """ def setUp(self): self.tmp = tempfile.mktemp() self.tmp2 = tempfile.mktemp() def tearDown(self): if os.access(self.tmp,os.F_OK): os.remove(self.tmp) if os.access(self.tmp2,os.F_OK): os.remove(self.tmp2) def test_build_model(self): cmd = "python %smoderna.py -t %s -a %s -o %s > %s"%(MODULE_PATH+os.sep, MINI_TEMPLATE,MINI_ALIGNMENT_FILE,self.tmp, self.tmp2) os.system(cmd) t = Template(self.tmp) self.assertEqual(t.get_sequence(),Sequence('ACUGUGAYUA[UACCU#PG')) def test_insert_modification(self): cmd = "python %smoderna.py -s %s -o %s -m m22G -p 3 > %s"%(MODULE_PATH+os.sep, MINI_TEMPLATE, self.tmp, self.tmp2) os.system(cmd) t = Template(self.tmp) self.assertEqual(t.get_sequence(),Sequence('GCRGAUUUALCUCAG')) def test_insert_modi_chain(self): cmd = "python %smoderna.py -s %s -c D -o %s -m m22G -p 38 > %s"%(MODULE_PATH+os.sep, RNA_HAIRPIN, self.tmp, self.tmp2) os.system(cmd) t = Template(self.tmp, template_chain_name='D') self.assertEqual(t.get_sequence(),Sequence('CUGCCUQUC/RGC')) def test_get_sequence(self): cmd = "python %smoderna.py -t %s > %s"%(MODULE_PATH+os.sep, MINI_TEMPLATE, self.tmp) os.system(cmd) seq = open(self.tmp).read().strip() self.assertEqual(seq, "TEMPLATE SEQUENCE:\nGCGGAUUUALCUCAG") def test_examine_template(self): cmd = "python %smoderna.py -t %s -e > %s"%(MODULE_PATH+os.sep, NASTY_PDB, self.tmp) os.system(cmd) report = open(self.tmp).read().strip() self.assertTrue(report.find("Water residues present in the chain")>-1) def test_examine_template(self): cmd = "python %smoderna.py -t %s -l > %s"%(MODULE_PATH+os.sep, NASTY_PDB, self.tmp) os.system(cmd) report = open(self.tmp).read().strip() self.assertFalse(report.find("._._._")>-1) if __name__ == '__main__': main()
lenarother/moderna
tests/test_commandline.py
Python
gpl-3.0
2,750
print (("#000000 "*7)+"\n")*7
mungojelly/7by7grid
py/black.py
Python
cc0-1.0
30
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.paging import Paged class DomainPaged(Paged): """ A paging container for iterating over a list of :class:`Domain <azure.graphrbac.models.Domain>` object """ _attribute_map = { 'next_link': {'key': 'nextLink', 'type': 'str'}, 'current_page': {'key': 'value', 'type': '[Domain]'} } def __init__(self, *args, **kwargs): super(DomainPaged, self).__init__(*args, **kwargs)
Azure/azure-sdk-for-python
sdk/graphrbac/azure-graphrbac/azure/graphrbac/models/domain_paged.py
Python
mit
907
import os import math from collections import defaultdict G = {} with open(os.path.join(os.path.dirname(__file__), 'input.txt')) as f: for line in f: mats, outcome = line.strip().split('=>') outcome = outcome.strip().split(' ') mats = mats.strip().split(', ') mats = [mat.split(' ') for mat in mats] G[outcome[1]] = {"q": int(outcome[0]), "mats": [ {"q": int(mat[0]), "mat": mat[1]} for mat in mats], "produces": outcome[1]} recipies_used = defaultdict(int) def ore_needed(fuel): needed = defaultdict(int) needed['FUEL'] = fuel waste = defaultdict(int) while not (len(needed) == 1 and 'ORE' in needed): for mat, q in needed.items(): if mat == 'ORE': continue q -= min(waste[mat], q) waste[mat] -= min(waste[mat], q) if q > 0: recipe = G[mat] reactions_needed = math.ceil(q/recipe['q']) for child in recipe['mats']: needed[child['mat']] += reactions_needed * child['q'] waste[mat] += recipe['q'] * reactions_needed - q del needed[mat] break return needed['ORE'] # p1 print(ore_needed(1)) # p2 def binary_search(func, low, high): lo = low hi = high while lo <= hi: if lo == hi: return lo mid = (lo + hi + 1) // 2 if func(mid): lo = mid else: hi = mid - 1 arr = [1, 2, 3, 4, 5, 6] print(binary_search(lambda fuel: ore_needed(fuel) <= 1000000000000, low=1, high=10000000))
marcosfede/algorithms
adventofcode/2019/d14/d14.py
Python
gpl-3.0
1,643
import threading import time def worker(): print (threading.currentThread().getName() + 'Starting') time.sleep(2) print (threading.currentThread().getName()+'Exiting') def my_service(): print (threading.currentThread().getName()+ 'Starting') time.sleep(3) print (threading.currentThread().getName()+'Exiting') t = threading.Thread(name='my_service', target=my_service) w = threading.Thread(name='worker bee', target=worker) w2 = threading.Thread(target=worker) # use default name w3 = threading.Thread(target=worker) # use default name w.start() w2.start() w3.start() t.start()
mayankjohri/LetsExplorePython
Section 2 - Advance Python/Chapter S2.11 Multiprocessing and Threading/code/4_threading.py
Python
gpl-3.0
651
import _plotly_utils.basevalidators class TextValidator(_plotly_utils.basevalidators.StringValidator): def __init__( self, plotly_name="text", parent_name="isosurface.colorbar.title", **kwargs ): super(TextValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "calc"), role=kwargs.pop("role", "info"), **kwargs )
plotly/python-api
packages/python/plotly/plotly/validators/isosurface/colorbar/title/_text.py
Python
mit
464
from __future__ import unicode_literals from datetime import date from django import forms from django.db.models import Max, Min import django_filters from django.utils.translation import ugettext as _ from core.models import Personnel, Position, Program, ProgramCategory, \ ProgramReport, StockReport, StockOutReport from locations.models import Location from core.utils import iso_normalize CATEGORY_CHOICES = list( ProgramCategory.objects.all().values_list('pk', 'acronym')) POSITION_CHOICES = list(Position.objects.all().values_list('pk', 'description')) PROGRAM_CHOICES = list(Program.objects.all().values_list( 'pk', 'code')) # exclude(code='SFP').values_list('pk', 'code')) try: MAX_DATE = ProgramReport.objects.aggregate(Max('report_date')).values()[0] except Exception: # todo: this exception clause is too broad MAX_DATE = iso_normalize(date.today()) if MAX_DATE is None: MAX_DATE = iso_normalize(date.today()) try: MIN_DATE = ProgramReport.objects.aggregate(Min('report_date')).values()[0] except Exception: # todo: this exception clause is too broad MIN_DATE = iso_normalize(date.today()) if MIN_DATE is None: MIN_DATE = iso_normalize(date.today()) YEAR_CHOICES = [ (year, str(year)) for year in xrange(MAX_DATE.year, MIN_DATE.year - 1, -1) ] def make_period_choices(): return [('w{}'.format(week), 'week {}'.format(week)) for week in range(1, 54)] class LocationChoiceFilter(django_filters.ChoiceFilter): def __init__(self, *args, **kwargs): super(LocationChoiceFilter, self).__init__(*args, **kwargs) def filter(self, qs, value): if value: try: location = Location.objects.get(pk=value) descendant_sites = Location.get_sites( location.get_descendants()) return qs.filter(site__in=descendant_sites) except Location.DoesNotExist: return qs.none() return qs class SiteChoiceFilter(LocationChoiceFilter): def filter(self, qs, value): if value: try: location = Location.objects.get(pk=value) sublocation_pks = Location.get_sites( location.get_descendants()).values_list('pk', flat=True) return qs.filter(pk__in=sublocation_pks) except Location.DoesNotExist: return qs.none() return qs class PersonnelLocationChoiceFilter(LocationChoiceFilter): def filter(self, qs, value): if value: try: location = Location.objects.get(pk=value) descendant_loc_pks = location.get_descendants( include_self=True).values_list('pk', flat=True) return qs.filter(site__pk__in=descendant_loc_pks) except Location.DoesNotExist: return qs.none() return qs class PositionChoiceFilter(django_filters.ChoiceFilter): def __init__(self, *args, **kwargs): kwargs['choices'] = [('', '')] + POSITION_CHOICES super(PositionChoiceFilter, self).__init__(*args, **kwargs) def filter(self, qs, value): if value: try: position = Position.objects.get(pk=value) return qs.filter(position=position) except Position.DoesNotExist: return qs.none() return qs class CategoryChoiceFilter(django_filters.ChoiceFilter): def __init__(self, *args, **kwargs): kwargs['choices'] = [('', '')] + CATEGORY_CHOICES super(CategoryChoiceFilter, self).__init__(*args, **kwargs) def filter(self, qs, value): if value: try: category = ProgramCategory.objects.get(pk=value) return qs.filter(category=category) except ProgramCategory.DoesNotExist: return qs.none() return qs class PeriodChoiceFilter(django_filters.ChoiceFilter): def __init__(self, *args, **kwargs): kwargs['choices'] = [('', '')] + make_period_choices() super(PeriodChoiceFilter, self).__init__(*args, **kwargs) class ProgramChoiceFilter(django_filters.ChoiceFilter): def __init__(self, *args, **kwargs): kwargs['choices'] = [('0', _('All'))] + PROGRAM_CHOICES super(ProgramChoiceFilter, self).__init__(*args, **kwargs) def filter(self, qs, value): if value: return qs.filter(program__pk=value) return qs class YearChoiceFilter(django_filters.ChoiceFilter): def __init__(self, *args, **kwargs): kwargs['choices'] = YEAR_CHOICES if 'initial' not in kwargs: kwargs['initial'] = MAX_DATE.year super(YearChoiceFilter, self).__init__(*args, **kwargs) def filter(self, qs, value): if value: return qs.filter(created__year=value) return qs class ReportedYearChoiceFilter(YearChoiceFilter): def filter(self, qs, value): if value: return qs.filter(report_date__year=value) return qs class SiteFilterSet(django_filters.FilterSet): location = LocationChoiceFilter(widget=forms.HiddenInput()) class Meta: model = Location class PersonnelFilterSet(django_filters.FilterSet): location = PersonnelLocationChoiceFilter( widget=forms.HiddenInput() ) position = PositionChoiceFilter( widget=forms.Select({'class': 'select-two'}) ) class Meta: model = Personnel class ProgramReportFilterSet(django_filters.FilterSet): location = LocationChoiceFilter(widget=forms.HiddenInput()) year = ReportedYearChoiceFilter( widget=forms.Select({'class': 'select-two'}) ) period_number = PeriodChoiceFilter( widget=forms.Select({'class': 'select-two'}) ) program = ProgramChoiceFilter(widget=forms.Select({'class': 'select-two'})) class Meta: model = ProgramReport fields = [] class StockOutReportFilterSet(django_filters.FilterSet): location = LocationChoiceFilter( widget=forms.Select({'class': 'select-two'})) year = YearChoiceFilter(widget=forms.Select({'class': 'select-two'})) class Meta: model = StockOutReport fields = [] class StockReportFilterSet(django_filters.FilterSet): location = LocationChoiceFilter(widget=forms.HiddenInput()) start = django_filters.DateFilter(name='created', lookup_type='gte', input_formats=['%d/%m/%Y', '%d/%m/%y']) end = django_filters.DateFilter(name='created', lookup_type='lte', input_formats=['%d/%m/%Y', '%d/%m/%y']) class Meta: model = StockReport fields = []
system7-open-source/imamd
imam/webapp/filters.py
Python
agpl-3.0
6,756
# Copyright 2008-2010 WebDriver committers # Copyright 2008-2010 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Script for generating the wire protocol wiki documentation. This script is probably overkill, but it ensures commands are documented with consistent formatting. Usage: python trunk/wire.py > wiki/JsonWireProtocol.wiki """ class Resource(object): def __init__(self, path): self.path = path self.methods = [] def __getattribute__(self, attr): try: return super(Resource, self).__getattribute__(attr) except AttributeError, e: if self.methods: return self.methods[len(self.methods) - 1].__getattribute__(attr) raise e def Post(self, summary): return self.AddMethod(Method(self, 'POST', summary)) def Get(self, summary): return self.AddMethod(Method(self, 'GET', summary)) def Delete(self, summary): return self.AddMethod(Method(self, 'DELETE', summary)) def AddMethod(self, method): self.methods.append(method) return self def ToWikiString(self): str = '=== %s ===\n' % self.path for method in self.methods: str = '%s%s' % (str, method.ToWikiString(self.path)) return str def ToWikiTableString(self): return ''.join(m.ToWikiTableString() for m in self.methods) class SessionResource(Resource): def AddMethod(self, method): return (Resource.AddMethod(self, method). AddUrlParameter(':sessionId', 'ID of the session to route the command to.')) class ElementResource(SessionResource): def AddMethod(self, method): return (SessionResource.AddMethod(self, method). AddUrlParameter(':id', 'ID of the element to route the command to.'). AddError('StaleElementReference', 'If the element referenced by `:id` is no longer attached ' 'to the page\'s DOM.')) def RequiresVisibility(self): return self.AddError('ElementNotVisible', 'If the referenced element is not visible on the page ' '(either is hidden by CSS, has 0-width, or has 0-height)') def RequiresEnabledState(self): return self.AddError('InvalidElementState', 'If the referenced element is disabled.') class Method(object): def __init__(self, parent, method, summary): self.parent = parent self.method = method self.summary = summary self.url_parameters = [] self.json_parameters = [] self.return_type = None self.errors = {} def AddUrlParameter(self, name, description): self.url_parameters.append({ 'name': name, 'desc': description}) return self.parent def AddJsonParameter(self, name, type, description): self.json_parameters.append({ 'name': name, 'type': type, 'desc': description}) return self.parent def AddError(self, type, summary): self.errors[type] = {'type': type, 'summary': summary} return self.parent def SetReturnType(self, type, description): self.return_type = { 'type': type, 'desc': description} return self.parent def _GetUrlParametersWikiString(self): if not self.url_parameters: return '' return ''' <dd> <dl> <dt>*URL Parameters:*</dt> %s </dl> </dd>''' % '\n'.join('<dd>`%s` - %s</dd>' % (param['name'], param['desc']) for param in self.url_parameters) def _GetJsonParametersWikiString(self): if not self.json_parameters: return '' return ''' <dd> <dl> <dt>*JSON Parameters:*</dt> %s </dl> </dd>''' % '\n'.join('<dd>`%s` - `%s` %s</dd>' % (param['name'], param['type'], param['desc']) for param in self.json_parameters) def _GetReturnTypeWikiString(self): if not self.return_type: return '' type = '' if self.return_type['type']: type = '`%s` ' % self.return_type['type'] return ''' <dd> <dl> <dt>*Returns:*</dt> <dd>%s%s</dd> </dl> </dd>''' % (type, self.return_type['desc']) def _GetErrorWikiString(self): if not self.errors.values(): return '' return ''' <dd> <dl> <dt>*Potential Errors:*</dt> %s </dl> </dd>''' % '\n'.join('<dd>`%s` - %s</dd>' % (error['type'], error['summary']) for error in self.errors.values()) def ToWikiString(self, path): return ''' <dl> <dd> ==== %s %s ==== </dd> <dd> <dl> <dd>%s</dd>%s%s%s%s </dl> </dd> </dl> ''' % (self.method, path, self.summary, self._GetUrlParametersWikiString(), self._GetJsonParametersWikiString(), self._GetReturnTypeWikiString(), self._GetErrorWikiString()) def ToWikiTableString(self): return '|| %s || [#%s_%s %s] || %s ||\n' % ( self.method, self.method, self.parent.path, self.parent.path, self.summary[:self.summary.find('.') + 1].replace('\n', '').strip()) def main(): resources = [] resources.append(Resource('/status'). Get(''' Query the server\'s current status. The server should respond with a general \ "HTTP 200 OK" response if it is alive and accepting commands. The response \ body should be a JSON object describing the state of the server. All server \ implementations should return two basic objects describing the server's \ current platform and when the server was built. All fields are optional; \ if omitted, the client should assume the value is uknown. Furthermore, \ server implementations may include additional fields not listed here. || *Key* || *Type* || *Description* || || build || object || || || build.version || string || A generic release label (i.e. "2.0rc3") || || build.revision || string || The revision of the local source control client \ from which the server was built || || build.time || string || A timestamp from when the server was built. || || os || object || || || os.arch || string || The current system architecture. || || os.name || string || The name of the operating system the server is \ currently running on: "windows", "linux", etc. || || os.version || string || The operating system version. || '''). SetReturnType('{object}', 'An object describing the general status of the server.')) resources.append( Resource('/session'). Post(''' Create a new session. The server should attempt to create a session that most \ closely matches the desired capabilities.'''). AddJsonParameter('desiredCapabilities', '{object}', 'An object describing the session\'s ' '[#Desired_Capabilities desired capabilities].'). SetReturnType(None, 'A `303 See Other` redirect to `/session/:sessionId`, where' ' `:sessionId` is the ID of the newly created session.')) resources.append( SessionResource('/session/:sessionId'). Get('Retrieve the capabilities of the specified session.'). SetReturnType('{object}', 'An object describing the session\'s ' '[#Actual_Capabilities capabilities].'). Delete('Delete the session.')) resources.append( SessionResource('/session/:sessionId/timeouts/async_script'). Post('''Set the amount of time, in milliseconds, that asynchronous \ scripts executed by `/session/:sessionId/execute_async` are permitted to run \ before they are aborted and a |Timeout| error is returned to the client.'''). AddJsonParameter('ms', '{number}', 'The amount of time, in milliseconds, that time-limited' ' commands are permitted to run.')) resources.append( SessionResource('/session/:sessionId/timeouts/implicit_wait'). Post('''Set the amount of time the driver should wait when searching for \ elements. When searching for a single element, the driver should poll the page until an \ element is found or the timeout expires, whichever occurs first. When searching for multiple \ elements, the driver should poll the page until at least one element is found or the timeout \ expires, at which point it should return an empty list. If this command is never sent, the driver should default to an implicit wait of\ 0ms.'''). AddJsonParameter('ms', '{number}', 'The amount of time to wait, in milliseconds. This value' ' has a lower bound of 0.')) resources.append( SessionResource('/session/:sessionId/window_handle'). Get('Retrieve the current window handle.'). SetReturnType('{string}', 'The current window handle.')) resources.append( SessionResource('/session/:sessionId/window_handles'). Get('Retrieve the list of all window handles available to the session.'). SetReturnType('{Array.<string>}', 'A list of window handles.')) resources.append( SessionResource('/session/:sessionId/url'). Get('Retrieve the URL of the current page.'). SetReturnType('{string}', 'The current URL.'). Post('Navigate to a new URL.'). AddJsonParameter('url', '{string}', 'The URL to navigate to.')) resources.append( SessionResource('/session/:sessionId/forward'). Post('Navigate forwards in the browser history, if possible.')) resources.append( SessionResource('/session/:sessionId/back'). Post('Navigate backwards in the browser history, if possible.')) resources.append( SessionResource('/session/:sessionId/refresh'). Post('Refresh the current page.')) resources.append( SessionResource('/session/:sessionId/execute'). Post(''' Inject a snippet of !JavaScript into the page for execution in the context of \ the currently selected frame. The executed script is assumed to be \ synchronous and the result of evaluating the script is returned to the client. The `script` argument defines the script to execute in the form of a \ function body. The value returned by that function will be returned to the \ client. The function will be invoked with the provided `args` array and the \ values may be accessed via the `arguments` object in the order specified. Arguments may be any JSON-primitive, array, or JSON object. JSON objects that \ define a [#WebElement_JSON_Object WebElement reference] will be converted to \ the corresponding DOM element. Likewise, any !WebElements in the script result \ will be returned to the client as [#WebElement_JSON_Object WebElement \ JSON objects].'''). AddJsonParameter('script', '{string}', 'The script to execute.'). AddJsonParameter('args', '{Array.<*>}', 'The script arguments.'). AddError('JavaScriptError', 'If the script throws an Error.'). AddError('StaleElementReference', 'If one of the script arguments is a !WebElement that is not ' 'attached to the page\'s DOM.'). SetReturnType('{*}', 'The script result.')) resources.append( SessionResource('/session/:sessionId/execute_async'). Post(''' Inject a snippet of !JavaScript into the page for execution in the context of \ the currently selected frame. The executed script is assumed to be \ asynchronous and must signal that is done by invoking the provided callback, \ which is always provided as the final argument to the function. The value \ to this callback will be returned to the client. Asynchronous script commands may not span page loads. If an `unload` event is \ fired while waiting for a script result, an error should be returned to the \ client. The `script` argument defines the script to execute in teh form of a function \ body. The function will be invoked with the provided `args` array and the \ values may be accessed via the `arguments` object in the order specified. The \ final argument will always be a callback function that must be invoked to \ signal that the script has finished. Arguments may be any JSON-primitive, array, or JSON object. JSON objects that \ define a [#WebElement_JSON_Object WebElement reference] will be converted to \ the corresponding DOM element. Likewise, any !WebElements in the script result \ will be returned to the client as [#WebElement_JSON_Object WebElement \ JSON objects].'''). AddJsonParameter('script', '{string}', 'The script to execute.'). AddJsonParameter('args', '{Array.<*>}', 'The script arguments.'). AddError('JavaScriptError', 'If the script throws an Error or if an `unload` event is ' 'fired while waiting for the script to finish.'). AddError('StaleElementReference', 'If one of the script arguments is a !WebElement that is not ' 'attached to the page\'s DOM.'). AddError('Timeout', 'If the script callback is not invoked before the timout ' 'expires. Timeouts are controlled by the ' '`/session/:sessionId/timeout/async_script` command.'). SetReturnType('{*}', 'The script result.')) resources.append( SessionResource('/session/:sessionId/screenshot'). Get('Take a screenshot of the current page.'). SetReturnType('{string}', 'The screenshot as a base64 encoded PNG.')) resources.append( SessionResource('/session/:sessionId/ime/available_engines'). Get('List all available engines on the machine. To use an engine, it has to be present in this list.'). AddError('ImeNotAvailableException', 'If the host does not support IME'). SetReturnType('{Array.<string>}', 'A list of available engines')) resources.append( SessionResource('/session/:sessionId/ime/active_engine'). Get('Get the name of the active IME engine. The name string is platform specific.'). AddError('ImeNotAvailableException', 'If the host does not support IME'). SetReturnType('{string}', 'The name of the active IME engine.')) resources.append( SessionResource('/session/:sessionId/ime/activated'). Get('Indicates whether IME input is active at the moment (not if it\'s available.'). AddError('ImeNotAvailableException', 'If the host does not support IME'). SetReturnType('{boolean}', 'true if IME input is available and currently active, false otherwise')) resources.append( SessionResource('/session/:sessionId/ime/deactivate'). Post('De-activates the currently-active IME engine.'). AddError('ImeNotAvailableException', 'If the host does not support IME')) resources.append( SessionResource('/session/:sessionId/ime/activate'). Post('''Make an engines that is available (appears on the list returned by getAvailableEngines) active. After this call, the engine will be added to the list of engines loaded in the IME daemon and the input sent using sendKeys will be converted by the active engine. Note that this is a platform-independent method of activating IME (the platform-specific way being using keyboard shortcuts'''). AddJsonParameter('engine', '{string}', 'Name of the engine to activate.'). AddError('ImeActivationFailedException', 'If the engine is not available or if the activation fails for other reasons.'). AddError('ImeNotAvailableException', 'If the host does not support IME')) resources.append( SessionResource('/session/:sessionId/frame'). Post('''Change focus to another frame on the page. If the frame ID is \ `null`, the server should switch to the page's default content.'''). AddJsonParameter('id', '{string|number|null}', 'Identifier for the frame to change focus to.'). AddError('NoSuchFrame', 'If the frame specified by `id` cannot be found.')) resources.append( SessionResource('/session/:sessionId/window'). Post('''Change focus to another window. The window to change focus to \ may be specified by its server assigned window handle, or by the value of its `name` attribute.'''). AddJsonParameter('name', '{string}', 'The window to change focus to.'). Delete('''Close the current window.'''). AddError('NoSuchWindow', 'If the window specified by `name` cannot be found.')) resources.append( SessionResource('/session/:sessionId/cookie'). Get('Retrieve all cookies visible to the current page.'). SetReturnType('{Array.<object>}', 'A list of [#Cookie_JSON_Object cookies].'). Post('''Set a cookie. If the [#Cookie_JSON_Object cookie] path is not \ specified, it should be set to `"/"`. Likewise, if the domain is omitted, it \ should default to the current page's domain.'''). AddJsonParameter('cookie', '{object}', 'A [#Cookie_JSON_Object JSON object] defining the ' 'cookie to add.'). Delete('''Delete all cookies visible to the current page.'''). AddError('InvalidCookieDomain', 'If the cookie\'s `domain` is not visible from the current page.'). AddError('UnableToSetCookie', 'If attempting to set a cookie on a page that does not support ' 'cookies (e.g. pages with mime-type `text/plain`).')) resources.append( SessionResource('/session/:sessionId/cookie/:name'). Delete('''Delete the cookie with the given name. This command should be \ a no-op if there is no such cookie visible to the current page.'''). AddUrlParameter(':name', 'The name of the cookie to delete.')) resources.append( SessionResource('/session/:sessionId/source'). Get('Get the current page source.'). SetReturnType('{string}', 'The current page source.')) resources.append( SessionResource('/session/:sessionId/title'). Get('Get the current page title.'). SetReturnType('{string}', 'The current page title.')) resources.append( SessionResource('/session/:sessionId/element'). Post('''Search for an element on the page, starting from the document \ root. The located element will be returned as a WebElement JSON object. \ The table below lists the locator strategies that each server should support. \ Each locator must return the first matching element located in the DOM. || *Strategy* || *Description* || || class name || Returns an element whose class name contains the search \ value; compound class names are not permitted. || || css selector || Returns an element matching a CSS selector. || || id || Returns an element whose ID attribute matches the search value. || || name || Returns an element whose NAME attribute matches the search value. || || link text || Returns an anchor element whose visible text matches the \ search value. || || partial link text || Returns an anchor element whose visible text \ partially matches the search value. || || tag name || Returns an element whose tag name matches the search value. || || xpath || Returns an element matching an XPath expression. || '''). AddJsonParameter('using', '{string}', 'The locator strategy to use.'). AddJsonParameter('value', '{string}', 'The The search target.'). SetReturnType('{ELEMENT:string}', 'A WebElement JSON object for the located element.'). AddError('XPathLookupError', 'If using XPath and the input expression is invalid.'). AddError('NoSuchElement', 'If the element cannot be found.')) resources.append( SessionResource('/session/:sessionId/elements'). Post('''Search for multiple elements on the page, starting from the \ document root. The located elements will be returned as a WebElement JSON \ objects. The table below lists the locator strategies that each server should \ support. Elements should be returned in the order located in the DOM. || *Strategy* || *Description* || || class name || Returns all elements whose class name contains the search \ value; compound class names are not permitted. || || css selector || Returns all elements matching a CSS selector. || || id || Returns all elements whose ID attribute matches the search value. || || name || Returns all elements whose NAME attribute matches the search value. || || link text || Returns all anchor elements whose visible text matches the \ search value. || || partial link text || Returns all anchor elements whose visible text \ partially matches the search value. || || tag name || Returns all elements whose tag name matches the search value. || || xpath || Returns all elements matching an XPath expression. || '''). AddJsonParameter('using', '{string}', 'The locator strategy to use.'). AddJsonParameter('value', '{string}', 'The The search target.'). SetReturnType('{Array.<{ELEMENT:string}>}', 'A list of WebElement JSON objects for the located elements.'). AddError('XPathLookupError', 'If using XPath and the input expression is invalid.')) resources.append( SessionResource('/session/:sessionId/element/active'). Post('Get the element on the page that currently has focus. The element will be returned as ' 'a WebElement JSON object.'). SetReturnType('{ELEMENT:string}', 'A WebElement JSON object for the active element.')) resources.append( ElementResource('/session/:sessionId/element/:id'). Get('''Describe the identified element. *Note:* This command is reserved for future use; its return type is currently \ undefined.''')) resources.append( ElementResource('/session/:sessionId/element/:id/element'). Post('''Search for an element on the page, starting from the identified \ element. The located element will be returned as a WebElement JSON object. \ The table below lists the locator strategies that each server should support. \ Each locator must return the first matching element located in the DOM. || *Strategy* || *Description* || || class name || Returns an element whose class name contains the search \ value; compound class names are not permitted. || || css selector || Returns an element matching a CSS selector. || || id || Returns an element whose ID attribute matches the search value. || || name || Returns an element whose NAME attribute matches the search value. || || link text || Returns an anchor element whose visible text matches the \ search value. || || partial link text || Returns an anchor element whose visible text \ partially matches the search value. || || tag name || Returns an element whose tag name matches the search value. || || xpath || Returns an element matching an XPath expression. The provided \ XPath expression must be applied to the server "as is"; if the expression is \ not relative to the element root, the server should not modify it. \ Consequently, an XPath query may return elements not contained in the root \ element's subtree. || '''). AddJsonParameter('using', '{string}', 'The locator strategy to use.'). AddJsonParameter('value', '{string}', 'The The search target.'). SetReturnType('{ELEMENT:string}', 'A WebElement JSON object for the located element.'). AddError('NoSuchElement', 'If the element cannot be found.'). AddError('XPathLookupError', 'If using XPath and the input expression is invalid.')) resources.append( ElementResource('/session/:sessionId/element/:id/elements'). Post('''Search for multiple elements on the page, starting from the \ identified element. The located elements will be returned as a WebElement \ JSON objects. The table below lists the locator strategies that each server \ should support. Elements should be returned in the order located in the DOM. || *Strategy* || *Description* || || class name || Returns all elements whose class name contains the search \ value; compound class names are not permitted. || || css selector || Returns all elements matching a CSS selector. || || id || Returns all elements whose ID attribute matches the search value. || || name || Returns all elements whose NAME attribute matches the search value. || || link text || Returns all anchor elements whose visible text matches the \ search value. || || partial link text || Returns all anchor elements whose visible text \ partially matches the search value. || || tag name || Returns all elements whose tag name matches the search value. || || xpath || Returns all elements matching an XPath expression. The provided \ XPath expression must be applied to the server "as is"; if the expression is \ not relative to the element root, the server should not modify it. \ Consequently, an XPath query may return elements not contained in the root \ element's subtree. || '''). AddJsonParameter('using', '{string}', 'The locator strategy to use.'). AddJsonParameter('value', '{string}', 'The The search target.'). SetReturnType('{Array.<{ELEMENT:string}>}', 'A list of WebElement JSON objects for the located elements.'). AddError('XPathLookupError', 'If using XPath and the input expression is invalid.')) resources.append( ElementResource('/session/:sessionId/element/:id/click'). Post('Click on an element.'). RequiresVisibility()) resources.append( ElementResource('/session/:sessionId/element/:id/submit'). Post('Submit a `FORM` element. The submit command may also be applied to any element that is ' 'a descendant of a `FORM` element.')) resources.append( ElementResource('/session/:sessionId/element/:id/text'). Get('Returns the visible text for the element.')) resources.append( ElementResource('/session/:sessionId/element/:id/value'). Get('Query for the value of an element, as determined by its `value` attribute.'). SetReturnType('{string|null}', 'The element\'s value, or `null` if it does not have a `value` attribute.'). Post('''Send a sequence of key strokes to an element. Any UTF-8 character may be specified, however, if the server does not support \ native key events, it should simulate key strokes for a standard US keyboard \ layout. The Unicode [http://unicode.org/faq/casemap_charprop.html#8 Private Use\ Area] code points, 0xE000-0xF8FF, are used to represent pressable, non-text \ keys (see table below). <table cellspacing=5 cellpadding=5> <tbody><tr><td valign=top> || *Key* || *Code* || || NULL || U+E000 || || Cancel || U+E001 || || Help || U+E002 || || Back space || U+E003 || || Tab || U+E004 || || Clear || U+E005 || || Return^1^ || U+E006 || || Enter^1^ || U+E007 || || Shift || U+E008 || || Control || U+E009 || || Alt || U+E00A || || Pause || U+E00B || || Escape || U+E00C || </td><td valign=top> || *Key* || *Code* || || Space || U+E00D || || Pageup || U+E00E || || Pagedown || U+E00F || || End || U+E010 || || Home || U+E011 || || Left arrow || U+E012 || || Up arrow || U+E013 || || Right arrow || U+E014 || || Down arrow || U+E015 || || Insert || U+E016 || || Delete || U+E017 || || Semicolon || U+E018 || || Equals || U+E019 || </td><td valign=top> || *Key* || *Code* || || Numpad 0 || U+E01A || || Numpad 1 || U+E01B || || Numpad 2 || U+E01C || || Numpad 3 || U+E01D || || Numpad 4 || U+E01E || || Numpad 5 || U+E01F || || Numpad 6 || U+E020 || || Numpad 7 || U+E021 || || Numpad 8 || U+E022 || || Numpad 9 || U+E023 || </td><td valign=top> || *Key* || *Code* || || Multiply || U+E024 || || Add || U+E025 || || Separator || U+E026 || || Subtract || U+E027 || || Decimal || U+E028 || || Divide || U+E029 || </td><td valign=top> || *Key* || *Code* || || F1 || U+E031 || || F2 || U+E032 || || F3 || U+E033 || || F4 || U+E034 || || F5 || U+E035 || || F6 || U+E036 || || F7 || U+E037 || || F8 || U+E038 || || F9 || U+E039 || || F10 || U+E03A || || F11 || U+E03B || || F12 || U+E03C || || Command/Meta || U+E03D || </td></tr> <tr><td colspan=5>^1^ The return key is _not the same_ as the \ [http://en.wikipedia.org/wiki/Enter_key enter key].</td></tr></tbody></table> The server must process the key sequence as follows: * Each key that appears on the keyboard without requiring modifiers are sent \ as a keydown followed by a key up. * If the server does not support native events and must simulate key strokes \ with !JavaScript, it must generate keydown, keypress, and keyup events, in that\ order. The keypress event should only be fired when the corresponding key is \ for a printable character. * If a key requires a modifier key (e.g. "!" on a standard US keyboard), the \ sequence is: <var>modifier</var> down, <var>key</var> down, <var>key</var> up, \ <var>modifier</var> up, where <var>key</var> is the ideal unmodified key value \ (using the previous example, a "1"). * Modifier keys (Ctrl, Shift, Alt, and Command/Meta) are assumed to be \ "sticky"; each modifier should be held down (e.g. only a keydown event) until \ either the modifier is encountered again in the sequence, or the `NULL` \ (U+E000) key is encountered. * Each key sequence is terminated with an implicit `NULL` key. Subsequently, \ all depressed modifier keys must be released (with corresponding keyup events) \ at the end of the sequence. '''). RequiresVisibility(). AddJsonParameter('value', '{Array.<string>}', 'The sequence of keys to type. An array must be provided. ' 'The server should flatten the array items to a single ' 'string to be typed.')) resources.append( SessionResource('/session/:sessionId/modifier'). Post('Send an event to the active element to depress or release a ' 'modifier key.'). AddJsonParameter('value', '{string}', 'The modifier key event to be sent. This key must be one' ' Ctrl, Shift, Alt, or Command/Meta, as defined by the ' '[JsonWireProtocol#/session/:sessionId/element/:id/value' ' send keys] command.'). AddJsonParameter('isdown', '{boolean}', 'Whether to generate a key down or key up.')) resources.append( ElementResource('/session/:sessionId/element/:id/name'). Get('Query for an element\'s tag name.'). SetReturnType('{string}', 'The element\'s tag name, as a lowercase string.')) resources.append( ElementResource('/session/:sessionId/element/:id/clear'). Post('Clear a `TEXTAREA` or `text INPUT` element\'s value.'). RequiresVisibility(). RequiresEnabledState()) resources.append( ElementResource('/session/:sessionId/element/:id/selected'). Get('Determine if an `OPTION` element, or an `INPUT` element of type `checkbox` or ' '`radiobutton` is currently selected.'). SetReturnType('{boolean}', 'Whether the element is selected.'). Post('Select an `OPTION` element, or an `INPUT` element of type `checkbox` or `radiobutton`.'). RequiresVisibility(). RequiresEnabledState(). AddError('ElementIsNotSelectable', 'If the referenced element cannot be selected.')) resources.append( ElementResource('/session/:sessionId/element/:id/toggle'). Post('Toggle whether an `OPTION` element, or an `INPUT` element of type `checkbox` or ' '`radiobutton` is currently selected.'). RequiresVisibility(). RequiresEnabledState(). AddError('ElementIsNotSelectable', 'If the referenced element cannot be selected.'). SetReturnType('{boolean}', 'Whether the element is selected after toggling its state.')) resources.append( ElementResource('/session/:sessionId/element/:id/enabled'). Get('Determine if an element is currently enabled.'). SetReturnType('{boolean}', 'Whether the element is enabled.')) resources.append( ElementResource('/session/:sessionId/element/:id/attribute/:name'). Get('Get the value of an element\'s attribute.'). SetReturnType('{string|null}', 'The value of the attribute, or null if it is not set on the element.')) resources.append( ElementResource('/session/:sessionId/element/:id/equals/:other'). Get('Test if two element IDs refer to the same DOM element.'). AddUrlParameter(':other', 'ID of the element to compare against.'). SetReturnType('{boolean}', 'Whether the two IDs refer to the same element.'). AddError('StaleElementReference', 'If either the element refered to by `:id` or `:other` is no ' 'longer attached to the page\'s DOM.')) resources.append( ElementResource('/session/:sessionId/element/:id/displayed'). Get('Determine if an element is currently displayed.'). SetReturnType('{boolean}', 'Whether the element is displayed.')) resources.append( ElementResource('/session/:sessionId/element/:id/location'). Get('Determine an element\'s location on the page. The point `(0, 0)` refers to the ' 'upper-left corner of the page. The element\'s coordinates are returned as a JSON object ' 'with `x` and `y` properties.'). SetReturnType('{x:number, y:number}', 'The X and Y coordinates for the element on the page.')) resources.append( ElementResource('/session/:sessionId/element/:id/location_in_view'). Get('''Determine an element\'s location on the screen once it has been \ scrolled into view. *Note:* This is considered an internal command and should *only* be used to \ determine an element's location for correctly generating native events.'''). SetReturnType('{x:number, y:number}', 'The X and Y coordinates for the element.')) resources.append( ElementResource('/session/:sessionId/element/:id/size'). Get('Determine an element\'s size in pixels. The size will be returned as a JSON object ' ' with `width` and `height` properties.'). SetReturnType('{width:number, height:number}', 'The width and height of the element, in pixels.')) resources.append( ElementResource('/session/:sessionId/element/:id/css/:propertyName'). Get('Query the value of an element\'s computed CSS property. The CSS property to query should' ' be specified using the CSS property name, *not* the !JavaScript property name (e.g. ' '`background-color` instead of `backgroundColor`).'). SetReturnType('{string}', 'The value of the specified CSS property.')) resources.append( ElementResource('/session/:sessionId/element/:id/hover'). Post('Move the mouse over an element.'). RequiresVisibility(). RequiresEnabledState()) resources.append( ElementResource('/session/:sessionId/element/:id/drag'). Post('Drag and drop an element. The distance to drag an element should be specified relative ' 'to the upper-left corner of the page.'). RequiresVisibility(). RequiresEnabledState(). AddJsonParameter('x', '{number}', 'The number of pixels to drag the element in the horizontal direction. ' 'A positive value indicates the element should be dragged to the right, ' 'while a negative value indicates that it should be dragged to the left.'). AddJsonParameter('y', '{number}', 'The number of pixels to drag the element in the vertical direction. ' 'A positive value indicates the element should be dragged down towards the ' 'bottom of the screen, while a negative value indicates that it should be ' 'dragged towards the top of the screen.')) resources.append( SessionResource('/session/:sessionId/orientation'). Get('Get the current browser orientation. The server should return a ' 'valid orientation value as defined in [http://selenium.googlecode.' 'com/svn/trunk/docs/api/java/org/openqa/selenium/ScreenOrientation' '.html ScreenOrientation]: `{LANDSCAPE|PORTRAIT}`.'). SetReturnType('{string}', 'The current browser orientation corresponding' ' to a value defined in [http://selenium.googlecode.com/' 'svn/trunk/docs/api/java/org/openqa/selenium/' 'ScreenOrientation.html ScreenOrientation]: ' '`{LANDSCAPE|PORTRAIT}`.'). Post('Set the browser orientation. The orientation should be specified ' 'as defined in [http://selenium.googlecode.com/svn/trunk/docs/api/' 'java/org/openqa/selenium/ScreenOrientation.html ScreenOrientation]' ': `{LANDSCAPE|PORTRAIT}`.'). AddJsonParameter('orientation', '{string}', 'The new browser orientation as defined in ' '[http://selenium.googlecode.com/svn/trunk/docs/api/' 'java/org/openqa/selenium/ScreenOrientation.html ' 'ScreenOrientation]: `{LANDSCAPE|PORTRAIT}`.')) resources.append( SessionResource('/session/:sessionId/alert_text'). Get('Gets the text of the currently displayed JavaScript `alert()`, `confirm()`, ' 'or `prompt()` dialog.'). SetReturnType('{string}', 'The text of the currently displayed alert.'). AddError('NoAlertPresent', 'If there is no alert displayed.'). Post('Sends keystrokes to a JavaScript `prompt()` dialog.'). AddJsonParameter('keysToSend', '{string}', 'Keystrokes to send to the `prompt()` dialog.'). AddError('NoAlertPresent', 'If there is no alert displayed.')) resources.append( SessionResource('/session/:sessionId/accept_alert'). Post('Accepts the currently displayed alert dialog. Usually, this is equivalent ' 'to clicking on the \'OK\' button in the dialog.'). AddError('NoAlertPresent', 'If there is no alert displayed.')) resources.append( SessionResource('/session/:sessionId/dismiss_alert'). Post('Dismisses the currently displayed alert dialog. For `confirm()` and `prompt()` ' 'dialogs, this is equivalent to clicking the \'Cancel\' button. For `alert()` ' 'dialogs, this is equivalent to clicking the \'OK\' button.'). AddError('NoAlertPresent', 'If there is no alert displayed.')) resources.append( SessionResource('/session/:sessionId/moveto'). Post('Move the mouse by an offset of the specificed element. If no element ' 'is specified, the move is relative to the current mouse cursor. If an ' 'element is provided but no offset, the mouse will be moved to the center' ' of the element. If the element is not visible, it will be scrolled into view.'). AddJsonParameter('element', '{string}', 'ID of the element to move to. If not specified' ' or is null, the offset is relative to current position of the mouse.'). AddJsonParameter('xoffset', '{number}', 'X offset to move to, relative to the top-left ' 'corner of the element. If not specified, the mouse' ' will move to the middle of the element.'). AddJsonParameter('yoffset', '{number}', 'Y offset to move to, relative to the top-left ' 'corner of the element. If not specified, the mouse' ' will move to the middle of the element.')) resources.append( SessionResource('/session/:sessionId/click'). Post('Click any mouse button (at the coordinates set by the last moveto command). Note ' 'that calling this command after calling buttondown and before calling button up ' '(or any out-of-order interactions sequence) will yield undefined behaviour).'). AddJsonParameter('button', '{number}', 'Which button, enum: `{LEFT = 0, MIDDLE = 1 ' ', RIGHT = 2}`. Defaults to the left mouse button if not specified.')) resources.append( SessionResource('/session/:sessionId/buttondown'). Post('Click and hold the left mouse button (at the coordinates set by the last moveto ' 'command). Note that the next mouse-related command that should follow is buttondown' ' . Any other mouse command (such as click or another call to buttondown) will yield' ' undefined behaviour.')) resources.append( SessionResource('/session/:sessionId/buttonup'). Post('Releases the mouse button previously held (where the mouse is currently at). ' 'Must be called once for every buttondown command issued. See the note in click and ' 'buttondown about implications of out-of-order commands.')) resources.append( SessionResource('/session/:sessionId/doubleclick'). Post('Double-clicks at the current mouse coordinates (set by moveto).')) print '''#summary A description of the protocol used by WebDriver to \ communicate with remote instances #labels WebDriver <wiki:comment> ======================================================== ======================================================== DO NOT EDIT THIS WIKI PAGE THROUGH THE UI. Instead, use http://selenium.googlecode.com/svn/trunk/wire.py $ svn co https://selenium.googlecode.com/svn/ --depth=empty wire_protocol $ cd wire_protocol $ svn update --depth=infinity ./wiki $ svn update --depth=files ./trunk # modify ./trunk/wire.py $ python ./trunk/wire.py > ./wiki/JsonWireProtocol.wiki $ svn commit ./trunk/wire.py ./wiki/JsonWireProtocol.wiki ======================================================== ======================================================== </wiki:comment> <font size=6>*The !WebDriver Wire Protocol*</font> <font size=3>*Status:* _DRAFT_</font> <wiki:toc max_depth="3" /> = Introduction = All implementations of WebDriver that communicate with the browser, or a \ RemoteWebDriver server shall use a common wire protocol. This wire protocol \ defines a [http://www.google.com?q=RESTful+web+service RESTful web service] \ using [http://www.json.org JSON] over HTTP. The protocol will assume that the WebDriver API has been "flattened", but there\ is an expectation that client implementations will take a more Object-Oriented\ approach, as demonstrated in the existing Java API. The wire protocol is\ implemented in request/response pairs of "commands" and "responses". == Basic Terms and Concepts == <dl> <dt> ==== Client ==== </dt> <dd>The machine on which the !WebDriver API is being used. </dd> <dt> ==== Server ==== </dt> <dd>The machine running the RemoteWebDriver. This term may also refer to a \ specific browser that implements the wire protocol directly, such as the \ FirefoxDriver or IPhoneDriver. </dd> <dt> ==== Session ==== </dt> <dd>The server should maintain one browser per session. Commands sent to a \ session will be directed to the corresponding browser. </dd> <dt> ==== !WebElement ==== </dt> <dd>An object in the !WebDriver API that represents a DOM element on the page. </dd> <dt> ==== !WebElement JSON Object ==== </dt> <dd>The JSON representation of a !WebElement for transmission over the wire. \ This object will have the following properties: || *Key* || *Type* || *Description* || || ELEMENT || string || The opaque ID assigned to the element by the server. \ This ID should be used in all subsequent commands issued against the element. || </dd> <dt> ==== Capabilities JSON Object ==== </dt> <dd>Not all server implementations will support every !WebDriver feature. \ Therefore, the client and server should use JSON objects with the properties \ listed below when describing which features a session supports. || *Key* || *Type* || *Description* || || browserName || string || The name of the browser being used; should be one \ of `{chrome|firefox|htmlunit|internet explorer|iphone}`. || || version || string || The browser version, or the empty string if unknown. || || platform || string || A key specifying which platform the browser is running \ on. This value should be one of `{WINDOWS|XP|VISTA|MAC|LINUX|UNIX}`. When \ requesting a new session, the client may specify `ANY` to indicate any \ available platform may be used. || || javascriptEnabled || boolean || Whether the session supports executing user \ supplied JavaScript in the context of the current page. || || takesScreenshot || boolean || Whether the session supports taking \ screenshots of the current page. || || handlesAlerts || boolean || Whether the session can interact with modal \ popups, such as `window.alert` and `window.confirm`. || || databaseEnabled || boolean || Whether the session can interact \ database storage. || || locationContextEnabled || boolean || Whether the session can set and query \ the browser's location context. || || applicationCacheEnabled || boolean || Whether the session can interact with \ the application cache. || || browserConnectionEnabled || boolean || Whether the session can query for \ the browser's connectivity and disable it if desired. || || cssSelectorsEnabled || boolean || Whether the session supports CSS \ selectors when searching for elements. || || webStorageEnabled || boolean || Whether the session supports interactions \ with [http://www.w3.org/TR/2009/WD-webstorage-20091029/ storage objects]. || || rotatable || boolean || Whether the session can rotate the current page's \ current layout between portrait and landscape orientations (only applies to \ mobile platforms). || || acceptSslCerts || boolean || Whether the session should accept all SSL \ certs by default. || || nativeEvents || boolean || Whether the session is capable of generating \ native events when simulating user input. || </dd> <dt> ==== Desired Capabilities ==== </dt> <dd>A Capabilities JSON Object sent by the client describing the capabilities \ a new session created by the server should possess. Any omitted keys implicitly \ indicate the corresponding capability is irrelevant.</dd> <dt> ==== Actual Capabilities ==== </dt> <dd>A Capabilities JSON Object returned by the server describing what \ features a session actually supports. Any omitted keys implicitly indicate \ the corresponding capability is not supported.</dd> <dt> ==== Cookie JSON Object ==== </dt> <dd> A JSON object describing a Cookie. || *Key* || *Type* || *Description* || || name || string || The name of the cookie. || || value || string || The cookie value. || || path || string || (Optional) The cookie path.^1^ || || domain || string || (Optional) The domain the cookie is visible to.^1^ || || secure || boolean || (Optional) Whether the cookie is a secure cookie.^1^ || || expiry || number || (Optional) When the cookie expires, specified in \ seconds since midnight, January 1, 1970 UTC.^1^ || ^1^ When returning Cookie objects, the server should only omit an optional \ field if it is incapable of providing the information.</dd> </dl> = Messages = == Commands == !WebDriver command messages should conform to the [http://www.w3.org/Protocols/\ rfc2616/rfc2616-sec5.html#sec5 HTTP/1.1 request specification]. Although the \ server may be extended to respond to other content-types, the wire protocol \ dictates that all commands accept a content-type of \ `application/json;charset=UTF-8`. Likewise, the message bodies for POST and PUT\ request must use an `application/json;charset=UTF-8` content-type. Each command in the WebDriver service will be mapped to an HTTP method at a \ specific path. Path segments prefixed with a colon (:) indicate that segment \ is a variable used to further identify the underlying resource. For example, \ consider an arbitrary resource mapped as: {{{ GET /favorite/color/:name }}} Given this mapping, the server should respond to GET requests sent to \ "/favorite/color/Jack" and "/favorite/color/Jill", with the variable `:name` \ set to "Jack" and "Jill", respectively. == Responses == Command responses shall be sent as \ [http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6 HTTP/1.1 response \ messages]. If the remote server must return a 4xx response, the response body \ shall have a Content-Type of text/plain and the message body shall be a \ descriptive message of the bad request. For all other cases, if a response \ includes a message body, it must have a Content-Type of \ application/json;charset=UTF-8 and will be a JSON object with the following \ properties: || *Key* || *Type* || *Description* || || sessionId || string|null || An opaque handle used by the server to \ determine where to route session-specific commands. This ID should be included \ in all future session-commands in place of the :sessionId path segment \ variable. || || status || number || A status code summarizing the result of the command. \ A non-zero value indicates that the command failed. || || value || `*` || The response JSON value. || === Response Status Codes === The wire protocol will inherit its status codes from those used by the \ InternetExplorerDriver: || *Code* || *Summary* || *Detail* || || 0 || `Success` || The command executed successfully. || || 7 || `NoSuchElement` || An element could not be located on the page using \ the given search parameters. || || 8 || `NoSuchFrame` || A request to switch to a frame could not be \ satisfied because the frame could not be found. || || 9 || `UnknownCommand` || The requested resource could not be found, or a \ request was received using an HTTP method that is not supported by the mapped \ resource. || || 10 || `StaleElementReference` || An element command failed because the \ referenced element is no longer attached to the DOM. || || 11 || `ElementNotVisible` || An element command could not be completed \ because the element is not visible on the page. || || 12 || `InvalidElementState` || An element command could not be completed \ because the element is in an invalid state (e.g. attempting to click a \ disabled element). || || 13 || `UnknownError` || An unknown server-side error occurred while \ processing the command. || || 15 || `ElementIsNotSelectable` || An attempt was made to select an element \ that cannot be selected. || || 17 || `JavaScriptError` || An error occurred while executing user supplied \ !JavaScript. || || 19 || `XPathLookupError` || An error occurred while searching for an \ element by XPath. || || 23 || `NoSuchWindow` || A request to switch to a different window could \ not be satisfied because the window could not be found. || || 24 || `InvalidCookieDomain` || An illegal attempt was made to set a cookie \ under a different domain than the current page. || || 25 || `UnableToSetCookie` || A request to set a cookie's value could not \ be satisfied. || || 28 || `Timeout` || A command did not complete before its timeout expired. || The client should interpret a 404 Not Found response from the server as an \ "Unknown command" response. All other 4xx and 5xx responses from the server \ that do not define a status field should be interpreted as "Unknown error" \ responses. == Error Handling == There are two levels of error handling specified by the wire protocol: invalid \ requests and failed commands. === Invalid Requests === All invalid requests should result in the server returning a 4xx HTTP \ response. The response Content-Type should be set to text/plain and the \ message body should be a descriptive error message. The categories of invalid \ requests are as follows: <dl> <dt>*Unknown Commands*</dt> <dd>If the server receives a command request whose path is not mapped to a \ resource in the REST service, it should respond with a `404 Not Found` message. </dd> <dt>*Unimplemented Commands*</dt> <dd>Every server implementing the WebDriver wire protocol must respond to \ every defined command. If an individual command has not been implemented on \ the server, the server should respond with a `501 Not Implemented` error \ message. Note this is the only error in the Invalid Request category that does \ not return a `4xx` status code. </dd> <dt>*Variable Resource Not Found*</dt> <dd>If a request path maps to a variable resource, but that resource does not \ exist, then the server should respond with a `404 Not Found`. For example, if \ ID `my-session` is not a valid session ID on the server, and a command is sent \ to `GET /session/my-session HTTP/1.1`, then the server should gracefully \ return a `404`. </dd> <dt>*Invalid Command Method*</dt> <dd>If a request path maps to a valid resource, but that resource does not \ respond to the request method, the server should respond with a `405 Method \ Not Allowed`. The response must include an Allows header with a list of the \ allowed methods for the requested resource. </dd> <dt>*Missing Command Parameters*</dt> <dd>If a POST/PUT command maps to a resource that expects a set of JSON \ parameters, and the response body does not include one of those parameters, \ the server should respond with a `400 Bad Request`. The response body should \ list the missing parameters. </dd> </dl> === Failed Commands === If a request maps to a valid command and contains all of the expected \ parameters in the request body, yet fails to execute successfully, then the \ server should send a 500 Internal Server Error. This response should have a \ Content-Type of `application/json;charset=UTF-8` and the response body should \ be a well formed JSON response object. The response status should be one of the defined status codes and the response \ value should be another JSON object with detailed information for the failing \ command: || Key || Type || Description || || message || string || A descriptive message for the command failure. || || screen || string || (Optional) If included, a screenshot of the current \ page as a base64 encoded string. || || class || string || (Optional) If included, specifies the fully qualified \ class name for the exception that was thrown when the command failed. || || stackTrace || array || (Optional) If included, specifies an array of JSON \ objects describing the stack trace for the exception that was thrown when the \ command failed. The zeroeth element of the array represents the top of the \ stack. || Each JSON object in the stackTrace array must contain the following properties: || *Key* || *Type* || *Description* || || fileName || string || The name of the source file containing the line \ represented by this frame. || || className || string || The fully qualified class name for the class active \ in this frame. If the class name cannot be determined, or is not applicable \ for the language the server is implemented in, then this property should be \ set to the empty string. || || methodName || string || The name of the method active in this frame, or \ the empty string if unknown/not applicable. || || lineNumber || number || The line number in the original source file for the \ frame, or 0 if unknown. || = Resource Mapping = Resources in the WebDriver REST service are mapped to individual URL patterns. \ Each resource may respond to one or more HTTP request methods. If a resource \ responds to a GET request, then it should also respond to HEAD requests. All \ resources should respond to OPTIONS requests with an `Allow` header field, \ whose value is a list of all methods that resource responds to. If a resource is mapped to a URL containing a variable path segment name, that \ path segment should be used to further route the request. Variable path \ segments are indicated in the resource mapping by a colon-prefix. For example, \ consider the following: {{{ /favorite/color/:person }}} A resource mapped to this URL should parse the value of the `:person` path \ segment to further determine how to respond to the request. If this resource \ received a request for `/favorite/color/Jack`, then it should return Jack's \ favorite color. Likewise, the server should return Jill's favorite color for \ any requests to `/favorite/color/Jill`. Two resources may only be mapped to the same URL pattern if one of those \ resources' patterns contains variable path segments, and the other does not. In\ these cases, the server should always route requests to the resource whose \ path is the best match for the request. Consider the following two resource \ paths: # `/session/:sessionId/element/active` # `/session/:sessionId/element/:id` Given these mappings, the server should always route requests whose final path \ segment is active to the first resource. All other requests should be routed to\ second. = Command Reference = == Command Summary == || *HTTP Method* || *Path* || *Summary* || %s == Command Detail == %s''' % (''.join(r.ToWikiTableString() for r in resources), '\n----\n\n'.join(r.ToWikiString() for r in resources)) if __name__ == '__main__': main()
akiellor/selenium
wire.py
Python
apache-2.0
58,502
# THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE. # Copyright (C) NIWA & British Crown (Met Office) & Contributors. # # 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 os from pathlib import Path from typing import Any, Optional, List import pytest from cylc.flow.scripts.config import get_config_file_hierarchy from cylc.flow.cfgspec.globalcfg import GlobalConfig Fixture = Any HOME: str = str(Path('~').expanduser()) @pytest.fixture def conf_env(monkeypatch): """Clear any env vars that affect which conf files get loaded. Return a convenience function for setting environment variables. """ # wipe any cached config monkeypatch.setattr( GlobalConfig, '_DEFAULT', None, ) for envvar in ('CYLC_SITE_CONF_PATH', 'CYLC_CONF_PATH'): if envvar in os.environ: monkeypatch.delenv(envvar) def _set_env(key, value): if value: monkeypatch.setenv(key, value) return _set_env @pytest.fixture def dummy_version_hierarchy(monkeypatch): """Set the config version hierarchy.""" monkeypatch.setattr( 'cylc.flow.cfgspec.globalcfg.GlobalConfig.VERSION_HIERARCHY', ['', '1', '1.0'] ) @pytest.fixture def capload(monkeypatch): """Capture configuration load events. This prevents actual file loading. If the file name contains the string "invalid" it will not appear in the results as if it diddn't exist on the filesystem. """ files = [] def _capload(glblcfg, fname, _): nonlocal files if 'invalid' not in fname: # if the file is called invalid skip it # this is to replicate the behaviour of skipping files that # don't exist files.append(fname.replace(HOME, '~')) monkeypatch.setattr( GlobalConfig, '_load', _capload ) return files def test_get_config_file_hierarchy_global( monkeypatch: Fixture, conf_env: Fixture, capload: Fixture, dummy_version_hierarchy: Fixture ): """Test get_config_file_hierarchy() for the global hierarchy only.""" assert [ path.replace(HOME, '~') for path in get_config_file_hierarchy() ] == [ '/etc/cylc/flow/global.cylc', '/etc/cylc/flow/1/global.cylc', '/etc/cylc/flow/1.0/global.cylc', '~/.cylc/flow/global.cylc', '~/.cylc/flow/1/global.cylc', '~/.cylc/flow/1.0/global.cylc' ] @pytest.mark.parametrize( 'conf_path,site_conf_path,files', [ pytest.param( None, None, [ '/etc/cylc/flow/global.cylc', '/etc/cylc/flow/1/global.cylc', '/etc/cylc/flow/1.0/global.cylc', '~/.cylc/flow/global.cylc', '~/.cylc/flow/1/global.cylc', '~/.cylc/flow/1.0/global.cylc', ], id='(default)' ), pytest.param( None, '<path>', [ '<path>/flow/global.cylc', '<path>/flow/1/global.cylc', '<path>/flow/1.0/global.cylc', '~/.cylc/flow/global.cylc', '~/.cylc/flow/1/global.cylc', '~/.cylc/flow/1.0/global.cylc', ], id='CYLC_SITE_CONF_PATH=valid' ), pytest.param( None, 'invalid', [ '~/.cylc/flow/global.cylc', '~/.cylc/flow/1/global.cylc', '~/.cylc/flow/1.0/global.cylc', ], id='CYLC_SITE_CONF_PATH=invalid' ), pytest.param( '<path>', None, ['<path>/global.cylc'], id='CYLC_CONF_PATH=valid' ), pytest.param( 'invalid', None, [], id='CYLC_CONF_PATH=invalid' ), pytest.param( '<path1>', '<path2>', ['<path1>/global.cylc'], # should ignore CYLC_SITE_CONF_PATH id='CYLC_CONF_PATH=valid, CYLC_SITE_CONF_PATH=valid' ), pytest.param( 'invalid', '<path>', [], id='CYLC_CONF_PATH=invalid, CYLC_SITE_CONF_PATH=valid' ), ] ) def test_cylc_site_conf_path_env_var( monkeypatch: Fixture, conf_env: Fixture, capload: Fixture, dummy_version_hierarchy: Fixture, conf_path: Optional[str], site_conf_path: Optional[str], files: List[str], ): """Test that the right files are loaded according to env vars.""" # set the relevant environment variables conf_env('CYLC_CONF_PATH', conf_path) conf_env('CYLC_SITE_CONF_PATH', site_conf_path) # load the global config GlobalConfig.get_inst() assert capload == files
hjoliver/cylc
tests/unit/scripts/test_config.py
Python
gpl-3.0
5,439
"""Support for the DOODS service.""" import io import logging import time import voluptuous as vol from PIL import Image, ImageDraw from pydoods import PyDOODS from homeassistant.const import CONF_TIMEOUT from homeassistant.components.image_processing import ( CONF_CONFIDENCE, CONF_ENTITY_ID, CONF_NAME, CONF_SOURCE, PLATFORM_SCHEMA, ImageProcessingEntity, draw_box, ) from homeassistant.core import split_entity_id from homeassistant.helpers import template import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) ATTR_MATCHES = "matches" ATTR_SUMMARY = "summary" ATTR_TOTAL_MATCHES = "total_matches" CONF_URL = "url" CONF_AUTH_KEY = "auth_key" CONF_DETECTOR = "detector" CONF_LABELS = "labels" CONF_AREA = "area" CONF_COVERS = "covers" CONF_TOP = "top" CONF_BOTTOM = "bottom" CONF_RIGHT = "right" CONF_LEFT = "left" CONF_FILE_OUT = "file_out" AREA_SCHEMA = vol.Schema( { vol.Optional(CONF_BOTTOM, default=1): cv.small_float, vol.Optional(CONF_LEFT, default=0): cv.small_float, vol.Optional(CONF_RIGHT, default=1): cv.small_float, vol.Optional(CONF_TOP, default=0): cv.small_float, vol.Optional(CONF_COVERS, default=True): cv.boolean, } ) LABEL_SCHEMA = vol.Schema( { vol.Required(CONF_NAME): cv.string, vol.Optional(CONF_AREA): AREA_SCHEMA, vol.Optional(CONF_CONFIDENCE): vol.Range(min=0, max=100), } ) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_URL): cv.string, vol.Required(CONF_DETECTOR): cv.string, vol.Required(CONF_TIMEOUT, default=90): cv.positive_int, vol.Optional(CONF_AUTH_KEY, default=""): cv.string, vol.Optional(CONF_FILE_OUT, default=[]): vol.All(cv.ensure_list, [cv.template]), vol.Optional(CONF_CONFIDENCE, default=0.0): vol.Range(min=0, max=100), vol.Optional(CONF_LABELS, default=[]): vol.All( cv.ensure_list, [vol.Any(cv.string, LABEL_SCHEMA)] ), vol.Optional(CONF_AREA): AREA_SCHEMA, } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Doods client.""" url = config[CONF_URL] auth_key = config[CONF_AUTH_KEY] detector_name = config[CONF_DETECTOR] timeout = config[CONF_TIMEOUT] doods = PyDOODS(url, auth_key, timeout) response = doods.get_detectors() if not isinstance(response, dict): _LOGGER.warning("Could not connect to doods server: %s", url) return detector = {} for server_detector in response["detectors"]: if server_detector["name"] == detector_name: detector = server_detector break if not detector: _LOGGER.warning( "Detector %s is not supported by doods server %s", detector_name, url ) return entities = [] for camera in config[CONF_SOURCE]: entities.append( Doods( hass, camera[CONF_ENTITY_ID], camera.get(CONF_NAME), doods, detector, config, ) ) add_entities(entities) class Doods(ImageProcessingEntity): """Doods image processing service client.""" def __init__(self, hass, camera_entity, name, doods, detector, config): """Initialize the DOODS entity.""" self.hass = hass self._camera_entity = camera_entity if name: self._name = name else: name = split_entity_id(camera_entity)[1] self._name = f"Doods {name}" self._doods = doods self._file_out = config[CONF_FILE_OUT] self._detector_name = detector["name"] # detector config and aspect ratio self._width = None self._height = None self._aspect = None if detector["width"] and detector["height"]: self._width = detector["width"] self._height = detector["height"] self._aspect = self._width / self._height # the base confidence dconfig = {} confidence = config[CONF_CONFIDENCE] # handle labels and specific detection areas labels = config[CONF_LABELS] self._label_areas = {} self._label_covers = {} for label in labels: if isinstance(label, dict): label_name = label[CONF_NAME] if label_name not in detector["labels"] and label_name != "*": _LOGGER.warning("Detector does not support label %s", label_name) continue # If label confidence is not specified, use global confidence label_confidence = label.get(CONF_CONFIDENCE) if not label_confidence: label_confidence = confidence if label_name not in dconfig or dconfig[label_name] > label_confidence: dconfig[label_name] = label_confidence # Label area label_area = label.get(CONF_AREA) self._label_areas[label_name] = [0, 0, 1, 1] self._label_covers[label_name] = True if label_area: self._label_areas[label_name] = [ label_area[CONF_TOP], label_area[CONF_LEFT], label_area[CONF_BOTTOM], label_area[CONF_RIGHT], ] self._label_covers[label_name] = label_area[CONF_COVERS] else: if label not in detector["labels"] and label != "*": _LOGGER.warning("Detector does not support label %s", label) continue self._label_areas[label] = [0, 0, 1, 1] self._label_covers[label] = True if label not in dconfig or dconfig[label] > confidence: dconfig[label] = confidence if not dconfig: dconfig["*"] = confidence # Handle global detection area self._area = [0, 0, 1, 1] self._covers = True area_config = config.get(CONF_AREA) if area_config: self._area = [ area_config[CONF_TOP], area_config[CONF_LEFT], area_config[CONF_BOTTOM], area_config[CONF_RIGHT], ] self._covers = area_config[CONF_COVERS] template.attach(hass, self._file_out) self._dconfig = dconfig self._matches = {} self._total_matches = 0 self._last_image = None @property def camera_entity(self): """Return camera entity id from process pictures.""" return self._camera_entity @property def name(self): """Return the name of the image processor.""" return self._name @property def state(self): """Return the state of the entity.""" return self._total_matches @property def device_state_attributes(self): """Return device specific state attributes.""" return { ATTR_MATCHES: self._matches, ATTR_SUMMARY: { label: len(values) for label, values in self._matches.items() }, ATTR_TOTAL_MATCHES: self._total_matches, } def _save_image(self, image, matches, paths): img = Image.open(io.BytesIO(bytearray(image))).convert("RGB") img_width, img_height = img.size draw = ImageDraw.Draw(img) # Draw custom global region/area if self._area != [0, 0, 1, 1]: draw_box( draw, self._area, img_width, img_height, "Detection Area", (0, 255, 255) ) for label, values in matches.items(): # Draw custom label regions/areas if label in self._label_areas and self._label_areas[label] != [0, 0, 1, 1]: box_label = f"{label.capitalize()} Detection Area" draw_box( draw, self._label_areas[label], img_width, img_height, box_label, (0, 255, 0), ) # Draw detected objects for instance in values: box_label = f'{label} {instance["score"]:.1f}%' # Already scaled, use 1 for width and height draw_box( draw, instance["box"], img_width, img_height, box_label, (255, 255, 0), ) for path in paths: _LOGGER.info("Saving results image to %s", path) img.save(path) def process_image(self, image): """Process the image.""" img = Image.open(io.BytesIO(bytearray(image))) img_width, img_height = img.size if self._aspect and abs((img_width / img_height) - self._aspect) > 0.1: _LOGGER.debug( "The image aspect: %s and the detector aspect: %s differ by more than 0.1", (img_width / img_height), self._aspect, ) # Run detection start = time.time() response = self._doods.detect( image, dconfig=self._dconfig, detector_name=self._detector_name ) _LOGGER.debug( "doods detect: %s response: %s duration: %s", self._dconfig, response, time.time() - start, ) matches = {} total_matches = 0 if not response or "error" in response: if "error" in response: _LOGGER.error(response["error"]) self._matches = matches self._total_matches = total_matches return for detection in response["detections"]: score = detection["confidence"] boxes = [ detection["top"], detection["left"], detection["bottom"], detection["right"], ] label = detection["label"] # Exclude unlisted labels if "*" not in self._dconfig and label not in self._dconfig: continue # Exclude matches outside global area definition if self._covers: if ( boxes[0] < self._area[0] or boxes[1] < self._area[1] or boxes[2] > self._area[2] or boxes[3] > self._area[3] ): continue else: if ( boxes[0] > self._area[2] or boxes[1] > self._area[3] or boxes[2] < self._area[0] or boxes[3] < self._area[1] ): continue # Exclude matches outside label specific area definition if self._label_areas.get(label): if self._label_covers[label]: if ( boxes[0] < self._label_areas[label][0] or boxes[1] < self._label_areas[label][1] or boxes[2] > self._label_areas[label][2] or boxes[3] > self._label_areas[label][3] ): continue else: if ( boxes[0] > self._label_areas[label][2] or boxes[1] > self._label_areas[label][3] or boxes[2] < self._label_areas[label][0] or boxes[3] < self._label_areas[label][1] ): continue if label not in matches: matches[label] = [] matches[label].append({"score": float(score), "box": boxes}) total_matches += 1 # Save Images if total_matches and self._file_out: paths = [] for path_template in self._file_out: if isinstance(path_template, template.Template): paths.append( path_template.render(camera_entity=self._camera_entity) ) else: paths.append(path_template) self._save_image(image, matches, paths) self._matches = matches self._total_matches = total_matches
joopert/home-assistant
homeassistant/components/doods/image_processing.py
Python
apache-2.0
12,565
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Helper classes for twisted.test.test_ssl. They are in a separate module so they will not prevent test_ssl importing if pyOpenSSL is unavailable. """ from __future__ import division, absolute_import from twisted.python.compat import nativeString from twisted.internet import ssl from twisted.python.filepath import FilePath from OpenSSL import SSL certPath = nativeString(FilePath(__file__.encode("utf-8") ).sibling(b"server.pem").path) class ClientTLSContext(ssl.ClientContextFactory): isClient = 1 def getContext(self): return SSL.Context(SSL.TLSv1_METHOD) class ServerTLSContext: isClient = 0 def __init__(self, filename=certPath, method=SSL.TLSv1_METHOD): self.filename = filename self._method = method def getContext(self): ctx = SSL.Context(self._method) ctx.use_certificate_file(self.filename) ctx.use_privatekey_file(self.filename) return ctx
EricMuller/mynotes-backend
requirements/twisted/Twisted-17.1.0/src/twisted/test/ssl_helpers.py
Python
mit
1,032
# -*- coding: utf-8 -*- import copy import shutil from datetime import timedelta from functools import wraps from json import loads from textwrap import dedent from unittest import SkipTest from uuid import uuid4 import ddt import lxml.html import mock from django.conf import settings from django.contrib.auth.models import User from django.test import TestCase from django.test.utils import override_settings from edxval.api import create_video, get_videos_for_course from fs.osfs import OSFS from lxml import etree from opaque_keys import InvalidKeyError from opaque_keys.edx.keys import CourseKey, UsageKey from opaque_keys.edx.locations import AssetLocation, CourseLocator from path import Path as path from common.test.utils import XssTestMixin from contentstore.tests.utils import AjaxEnabledTestClient, CourseTestCase, get_url, parse_json from contentstore.utils import delete_course, reverse_course_url, reverse_url from contentstore.views.component import ADVANCED_COMPONENT_TYPES from course_action_state.managers import CourseActionStateItemNotFoundError from course_action_state.models import CourseRerunState, CourseRerunUIStateManager from django_comment_common.utils import are_permissions_roles_seeded from openedx.core.lib.tempdir import mkdtemp_clean from student import auth from student.models import CourseEnrollment from student.roles import CourseCreatorRole, CourseInstructorRole from xmodule.capa_module import CapaDescriptor from xmodule.contentstore.content import StaticContent from xmodule.contentstore.django import contentstore from xmodule.contentstore.utils import empty_asset_trashcan, restore_asset_from_trashcan from xmodule.course_module import CourseDescriptor, Textbook from xmodule.exceptions import InvalidVersionError from xmodule.modulestore import ModuleStoreEnum from xmodule.modulestore.django import modulestore from xmodule.modulestore.exceptions import ItemNotFoundError from xmodule.modulestore.inheritance import own_metadata from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory, LibraryFactory, check_mongo_calls from xmodule.modulestore.xml_exporter import export_course_to_xml from xmodule.modulestore.xml_importer import import_course_from_xml, perform_xlint from xmodule.seq_module import SequenceDescriptor TEST_DATA_CONTENTSTORE = copy.deepcopy(settings.CONTENTSTORE) TEST_DATA_CONTENTSTORE['DOC_STORE_CONFIG']['db'] = 'test_xcontent_%s' % uuid4().hex TEST_DATA_DIR = settings.COMMON_TEST_DATA_ROOT def requires_pillow_jpeg(func): """ A decorator to indicate that the function requires JPEG support for Pillow, otherwise it cannot be run """ @wraps(func) def decorated_func(*args, **kwargs): """ Execute the function if we have JPEG support in Pillow. """ try: from PIL import Image except ImportError: raise SkipTest("Pillow is not installed (or not found)") if not getattr(Image.core, "jpeg_decoder", False): raise SkipTest("Pillow cannot open JPEG files") return func(*args, **kwargs) return decorated_func @override_settings(CONTENTSTORE=TEST_DATA_CONTENTSTORE) class ContentStoreTestCase(CourseTestCase): """ Base class for Content Store Test Cases """ class ImportRequiredTestCases(ContentStoreTestCase): """ Tests which legitimately need to import a course """ def test_no_static_link_rewrites_on_import(self): course_items = import_course_from_xml( self.store, self.user.id, TEST_DATA_DIR, ['toy'], create_if_not_present=True ) course = course_items[0] handouts_usage_key = course.id.make_usage_key('course_info', 'handouts') handouts = self.store.get_item(handouts_usage_key) self.assertIn('/static/', handouts.data) handouts_usage_key = course.id.make_usage_key('html', 'toyhtml') handouts = self.store.get_item(handouts_usage_key) self.assertIn('/static/', handouts.data) def test_xlint_fails(self): err_cnt = perform_xlint(TEST_DATA_DIR, ['toy']) self.assertGreater(err_cnt, 0) def test_invalid_asset_overwrite(self): """ Tests that an asset with invalid displayname can be overwritten if multiple assets have same displayname. It Verifies that: During import, if ('/') or ('\') is present in displayname of an asset, it is replaced with underscores '_'. Export does not fail when an asset has '/' in its displayname. If the converted display matches with any other asset, then it will be replaced. Asset name in XML: "/invalid\\displayname/subs-esLhHcdKGWvKs.srt" """ content_store = contentstore() expected_displayname = '_invalid_displayname_subs-esLhHcdKGWvKs.srt' import_course_from_xml( self.store, self.user.id, TEST_DATA_DIR, ['import_draft_order'], static_content_store=content_store, verbose=True, create_if_not_present=True ) # Verify the course has imported successfully course = self.store.get_course(self.store.make_course_key( 'test_org', 'import_draft_order', 'import_draft_order' )) self.assertIsNotNone(course) # Add a new asset in the course, and make sure to name it such that it overwrite the one existing # asset in the course. (i.e. _invalid_displayname_subs-esLhHcdKGWvKs.srt) asset_key = course.id.make_asset_key('asset', 'sample_asset.srt') content = StaticContent( asset_key, expected_displayname, 'application/text', 'test', ) content_store.save(content) # Get & verify that course actually has two assets assets, count = content_store.get_all_content_for_course(course.id) self.assertEqual(count, 2) # Verify both assets have similar `displayname` after saving. for asset in assets: self.assertEquals(asset['displayname'], expected_displayname) # Test course export does not fail root_dir = path(mkdtemp_clean()) print 'Exporting to tempdir = {0}'.format(root_dir) export_course_to_xml(self.store, content_store, course.id, root_dir, 'test_export') filesystem = OSFS(root_dir / 'test_export/static') exported_static_files = filesystem.listdir() # Verify that asset have been overwritten during export. self.assertEqual(len(exported_static_files), 1) self.assertTrue(filesystem.exists(expected_displayname)) self.assertEqual(exported_static_files[0], expected_displayname) # Remove exported course shutil.rmtree(root_dir) def test_about_overrides(self): ''' This test case verifies that a course can use specialized override for about data, e.g. /about/Fall_2012/effort.html while there is a base definition in /about/effort.html ''' course_items = import_course_from_xml( self.store, self.user.id, TEST_DATA_DIR, ['toy'], create_if_not_present=True ) course_key = course_items[0].id effort = self.store.get_item(course_key.make_usage_key('about', 'effort')) self.assertEqual(effort.data, '6 hours') # this one should be in a non-override folder effort = self.store.get_item(course_key.make_usage_key('about', 'end_date')) self.assertEqual(effort.data, 'TBD') @requires_pillow_jpeg def test_asset_import(self): ''' This test validates that an image asset is imported and a thumbnail was generated for a .gif ''' content_store = contentstore() import_course_from_xml( self.store, self.user.id, TEST_DATA_DIR, ['toy'], static_content_store=content_store, verbose=True, create_if_not_present=True ) course = self.store.get_course(self.store.make_course_key('edX', 'toy', '2012_Fall')) self.assertIsNotNone(course) # make sure we have some assets in our contentstore all_assets, __ = content_store.get_all_content_for_course(course.id) self.assertGreater(len(all_assets), 0) # make sure we have some thumbnails in our contentstore all_thumbnails = content_store.get_all_content_thumbnails_for_course(course.id) self.assertGreater(len(all_thumbnails), 0) location = AssetLocation.from_deprecated_string('/c4x/edX/toy/asset/just_a_test.jpg') content = content_store.find(location) self.assertIsNotNone(content) self.assertIsNotNone(content.thumbnail_location) thumbnail = content_store.find(content.thumbnail_location) self.assertIsNotNone(thumbnail) def test_course_info_updates_import_export(self): """ Test that course info updates are imported and exported with all content fields ('data', 'items') """ content_store = contentstore() data_dir = TEST_DATA_DIR courses = import_course_from_xml( self.store, self.user.id, data_dir, ['course_info_updates'], static_content_store=content_store, verbose=True, create_if_not_present=True ) course = courses[0] self.assertIsNotNone(course) course_updates = self.store.get_item(course.id.make_usage_key('course_info', 'updates')) self.assertIsNotNone(course_updates) # check that course which is imported has files 'updates.html' and 'updates.items.json' filesystem = OSFS(data_dir + '/course_info_updates/info') self.assertTrue(filesystem.exists('updates.html')) self.assertTrue(filesystem.exists('updates.items.json')) # verify that course info update module has same data content as in data file from which it is imported # check 'data' field content with filesystem.open('updates.html', 'r') as course_policy: on_disk = course_policy.read() self.assertEqual(course_updates.data, on_disk) # check 'items' field content with filesystem.open('updates.items.json', 'r') as course_policy: on_disk = loads(course_policy.read()) self.assertEqual(course_updates.items, on_disk) # now export the course to a tempdir and test that it contains files 'updates.html' and 'updates.items.json' # with same content as in course 'info' directory root_dir = path(mkdtemp_clean()) print 'Exporting to tempdir = {0}'.format(root_dir) export_course_to_xml(self.store, content_store, course.id, root_dir, 'test_export') # check that exported course has files 'updates.html' and 'updates.items.json' filesystem = OSFS(root_dir / 'test_export/info') self.assertTrue(filesystem.exists('updates.html')) self.assertTrue(filesystem.exists('updates.items.json')) # verify that exported course has same data content as in course_info_update module with filesystem.open('updates.html', 'r') as grading_policy: on_disk = grading_policy.read() self.assertEqual(on_disk, course_updates.data) with filesystem.open('updates.items.json', 'r') as grading_policy: on_disk = loads(grading_policy.read()) self.assertEqual(on_disk, course_updates.items) def test_rewrite_nonportable_links_on_import(self): content_store = contentstore() import_course_from_xml( self.store, self.user.id, TEST_DATA_DIR, ['toy'], static_content_store=content_store, create_if_not_present=True ) # first check a static asset link course_key = self.store.make_course_key('edX', 'toy', 'run') html_module_location = course_key.make_usage_key('html', 'nonportable') html_module = self.store.get_item(html_module_location) self.assertIn('/static/foo.jpg', html_module.data) # then check a intra courseware link html_module_location = course_key.make_usage_key('html', 'nonportable_link') html_module = self.store.get_item(html_module_location) self.assertIn('/jump_to_id/nonportable_link', html_module.data) def verify_content_existence(self, store, root_dir, course_id, dirname, category_name, filename_suffix=''): filesystem = OSFS(root_dir / 'test_export') self.assertTrue(filesystem.exists(dirname)) items = store.get_items(course_id, qualifiers={'category': category_name}) for item in items: filesystem = OSFS(root_dir / ('test_export/' + dirname)) self.assertTrue(filesystem.exists(item.location.name + filename_suffix)) @mock.patch('xmodule.course_module.requests.get') def test_export_course_roundtrip(self, mock_get): mock_get.return_value.text = dedent(""" <?xml version="1.0"?><table_of_contents> <entry page="5" page_label="ii" name="Table of Contents"/> </table_of_contents> """).strip() content_store = contentstore() course_id = self.import_and_populate_course() root_dir = path(mkdtemp_clean()) print 'Exporting to tempdir = {0}'.format(root_dir) # export out to a tempdir export_course_to_xml(self.store, content_store, course_id, root_dir, 'test_export') # check for static tabs self.verify_content_existence(self.store, root_dir, course_id, 'tabs', 'static_tab', '.html') # check for about content self.verify_content_existence(self.store, root_dir, course_id, 'about', 'about', '.html') # assert that there is an html and video directory in drafts: draft_dir = OSFS(root_dir / 'test_export/drafts') self.assertTrue(draft_dir.exists('html')) self.assertTrue(draft_dir.exists('video')) # and assert that they contain the created modules self.assertIn(self.DRAFT_HTML + ".xml", draft_dir.listdir('html')) self.assertIn(self.DRAFT_VIDEO + ".xml", draft_dir.listdir('video')) # and assert the child of the orphaned draft wasn't exported self.assertNotIn(self.ORPHAN_DRAFT_HTML + ".xml", draft_dir.listdir('html')) # check for grading_policy.json filesystem = OSFS(root_dir / 'test_export/policies/2012_Fall') self.assertTrue(filesystem.exists('grading_policy.json')) course = self.store.get_course(course_id) # compare what's on disk compared to what we have in our course with filesystem.open('grading_policy.json', 'r') as grading_policy: on_disk = loads(grading_policy.read()) self.assertEqual(on_disk, course.grading_policy) # check for policy.json self.assertTrue(filesystem.exists('policy.json')) # compare what's on disk to what we have in the course module with filesystem.open('policy.json', 'r') as course_policy: on_disk = loads(course_policy.read()) self.assertIn('course/2012_Fall', on_disk) self.assertEqual(on_disk['course/2012_Fall'], own_metadata(course)) # remove old course self.store.delete_course(course_id, self.user.id) # reimport over old course self.check_import(root_dir, content_store, course_id) # import to different course id new_course_id = self.store.make_course_key('anotherX', 'anotherToy', 'Someday') self.check_import(root_dir, content_store, new_course_id) self.assertCoursesEqual(course_id, new_course_id) shutil.rmtree(root_dir) def check_import(self, root_dir, content_store, course_id): """Imports the course in root_dir into the given course_id and verifies its content""" # reimport import_course_from_xml( self.store, self.user.id, root_dir, ['test_export'], static_content_store=content_store, target_id=course_id, ) # verify content of the course self.check_populated_course(course_id) # verify additional export attributes def verify_export_attrs_removed(attributes): """Verifies all temporary attributes added during export are removed""" self.assertNotIn('index_in_children_list', attributes) self.assertNotIn('parent_sequential_url', attributes) self.assertNotIn('parent_url', attributes) vertical = self.store.get_item(course_id.make_usage_key('vertical', self.TEST_VERTICAL)) verify_export_attrs_removed(vertical.xml_attributes) for child in vertical.get_children(): verify_export_attrs_removed(child.xml_attributes) if hasattr(child, 'data'): verify_export_attrs_removed(child.data) def test_export_course_with_metadata_only_video(self): content_store = contentstore() import_course_from_xml(self.store, self.user.id, TEST_DATA_DIR, ['toy'], create_if_not_present=True) course_id = self.store.make_course_key('edX', 'toy', '2012_Fall') # create a new video module and add it as a child to a vertical # this re-creates a bug whereby since the video template doesn't have # anything in 'data' field, the export was blowing up verticals = self.store.get_items(course_id, qualifiers={'category': 'vertical'}) self.assertGreater(len(verticals), 0) parent = verticals[0] ItemFactory.create(parent_location=parent.location, category="video", display_name="untitled") root_dir = path(mkdtemp_clean()) print 'Exporting to tempdir = {0}'.format(root_dir) # export out to a tempdir export_course_to_xml(self.store, content_store, course_id, root_dir, 'test_export') shutil.rmtree(root_dir) def test_export_course_with_metadata_only_word_cloud(self): """ Similar to `test_export_course_with_metadata_only_video`. """ content_store = contentstore() import_course_from_xml(self.store, self.user.id, TEST_DATA_DIR, ['word_cloud'], create_if_not_present=True) course_id = self.store.make_course_key('HarvardX', 'ER22x', '2013_Spring') verticals = self.store.get_items(course_id, qualifiers={'category': 'vertical'}) self.assertGreater(len(verticals), 0) parent = verticals[0] ItemFactory.create(parent_location=parent.location, category="word_cloud", display_name="untitled") root_dir = path(mkdtemp_clean()) print 'Exporting to tempdir = {0}'.format(root_dir) # export out to a tempdir export_course_to_xml(self.store, content_store, course_id, root_dir, 'test_export') shutil.rmtree(root_dir) def test_import_after_renaming_xml_data(self): """ Test that import works fine on split mongo after renaming the blocks url. """ split_store = modulestore()._get_modulestore_by_type(ModuleStoreEnum.Type.split) # pylint: disable=W0212 import_course_from_xml( split_store, self.user.id, TEST_DATA_DIR, ['course_before_rename'], create_if_not_present=True ) course_after_rename = import_course_from_xml( split_store, self.user.id, TEST_DATA_DIR, ['course_after_rename'], create_if_not_present=True ) all_items = split_store.get_items(course_after_rename[0].id, qualifiers={'category': 'chapter'}) renamed_chapter = [item for item in all_items if item.location.block_id == 'renamed_chapter'][0] self.assertIsNotNone(renamed_chapter.published_on) self.assertIsNotNone(renamed_chapter.parent) self.assertIn(renamed_chapter.location, course_after_rename[0].children) original_chapter = [item for item in all_items if item.location.block_id == 'b9870b9af59841a49e6e02765d0e3bbf'][0] self.assertIsNone(original_chapter.published_on) self.assertIsNone(original_chapter.parent) self.assertNotIn(original_chapter.location, course_after_rename[0].children) def test_empty_data_roundtrip(self): """ Test that an empty `data` field is preserved through export/import. """ content_store = contentstore() import_course_from_xml(self.store, self.user.id, TEST_DATA_DIR, ['toy'], create_if_not_present=True) course_id = self.store.make_course_key('edX', 'toy', '2012_Fall') verticals = self.store.get_items(course_id, qualifiers={'category': 'vertical'}) self.assertGreater(len(verticals), 0) parent = verticals[0] # Create a module, and ensure that its `data` field is empty word_cloud = ItemFactory.create(parent_location=parent.location, category="word_cloud", display_name="untitled") del word_cloud.data self.assertEquals(word_cloud.data, '') # Export the course root_dir = path(mkdtemp_clean()) export_course_to_xml(self.store, content_store, course_id, root_dir, 'test_roundtrip') # Reimport and get the video back import_course_from_xml(self.store, self.user.id, root_dir) imported_word_cloud = self.store.get_item(course_id.make_usage_key('word_cloud', 'untitled')) # It should now contain empty data self.assertEquals(imported_word_cloud.data, '') def test_html_export_roundtrip(self): """ Test that a course which has HTML that has style formatting is preserved in export/import """ content_store = contentstore() import_course_from_xml(self.store, self.user.id, TEST_DATA_DIR, ['toy'], create_if_not_present=True) course_id = self.store.make_course_key('edX', 'toy', '2012_Fall') # Export the course root_dir = path(mkdtemp_clean()) export_course_to_xml(self.store, content_store, course_id, root_dir, 'test_roundtrip') # Reimport and get the video back import_course_from_xml(self.store, self.user.id, root_dir, create_if_not_present=True) # get the sample HTML with styling information html_module = self.store.get_item(course_id.make_usage_key('html', 'with_styling')) self.assertIn('<p style="font:italic bold 72px/30px Georgia, serif; color: red; ">', html_module.data) # get the sample HTML with just a simple <img> tag information html_module = self.store.get_item(course_id.make_usage_key('html', 'just_img')) self.assertIn('<img src="/static/foo_bar.jpg" />', html_module.data) def test_export_course_without_content_store(self): # Create toy course course_items = import_course_from_xml( self.store, self.user.id, TEST_DATA_DIR, ['toy'], create_if_not_present=True ) course_id = course_items[0].id root_dir = path(mkdtemp_clean()) print 'Exporting to tempdir = {0}'.format(root_dir) export_course_to_xml(self.store, None, course_id, root_dir, 'test_export_no_content_store') # Delete the course from module store and reimport it self.store.delete_course(course_id, self.user.id) import_course_from_xml( self.store, self.user.id, root_dir, ['test_export_no_content_store'], static_content_store=None, target_id=course_id ) # Verify reimported course items = self.store.get_items( course_id, qualifiers={ 'category': 'sequential', 'name': 'vertical_sequential', } ) self.assertEqual(len(items), 1) def test_export_course_no_xml_attributes(self): """ Test that a module without an `xml_attributes` attr will still be exported successfully """ content_store = contentstore() import_course_from_xml(self.store, self.user.id, TEST_DATA_DIR, ['toy'], create_if_not_present=True) course_id = self.store.make_course_key('edX', 'toy', '2012_Fall') verticals = self.store.get_items(course_id, qualifiers={'category': 'vertical'}) vertical = verticals[0] # create OpenAssessmentBlock: open_assessment = ItemFactory.create( parent_location=vertical.location, category="openassessment", display_name="untitled", ) # convert it to draft draft_open_assessment = self.store.convert_to_draft( open_assessment.location, self.user.id ) # note that it has no `xml_attributes` attribute self.assertFalse(hasattr(draft_open_assessment, "xml_attributes")) # export should still complete successfully root_dir = path(mkdtemp_clean()) export_course_to_xml( self.store, content_store, course_id, root_dir, 'test_no_xml_attributes' ) @ddt.ddt class MiscCourseTests(ContentStoreTestCase): """ Tests that rely on the toy courses. """ def setUp(self): super(MiscCourseTests, self).setUp() # save locs not items b/c the items won't have the subsequently created children in them until refetched self.chapter_loc = self.store.create_child( self.user.id, self.course.location, 'chapter', 'test_chapter' ).location self.seq_loc = self.store.create_child( self.user.id, self.chapter_loc, 'sequential', 'test_seq' ).location self.vert_loc = self.store.create_child(self.user.id, self.seq_loc, 'vertical', 'test_vert').location # now create some things quasi like the toy course had self.problem = self.store.create_child( self.user.id, self.vert_loc, 'problem', 'test_problem', fields={ "data": "<problem>Test</problem>" } ) self.store.create_child( self.user.id, self.vert_loc, 'video', fields={ "youtube_id_0_75": "JMD_ifUUfsU", "youtube_id_1_0": "OEoXaMPEzfM", "youtube_id_1_25": "AKqURZnYqpk", "youtube_id_1_5": "DYpADpL7jAY", "name": "sample_video", } ) self.store.create_child( self.user.id, self.vert_loc, 'video', fields={ "youtube_id_0_75": "JMD_ifUUfsU", "youtube_id_1_0": "OEoXaMPEzfM", "youtube_id_1_25": "AKqURZnYqpk", "youtube_id_1_5": "DYpADpL7jAY", "name": "truncated_video", "end_time": 10.0, } ) self.store.create_child( self.user.id, self.vert_loc, 'poll_question', fields={ "name": "T1_changemind_poll_foo_2", "display_name": "Change your answer", "question": "Have you changed your mind?", "answers": [{"id": "yes", "text": "Yes"}, {"id": "no", "text": "No"}], } ) self.course = self.store.publish(self.course.location, self.user.id) def check_components_on_page(self, component_types, expected_types): """ Ensure that the right types end up on the page. component_types is the list of advanced components. expected_types is the list of elements that should appear on the page. expected_types and component_types should be similar, but not exactly the same -- for example, 'video' in component_types should cause 'Video' to be present. """ self.course.advanced_modules = component_types self.store.update_item(self.course, self.user.id) # just pick one vertical resp = self.client.get_html(get_url('container_handler', self.vert_loc)) self.assertEqual(resp.status_code, 200) for expected in expected_types: self.assertIn(expected, resp.content) @ddt.data("<script>alert(1)</script>", "alert('hi')", "</script><script>alert(1)</script>") def test_container_handler_xss_prevent(self, malicious_code): """ Test that XSS attack is prevented """ resp = self.client.get_html(get_url('container_handler', self.vert_loc) + '?action=' + malicious_code) self.assertEqual(resp.status_code, 200) # Test that malicious code does not appear in html self.assertNotIn(malicious_code, resp.content) def test_advanced_components_in_edit_unit(self): # This could be made better, but for now let's just assert that we see the advanced modules mentioned in the page # response HTML self.check_components_on_page( ADVANCED_COMPONENT_TYPES, ['Word cloud', 'Annotation', 'Text Annotation', 'Video Annotation', 'Image Annotation', 'split_test'], ) @ddt.data('/Fake/asset/displayname', '\\Fake\\asset\\displayname') def test_export_on_invalid_displayname(self, invalid_displayname): """ Tests that assets with invalid 'displayname' does not cause export to fail """ content_store = contentstore() exported_asset_name = '_Fake_asset_displayname' # Create an asset with slash `invalid_displayname` ' asset_key = self.course.id.make_asset_key('asset', "fake_asset.txt") content = StaticContent( asset_key, invalid_displayname, 'application/text', 'test', ) content_store.save(content) # Verify that the course has only one asset and it has been added with an invalid asset name. assets, count = content_store.get_all_content_for_course(self.course.id) self.assertEqual(count, 1) display_name = assets[0]['displayname'] self.assertEqual(display_name, invalid_displayname) # Now export the course to a tempdir and test that it contains assets. The export should pass root_dir = path(mkdtemp_clean()) print 'Exporting to tempdir = {0}'.format(root_dir) export_course_to_xml(self.store, content_store, self.course.id, root_dir, 'test_export') filesystem = OSFS(root_dir / 'test_export/static') exported_static_files = filesystem.listdir() # Verify that only single asset has been exported with the expected asset name. self.assertTrue(filesystem.exists(exported_asset_name)) self.assertEqual(len(exported_static_files), 1) # Remove tempdir shutil.rmtree(root_dir) @mock.patch( 'lms.djangoapps.ccx.modulestore.CCXModulestoreWrapper.get_item', mock.Mock(return_value=mock.Mock(children=[])) ) def test_export_with_orphan_vertical(self): """ Tests that, export does not fail when a parent xblock does not have draft child xblock information but the draft child xblock has parent information. """ # Make an existing unit a draft self.store.convert_to_draft(self.problem.location, self.user.id) root_dir = path(mkdtemp_clean()) export_course_to_xml(self.store, None, self.course.id, root_dir, 'test_export') # Verify that problem is exported in the drafts. This is expected because we are # mocking get_item to for drafts. Expect no draft is exported. # Specifically get_item is used in `xmodule.modulestore.xml_exporter._export_drafts` export_draft_dir = OSFS(root_dir / 'test_export/drafts') self.assertEqual(len(export_draft_dir.listdir()), 0) # Remove tempdir shutil.rmtree(root_dir) def test_assets_overwrite(self): """ Tests that assets will similar 'displayname' will be overwritten during export """ content_store = contentstore() asset_displayname = 'Fake_asset.txt' # Create two assets with similar 'displayname' for i in range(2): asset_path = 'sample_asset_{}.txt'.format(i) asset_key = self.course.id.make_asset_key('asset', asset_path) content = StaticContent( asset_key, asset_displayname, 'application/text', 'test', ) content_store.save(content) # Fetch & verify course assets to be equal to 2. assets, count = content_store.get_all_content_for_course(self.course.id) self.assertEqual(count, 2) # Verify both assets have similar 'displayname' after saving. for asset in assets: self.assertEquals(asset['displayname'], asset_displayname) # Now export the course to a tempdir and test that it contains assets. root_dir = path(mkdtemp_clean()) print 'Exporting to tempdir = {0}'.format(root_dir) export_course_to_xml(self.store, content_store, self.course.id, root_dir, 'test_export') # Verify that asset have been overwritten during export. filesystem = OSFS(root_dir / 'test_export/static') exported_static_files = filesystem.listdir() self.assertTrue(filesystem.exists(asset_displayname)) self.assertEqual(len(exported_static_files), 1) # Remove tempdir shutil.rmtree(root_dir) def test_advanced_components_require_two_clicks(self): self.check_components_on_page(['word_cloud'], ['Word cloud']) def test_malformed_edit_unit_request(self): # just pick one vertical usage_key = self.course.id.make_usage_key('vertical', None) resp = self.client.get_html(get_url('container_handler', usage_key)) self.assertEqual(resp.status_code, 400) def test_edit_unit(self): """Verifies rendering the editor in all the verticals in the given test course""" self._check_verticals([self.vert_loc]) def _get_draft_counts(self, item): cnt = 1 if getattr(item, 'is_draft', False) else 0 for child in item.get_children(): cnt = cnt + self._get_draft_counts(child) return cnt def test_get_items(self): ''' This verifies a bug we had where the None setting in get_items() meant 'wildcard' Unfortunately, None = published for the revision field, so get_items() would return both draft and non-draft copies. ''' self.store.convert_to_draft(self.problem.location, self.user.id) # Query get_items() and find the html item. This should just return back a single item (not 2). direct_store_items = self.store.get_items( self.course.id, revision=ModuleStoreEnum.RevisionOption.published_only ) items_from_direct_store = [item for item in direct_store_items if item.location == self.problem.location] self.assertEqual(len(items_from_direct_store), 1) self.assertFalse(getattr(items_from_direct_store[0], 'is_draft', False)) # Fetch from the draft store. draft_store_items = self.store.get_items( self.course.id, revision=ModuleStoreEnum.RevisionOption.draft_only ) items_from_draft_store = [item for item in draft_store_items if item.location == self.problem.location] self.assertEqual(len(items_from_draft_store), 1) # TODO the below won't work for split mongo self.assertTrue(getattr(items_from_draft_store[0], 'is_draft', False)) def test_draft_metadata(self): ''' This verifies a bug we had where inherited metadata was getting written to the module as 'own-metadata' when publishing. Also verifies the metadata inheritance is properly computed ''' # refetch course so it has all the children correct course = self.store.update_item(self.course, self.user.id) course.graceperiod = timedelta(days=1, hours=5, minutes=59, seconds=59) course = self.store.update_item(course, self.user.id) problem = self.store.get_item(self.problem.location) self.assertEqual(problem.graceperiod, course.graceperiod) self.assertNotIn('graceperiod', own_metadata(problem)) self.store.convert_to_draft(problem.location, self.user.id) # refetch to check metadata problem = self.store.get_item(problem.location) self.assertEqual(problem.graceperiod, course.graceperiod) self.assertNotIn('graceperiod', own_metadata(problem)) # publish module self.store.publish(problem.location, self.user.id) # refetch to check metadata problem = self.store.get_item(problem.location) self.assertEqual(problem.graceperiod, course.graceperiod) self.assertNotIn('graceperiod', own_metadata(problem)) # put back in draft and change metadata and see if it's now marked as 'own_metadata' self.store.convert_to_draft(problem.location, self.user.id) problem = self.store.get_item(problem.location) new_graceperiod = timedelta(hours=1) self.assertNotIn('graceperiod', own_metadata(problem)) problem.graceperiod = new_graceperiod # Save the data that we've just changed to the underlying # MongoKeyValueStore before we update the mongo datastore. problem.save() self.assertIn('graceperiod', own_metadata(problem)) self.assertEqual(problem.graceperiod, new_graceperiod) self.store.update_item(problem, self.user.id) # read back to make sure it reads as 'own-metadata' problem = self.store.get_item(problem.location) self.assertIn('graceperiod', own_metadata(problem)) self.assertEqual(problem.graceperiod, new_graceperiod) # republish self.store.publish(problem.location, self.user.id) # and re-read and verify 'own-metadata' self.store.convert_to_draft(problem.location, self.user.id) problem = self.store.get_item(problem.location) self.assertIn('graceperiod', own_metadata(problem)) self.assertEqual(problem.graceperiod, new_graceperiod) def test_get_depth_with_drafts(self): # make sure no draft items have been returned num_drafts = self._get_draft_counts(self.course) self.assertEqual(num_drafts, 0) # put into draft self.store.convert_to_draft(self.problem.location, self.user.id) # make sure we can query that item and verify that it is a draft draft_problem = self.store.get_item(self.problem.location) self.assertTrue(getattr(draft_problem, 'is_draft', False)) # now requery with depth course = self.store.get_course(self.course.id, depth=None) # make sure just one draft item have been returned num_drafts = self._get_draft_counts(course) self.assertEqual(num_drafts, 1) @mock.patch('xmodule.course_module.requests.get') def test_import_textbook_as_content_element(self, mock_get): mock_get.return_value.text = dedent(""" <?xml version="1.0"?><table_of_contents> <entry page="5" page_label="ii" name="Table of Contents"/> </table_of_contents> """).strip() self.course.textbooks = [Textbook("Textbook", "https://s3.amazonaws.com/edx-textbooks/guttag_computation_v3/")] course = self.store.update_item(self.course, self.user.id) self.assertGreater(len(course.textbooks), 0) def test_import_polls(self): items = self.store.get_items(self.course.id, qualifiers={'category': 'poll_question'}) self.assertGreater(len(items), 0) # check that there's actually content in the 'question' field self.assertGreater(len(items[0].question), 0) def test_module_preview_in_whitelist(self): """ Tests the ajax callback to render an XModule """ with override_settings(COURSES_WITH_UNSAFE_CODE=[unicode(self.course.id)]): # also try a custom response which will trigger the 'is this course in whitelist' logic resp = self.client.get_json( get_url('xblock_view_handler', self.vert_loc, kwargs={'view_name': 'container_preview'}) ) self.assertEqual(resp.status_code, 200) vertical = self.store.get_item(self.vert_loc) for child in vertical.children: self.assertContains(resp, unicode(child)) def test_delete(self): # make sure the parent points to the child object which is to be deleted # need to refetch chapter b/c at the time it was assigned it had no children chapter = self.store.get_item(self.chapter_loc) self.assertIn(self.seq_loc, chapter.children) self.client.delete(get_url('xblock_handler', self.seq_loc)) with self.assertRaises(ItemNotFoundError): self.store.get_item(self.seq_loc) chapter = self.store.get_item(self.chapter_loc) # make sure the parent no longer points to the child object which was deleted self.assertNotIn(self.seq_loc, chapter.children) def test_asset_delete_and_restore(self): ''' This test will exercise the soft delete/restore functionality of the assets ''' asset_key = self._delete_asset_in_course() # now try to find it in store, but they should not be there any longer content = contentstore().find(asset_key, throw_on_not_found=False) self.assertIsNone(content) # now try to find it and the thumbnail in trashcan - should be in there content = contentstore('trashcan').find(asset_key, throw_on_not_found=False) self.assertIsNotNone(content) # let's restore the asset restore_asset_from_trashcan(unicode(asset_key)) # now try to find it in courseware store, and they should be back after restore content = contentstore('trashcan').find(asset_key, throw_on_not_found=False) self.assertIsNotNone(content) def _delete_asset_in_course(self): """ Helper method for: 1) importing course from xml 2) finding asset in course (verifying non-empty) 3) computing thumbnail location of asset 4) deleting the asset from the course """ asset_key = self.course.id.make_asset_key('asset', 'sample_static.html') content = StaticContent( asset_key, "Fake asset", "application/text", "test", ) contentstore().save(content) # go through the website to do the delete, since the soft-delete logic is in the view url = reverse_course_url( 'assets_handler', self.course.id, kwargs={'asset_key_string': unicode(asset_key)} ) resp = self.client.delete(url) self.assertEqual(resp.status_code, 204) return asset_key def test_empty_trashcan(self): ''' This test will exercise the emptying of the asset trashcan ''' self._delete_asset_in_course() # make sure there's something in the trashcan all_assets, __ = contentstore('trashcan').get_all_content_for_course(self.course.id) self.assertGreater(len(all_assets), 0) # empty the trashcan empty_asset_trashcan([self.course.id]) # make sure trashcan is empty all_assets, count = contentstore('trashcan').get_all_content_for_course(self.course.id) self.assertEqual(len(all_assets), 0) self.assertEqual(count, 0) def test_illegal_draft_crud_ops(self): # this test presumes old mongo and split_draft not full split with self.assertRaises(InvalidVersionError): self.store.convert_to_draft(self.chapter_loc, self.user.id) chapter = self.store.get_item(self.chapter_loc) chapter.data = 'chapter data' self.store.update_item(chapter, self.user.id) newobject = self.store.get_item(self.chapter_loc) self.assertFalse(getattr(newobject, 'is_draft', False)) with self.assertRaises(InvalidVersionError): self.store.unpublish(self.chapter_loc, self.user.id) def test_bad_contentstore_request(self): """ Test that user get proper responses for urls with invalid url or asset/course key """ resp = self.client.get_html('/c4x/CDX/123123/asset/&invalid.png') self.assertEqual(resp.status_code, 400) resp = self.client.get_html('/c4x/CDX/123123/asset/invalid.png') self.assertEqual(resp.status_code, 404) # Now test that 404 response is returned when user tries to access # asset of some invalid course from split ModuleStore with self.store.default_store(ModuleStoreEnum.Type.split): resp = self.client.get_html('/c4x/InvalidOrg/InvalidCourse/asset/invalid.png') self.assertEqual(resp.status_code, 404) def test_delete_course(self): """ This test creates a course, makes a draft item, and deletes the course. This will also assert that the draft content is also deleted """ # add an asset asset_key = self.course.id.make_asset_key('asset', 'sample_static.html') content = StaticContent( asset_key, "Fake asset", "application/text", "test", ) contentstore().save(content) assets, count = contentstore().get_all_content_for_course(self.course.id) self.assertGreater(len(assets), 0) self.assertGreater(count, 0) self.store.convert_to_draft(self.vert_loc, self.user.id) # delete the course self.store.delete_course(self.course.id, self.user.id) # assert that there's absolutely no non-draft modules in the course # this should also include all draft items items = self.store.get_items(self.course.id) self.assertEqual(len(items), 0) # assert that all content in the asset library is also deleted assets, count = contentstore().get_all_content_for_course(self.course.id) self.assertEqual(len(assets), 0) self.assertEqual(count, 0) def test_course_handouts_rewrites(self): """ Test that the xblock_handler rewrites static handout links """ handouts = self.store.create_item( self.user.id, self.course.id, 'course_info', 'handouts', fields={ "data": "<a href='/static/handouts/sample_handout.txt'>Sample</a>", } ) # get module info (json) resp = self.client.get(get_url('xblock_handler', handouts.location)) # make sure we got a successful response self.assertEqual(resp.status_code, 200) # check that /static/ has been converted to the full path # note, we know the link it should be because that's what in the 'toy' course in the test data asset_key = self.course.id.make_asset_key('asset', 'handouts_sample_handout.txt') self.assertContains(resp, unicode(asset_key)) def test_prefetch_children(self): # make sure we haven't done too many round trips to DB: # 1) the course, # 2 & 3) for the chapters and sequentials # Because we're querying from the top of the tree, we cache information needed for inheritance, # so we don't need to make an extra query to compute it. # set the branch to 'publish' in order to prevent extra lookups of draft versions with self.store.branch_setting(ModuleStoreEnum.Branch.published_only, self.course.id): with check_mongo_calls(3): course = self.store.get_course(self.course.id, depth=2) # make sure we pre-fetched a known sequential which should be at depth=2 self.assertIn(self.seq_loc, course.system.module_data) # make sure we don't have a specific vertical which should be at depth=3 self.assertNotIn(self.vert_loc, course.system.module_data) # Now, test with the branch set to draft. No extra round trips b/c it doesn't go deep enough to get # beyond direct only categories with self.store.branch_setting(ModuleStoreEnum.Branch.draft_preferred, self.course.id): with check_mongo_calls(3): self.store.get_course(self.course.id, depth=2) def _check_verticals(self, locations): """ Test getting the editing HTML for each vertical. """ # Assert is here to make sure that the course being tested actually has verticals (units) to check. self.assertGreater(len(locations), 0) for loc in locations: resp = self.client.get_html(get_url('container_handler', loc)) self.assertEqual(resp.status_code, 200) @ddt.ddt class ContentStoreTest(ContentStoreTestCase, XssTestMixin): """ Tests for the CMS ContentStore application. """ duplicate_course_error = ("There is already a course defined with the same organization and course number. " "Please change either organization or course number to be unique.") def setUp(self): super(ContentStoreTest, self).setUp() self.course_data = { 'org': 'MITx', 'number': '111', 'display_name': 'Robot Super Course', 'run': '2013_Spring' } def assert_created_course(self, number_suffix=None): """ Checks that the course was created properly. """ test_course_data = {} test_course_data.update(self.course_data) if number_suffix: test_course_data['number'] = '{0}_{1}'.format(test_course_data['number'], number_suffix) course_key = _get_course_id(self.store, test_course_data) _create_course(self, course_key, test_course_data) # Verify that the creator is now registered in the course. self.assertTrue(CourseEnrollment.is_enrolled(self.user, course_key)) return test_course_data def assert_create_course_failed(self, error_message): """ Checks that the course not created. """ resp = self.client.ajax_post('/course/', self.course_data) self.assertEqual(resp.status_code, 400) data = parse_json(resp) self.assertEqual(data['error'], error_message) def test_create_course(self): """Test new course creation - happy path""" self.assert_created_course() @override_settings(DEFAULT_COURSE_LANGUAGE='hr') def test_create_course_default_language(self): """Test new course creation and verify default language""" test_course_data = self.assert_created_course() course_id = _get_course_id(self.store, test_course_data) course_module = self.store.get_course(course_id) self.assertEquals(course_module.language, 'hr') def test_create_course_with_dots(self): """Test new course creation with dots in the name""" self.course_data['org'] = 'org.foo.bar' self.course_data['number'] = 'course.number' self.course_data['run'] = 'run.name' self.assert_created_course() @ddt.data(ModuleStoreEnum.Type.split, ModuleStoreEnum.Type.mongo) def test_course_with_different_cases(self, default_store): """ Tests that course can not be created with different case using an AJAX request to course handler. """ course_number = '99x' with self.store.default_store(default_store): # Verify create a course passes with lower case. self.course_data['number'] = course_number.lower() self.assert_created_course() # Verify create a course fail when same course number is provided with different case. self.course_data['number'] = course_number.upper() self.assert_course_creation_failed(self.duplicate_course_error) def test_create_course_check_forum_seeding(self): """Test new course creation and verify forum seeding """ test_course_data = self.assert_created_course(number_suffix=uuid4().hex) self.assertTrue(are_permissions_roles_seeded(_get_course_id(self.store, test_course_data))) def test_forum_unseeding_on_delete(self): """Test new course creation and verify forum unseeding """ test_course_data = self.assert_created_course(number_suffix=uuid4().hex) course_id = _get_course_id(self.store, test_course_data) self.assertTrue(are_permissions_roles_seeded(course_id)) delete_course(course_id, self.user.id) # should raise an exception for checking permissions on deleted course with self.assertRaises(ItemNotFoundError): are_permissions_roles_seeded(course_id) def test_forum_unseeding_with_multiple_courses(self): """Test new course creation and verify forum unseeding when there are multiple courses""" test_course_data = self.assert_created_course(number_suffix=uuid4().hex) second_course_data = self.assert_created_course(number_suffix=uuid4().hex) # unseed the forums for the first course course_id = _get_course_id(self.store, test_course_data) delete_course(course_id, self.user.id) # should raise an exception for checking permissions on deleted course with self.assertRaises(ItemNotFoundError): are_permissions_roles_seeded(course_id) second_course_id = _get_course_id(self.store, second_course_data) # permissions should still be there for the other course self.assertTrue(are_permissions_roles_seeded(second_course_id)) def test_course_enrollments_and_roles_on_delete(self): """ Test that course deletion doesn't remove course enrollments or user's roles """ test_course_data = self.assert_created_course(number_suffix=uuid4().hex) course_id = _get_course_id(self.store, test_course_data) # test that a user gets his enrollment and its 'student' role as default on creating a course self.assertTrue(CourseEnrollment.is_enrolled(self.user, course_id)) self.assertTrue(self.user.roles.filter(name="Student", course_id=course_id)) delete_course(course_id, self.user.id) # check that user's enrollment for this course is not deleted self.assertTrue(CourseEnrollment.is_enrolled(self.user, course_id)) # check that user has form role "Student" for this course even after deleting it self.assertTrue(self.user.roles.filter(name="Student", course_id=course_id)) def test_course_access_groups_on_delete(self): """ Test that course deletion removes users from 'instructor' and 'staff' groups of this course of all format e.g, 'instructor_edX/Course/Run', 'instructor_edX.Course.Run', 'instructor_Course' """ test_course_data = self.assert_created_course(number_suffix=uuid4().hex) course_id = _get_course_id(self.store, test_course_data) # Add user in possible groups and check that user in instructor groups of this course instructor_role = CourseInstructorRole(course_id) auth.add_users(self.user, instructor_role, self.user) self.assertGreater(len(instructor_role.users_with_role()), 0) # Now delete course and check that user not in instructor groups of this course delete_course(course_id, self.user.id) # Update our cached user since its roles have changed self.user = User.objects.get_by_natural_key(self.user.natural_key()[0]) self.assertFalse(instructor_role.has_user(self.user)) self.assertEqual(len(instructor_role.users_with_role()), 0) def test_delete_course_with_keep_instructors(self): """ Tests that when you delete a course with 'keep_instructors', it does not remove any permissions of users/groups from the course """ test_course_data = self.assert_created_course(number_suffix=uuid4().hex) course_id = _get_course_id(self.store, test_course_data) # Add and verify instructor role for the course instructor_role = CourseInstructorRole(course_id) instructor_role.add_users(self.user) self.assertTrue(instructor_role.has_user(self.user)) delete_course(course_id, self.user.id, keep_instructors=True) # Update our cached user so if any change in roles can be captured self.user = User.objects.get_by_natural_key(self.user.natural_key()[0]) self.assertTrue(instructor_role.has_user(self.user)) def test_create_course_after_delete(self): """ Test that course creation works after deleting a course with the same URL """ test_course_data = self.assert_created_course() course_id = _get_course_id(self.store, test_course_data) delete_course(course_id, self.user.id) self.assert_created_course() def test_create_course_duplicate_course(self): """Test new course creation - error path""" self.client.ajax_post('/course/', self.course_data) self.assert_course_creation_failed(self.duplicate_course_error) def assert_course_creation_failed(self, error_message): """ Checks that the course did not get created """ test_enrollment = False try: course_id = _get_course_id(self.store, self.course_data) initially_enrolled = CourseEnrollment.is_enrolled(self.user, course_id) test_enrollment = True except InvalidKeyError: # b/c the intent of the test with bad chars isn't to test auth but to test the handler, ignore pass resp = self.client.ajax_post('/course/', self.course_data) self.assertEqual(resp.status_code, 200) data = parse_json(resp) self.assertRegexpMatches(data['ErrMsg'], error_message) if test_enrollment: # One test case involves trying to create the same course twice. Hence for that course, # the user will be enrolled. In the other cases, initially_enrolled will be False. self.assertEqual(initially_enrolled, CourseEnrollment.is_enrolled(self.user, course_id)) def test_create_course_duplicate_number(self): """Test new course creation - error path""" self.client.ajax_post('/course/', self.course_data) self.course_data['display_name'] = 'Robot Super Course Two' self.course_data['run'] = '2013_Summer' self.assert_course_creation_failed(self.duplicate_course_error) @ddt.data(ModuleStoreEnum.Type.split, ModuleStoreEnum.Type.mongo) def test_create_course_case_change(self, default_store): """Test new course creation - error path due to case insensitive name equality""" self.course_data['number'] = '99x' with self.store.default_store(default_store): # Verify that the course was created properly. self.assert_created_course() # Keep the copy of original org cache_current = self.course_data['org'] # Change `org` to lower case and verify that course did not get created self.course_data['org'] = self.course_data['org'].lower() self.assert_course_creation_failed(self.duplicate_course_error) # Replace the org with its actual value, and keep the copy of course number. self.course_data['org'] = cache_current cache_current = self.course_data['number'] self.course_data['number'] = self.course_data['number'].upper() self.assert_course_creation_failed(self.duplicate_course_error) # Replace the org with its actual value, and keep the copy of course number. self.course_data['number'] = cache_current __ = self.course_data['run'] self.course_data['run'] = self.course_data['run'].upper() self.assert_course_creation_failed(self.duplicate_course_error) def test_course_substring(self): """ Test that a new course can be created whose name is a substring of an existing course """ self.client.ajax_post('/course/', self.course_data) cache_current = self.course_data['number'] self.course_data['number'] = '{}a'.format(self.course_data['number']) resp = self.client.ajax_post('/course/', self.course_data) self.assertEqual(resp.status_code, 200) self.course_data['number'] = cache_current self.course_data['org'] = 'a{}'.format(self.course_data['org']) resp = self.client.ajax_post('/course/', self.course_data) self.assertEqual(resp.status_code, 200) def test_create_course_with_bad_organization(self): """Test new course creation - error path for bad organization name""" self.course_data['org'] = 'University of California, Berkeley' self.assert_course_creation_failed(r"(?s)Unable to create course 'Robot Super Course'.*") def test_create_course_with_course_creation_disabled_staff(self): """Test new course creation -- course creation disabled, but staff access.""" with mock.patch.dict('django.conf.settings.FEATURES', {'DISABLE_COURSE_CREATION': True}): self.assert_created_course() def test_create_course_with_course_creation_disabled_not_staff(self): """Test new course creation -- error path for course creation disabled, not staff access.""" with mock.patch.dict('django.conf.settings.FEATURES', {'DISABLE_COURSE_CREATION': True}): self.user.is_staff = False self.user.save() self.assert_course_permission_denied() def test_create_course_no_course_creators_staff(self): """Test new course creation -- course creation group enabled, staff, group is empty.""" with mock.patch.dict('django.conf.settings.FEATURES', {'ENABLE_CREATOR_GROUP': True}): self.assert_created_course() def test_create_course_no_course_creators_not_staff(self): """Test new course creation -- error path for course creator group enabled, not staff, group is empty.""" with mock.patch.dict('django.conf.settings.FEATURES', {"ENABLE_CREATOR_GROUP": True}): self.user.is_staff = False self.user.save() self.assert_course_permission_denied() def test_create_course_with_course_creator(self): """Test new course creation -- use course creator group""" with mock.patch.dict('django.conf.settings.FEATURES', {"ENABLE_CREATOR_GROUP": True}): auth.add_users(self.user, CourseCreatorRole(), self.user) self.assert_created_course() def test_create_course_with_unicode_in_id_disabled(self): """ Test new course creation with feature setting: ALLOW_UNICODE_COURSE_ID disabled. """ with mock.patch.dict('django.conf.settings.FEATURES', {'ALLOW_UNICODE_COURSE_ID': False}): error_message = "Special characters not allowed in organization, course number, and course run." self.course_data['org'] = u'��������������' self.assert_create_course_failed(error_message) self.course_data['number'] = u'��chantillon' self.assert_create_course_failed(error_message) self.course_data['run'] = u'����������' self.assert_create_course_failed(error_message) def assert_course_permission_denied(self): """ Checks that the course did not get created due to a PermissionError. """ resp = self.client.ajax_post('/course/', self.course_data) self.assertEqual(resp.status_code, 403) def test_course_index_view_with_no_courses(self): """Test viewing the index page with no courses""" resp = self.client.get_html('/home/') self.assertContains( resp, '<h1 class="page-header">Studio Home</h1>', status_code=200, html=True ) def test_course_factory(self): """Test that the course factory works correctly.""" course = CourseFactory.create() self.assertIsInstance(course, CourseDescriptor) def test_item_factory(self): """Test that the item factory works correctly.""" course = CourseFactory.create() item = ItemFactory.create(parent_location=course.location) self.assertIsInstance(item, SequenceDescriptor) def test_course_index_view_with_course(self): """Test viewing the index page with an existing course""" CourseFactory.create(display_name='Robot Super Educational Course') resp = self.client.get_html('/home/') self.assertContains( resp, '<h3 class="course-title">Robot Super Educational Course</h3>', status_code=200, html=True ) def test_course_index_view_xss(self): """Test that the index page correctly escapes course names with script tags.""" CourseFactory.create( display_name='<script>alert("course XSS")</script>' ) LibraryFactory.create(display_name='<script>alert("library XSS")</script>') resp = self.client.get_html('/home/') for xss in ('course', 'library'): html = '<script>alert("{name} XSS")</script>'.format( name=xss ) self.assert_no_xss(resp, html) def test_course_overview_view_with_course(self): """Test viewing the course overview page with an existing course""" course = CourseFactory.create() resp = self._show_course_overview(course.id) self.assertContains( resp, '<article class="outline outline-complex outline-course" data-locator="{locator}" data-course-key="{course_key}">'.format( locator=unicode(course.location), course_key=unicode(course.id), ), status_code=200, html=True ) def test_create_item(self): """Test creating a new xblock instance.""" course = CourseFactory.create() section_data = { 'parent_locator': unicode(course.location), 'category': 'chapter', 'display_name': 'Section One', } resp = self.client.ajax_post(reverse_url('xblock_handler'), section_data) self.assertEqual(resp.status_code, 200) data = parse_json(resp) retarget = unicode(course.id.make_usage_key('chapter', 'REPLACE')).replace('REPLACE', r'([0-9]|[a-f]){3,}') self.assertRegexpMatches(data['locator'], retarget) def test_capa_module(self): """Test that a problem treats markdown specially.""" course = CourseFactory.create() problem_data = { 'parent_locator': unicode(course.location), 'category': 'problem' } resp = self.client.ajax_post(reverse_url('xblock_handler'), problem_data) self.assertEqual(resp.status_code, 200) payload = parse_json(resp) problem_loc = UsageKey.from_string(payload['locator']) problem = self.store.get_item(problem_loc) # should be a CapaDescriptor self.assertIsInstance(problem, CapaDescriptor, "New problem is not a CapaDescriptor") context = problem.get_context() self.assertIn('markdown', context, "markdown is missing from context") self.assertNotIn('markdown', problem.editable_metadata_fields, "Markdown slipped into the editable metadata fields") def test_cms_imported_course_walkthrough(self): """ Import and walk through some common URL endpoints. This just verifies non-500 and no other correct behavior, so it is not a deep test """ def test_get_html(handler): # Helper function for getting HTML for a page in Studio and # checking that it does not error. resp = self.client.get_html( get_url(handler, course_key, 'course_key_string') ) self.assertEqual(resp.status_code, 200) course_items = import_course_from_xml( self.store, self.user.id, TEST_DATA_DIR, ['simple'], create_if_not_present=True ) course_key = course_items[0].id resp = self._show_course_overview(course_key) self.assertEqual(resp.status_code, 200) self.assertContains(resp, 'Chapter 2') # go to various pages test_get_html('import_handler') test_get_html('export_handler') test_get_html('course_team_handler') test_get_html('course_info_handler') test_get_html('assets_handler') test_get_html('tabs_handler') test_get_html('settings_handler') test_get_html('grading_handler') test_get_html('advanced_settings_handler') test_get_html('textbooks_list_handler') # go look at the Edit page unit_key = course_key.make_usage_key('vertical', 'test_vertical') resp = self.client.get_html(get_url('container_handler', unit_key)) self.assertEqual(resp.status_code, 200) def delete_item(category, name): """ Helper method for testing the deletion of an xblock item. """ item_key = course_key.make_usage_key(category, name) resp = self.client.delete(get_url('xblock_handler', item_key)) self.assertEqual(resp.status_code, 204) # delete a component delete_item(category='html', name='test_html') # delete a unit delete_item(category='vertical', name='test_vertical') # delete a unit delete_item(category='sequential', name='test_sequence') # delete a chapter delete_item(category='chapter', name='chapter_2') def test_import_into_new_course_id(self): target_id = _get_course_id(self.store, self.course_data) _create_course(self, target_id, self.course_data) import_course_from_xml(self.store, self.user.id, TEST_DATA_DIR, ['toy'], target_id=target_id) modules = self.store.get_items(target_id) # we should have a number of modules in there # we can't specify an exact number since it'll always be changing self.assertGreater(len(modules), 10) # # test various re-namespacing elements # # first check PDF textbooks, to make sure the url paths got updated course_module = self.store.get_course(target_id) self.assertEqual(len(course_module.pdf_textbooks), 1) self.assertEqual(len(course_module.pdf_textbooks[0]["chapters"]), 2) self.assertEqual(course_module.pdf_textbooks[0]["chapters"][0]["url"], '/static/Chapter1.pdf') self.assertEqual(course_module.pdf_textbooks[0]["chapters"][1]["url"], '/static/Chapter2.pdf') def test_import_into_new_course_id_wiki_slug_renamespacing(self): # If reimporting into the same course do not change the wiki_slug. target_id = self.store.make_course_key('edX', 'toy', '2012_Fall') course_data = { 'org': target_id.org, 'number': target_id.course, 'display_name': 'Robot Super Course', 'run': target_id.run } _create_course(self, target_id, course_data) course_module = self.store.get_course(target_id) course_module.wiki_slug = 'toy' course_module.save() # Import a course with wiki_slug == location.course import_course_from_xml(self.store, self.user.id, TEST_DATA_DIR, ['toy'], target_id=target_id) course_module = self.store.get_course(target_id) self.assertEquals(course_module.wiki_slug, 'toy') # But change the wiki_slug if it is a different course. target_id = self.store.make_course_key('MITx', '111', '2013_Spring') course_data = { 'org': target_id.org, 'number': target_id.course, 'display_name': 'Robot Super Course', 'run': target_id.run } _create_course(self, target_id, course_data) # Import a course with wiki_slug == location.course import_course_from_xml(self.store, self.user.id, TEST_DATA_DIR, ['toy'], target_id=target_id) course_module = self.store.get_course(target_id) self.assertEquals(course_module.wiki_slug, 'MITx.111.2013_Spring') # Now try importing a course with wiki_slug == '{0}.{1}.{2}'.format(location.org, location.course, location.run) import_course_from_xml(self.store, self.user.id, TEST_DATA_DIR, ['two_toys'], target_id=target_id) course_module = self.store.get_course(target_id) self.assertEquals(course_module.wiki_slug, 'MITx.111.2013_Spring') def test_import_metadata_with_attempts_empty_string(self): import_course_from_xml(self.store, self.user.id, TEST_DATA_DIR, ['simple'], create_if_not_present=True) did_load_item = False try: course_key = self.store.make_course_key('edX', 'simple', 'problem') usage_key = course_key.make_usage_key('problem', 'ps01-simple') self.store.get_item(usage_key) did_load_item = True except ItemNotFoundError: pass # make sure we found the item (e.g. it didn't error while loading) self.assertTrue(did_load_item) @ddt.data(ModuleStoreEnum.Type.split, ModuleStoreEnum.Type.mongo) def test_forum_id_generation(self, default_store): """ Test that a discussion item, even if it doesn't set its discussion_id, consistently generates the same one """ course = CourseFactory.create(default_store=default_store) # create a discussion item discussion_item = self.store.create_item(self.user.id, course.id, 'discussion', 'new_component') # now fetch it from the modulestore to instantiate its descriptor fetched = self.store.get_item(discussion_item.location) # refetch it to be safe refetched = self.store.get_item(discussion_item.location) # and make sure the same discussion items have the same discussion ids self.assertEqual(fetched.discussion_id, discussion_item.discussion_id) self.assertEqual(fetched.discussion_id, refetched.discussion_id) # and make sure that the id isn't the old "$$GUID$$" self.assertNotEqual(discussion_item.discussion_id, '$$GUID$$') def test_metadata_inheritance(self): course_items = import_course_from_xml( self.store, self.user.id, TEST_DATA_DIR, ['toy'], create_if_not_present=True ) course = course_items[0] verticals = self.store.get_items(course.id, qualifiers={'category': 'vertical'}) # let's assert on the metadata_inheritance on an existing vertical for vertical in verticals: self.assertEqual(course.xqa_key, vertical.xqa_key) self.assertEqual(course.start, vertical.start) self.assertGreater(len(verticals), 0) # crate a new module and add it as a child to a vertical parent = verticals[0] new_block = self.store.create_child( self.user.id, parent.location, 'html', 'new_component' ) # flush the cache new_block = self.store.get_item(new_block.location) # check for grace period definition which should be defined at the course level self.assertEqual(parent.graceperiod, new_block.graceperiod) self.assertEqual(parent.start, new_block.start) self.assertEqual(course.start, new_block.start) self.assertEqual(course.xqa_key, new_block.xqa_key) # # now let's define an override at the leaf node level # new_block.graceperiod = timedelta(1) self.store.update_item(new_block, self.user.id) # flush the cache and refetch new_block = self.store.get_item(new_block.location) self.assertEqual(timedelta(1), new_block.graceperiod) def test_default_metadata_inheritance(self): course = CourseFactory.create() vertical = ItemFactory.create(parent_location=course.location) course.children.append(vertical) # in memory self.assertIsNotNone(course.start) self.assertEqual(course.start, vertical.start) self.assertEqual(course.textbooks, []) self.assertIn('GRADER', course.grading_policy) self.assertIn('GRADE_CUTOFFS', course.grading_policy) # by fetching fetched_course = self.store.get_item(course.location) fetched_item = self.store.get_item(vertical.location) self.assertIsNotNone(fetched_course.start) self.assertEqual(course.start, fetched_course.start) self.assertEqual(fetched_course.start, fetched_item.start) self.assertEqual(course.textbooks, fetched_course.textbooks) def test_image_import(self): """Test backwards compatibilty of course image.""" content_store = contentstore() # Use conditional_and_poll, as it's got an image already courses = import_course_from_xml( self.store, self.user.id, TEST_DATA_DIR, ['conditional_and_poll'], static_content_store=content_store, create_if_not_present=True ) course = courses[0] # Make sure the course image is set to the right place self.assertEqual(course.course_image, 'images_course_image.jpg') # Ensure that the imported course image is present -- this shouldn't raise an exception asset_key = course.id.make_asset_key('asset', course.course_image) content_store.find(asset_key) def _show_course_overview(self, course_key): """ Show the course overview page. """ resp = self.client.get_html(get_url('course_handler', course_key, 'course_key_string')) return resp def test_wiki_slug(self): """When creating a course a unique wiki_slug should be set.""" course_key = _get_course_id(self.store, self.course_data) _create_course(self, course_key, self.course_data) course_module = self.store.get_course(course_key) self.assertEquals(course_module.wiki_slug, 'MITx.111.2013_Spring') def test_course_handler_with_invalid_course_key_string(self): """Test viewing the course overview page with invalid course id""" response = self.client.get_html('/course/edX/test') self.assertEquals(response.status_code, 404) class MetadataSaveTestCase(ContentStoreTestCase): """Test that metadata is correctly cached and decached.""" def setUp(self): super(MetadataSaveTestCase, self).setUp() course = CourseFactory.create() video_sample_xml = ''' <video display_name="Test Video" youtube="1.0:p2Q6BrNhdh8,0.75:izygArpw-Qo,1.25:1EeWXzPdhSA,1.5:rABDYkeK0x8" show_captions="false" from="00:00:01" to="00:01:00"> <source src="http://www.example.com/file.mp4"/> <track src="http://www.example.com/track"/> </video> ''' self.video_descriptor = ItemFactory.create( parent_location=course.location, category='video', data={'data': video_sample_xml} ) def test_metadata_not_persistence(self): """ Test that descriptors which set metadata fields in their constructor are correctly deleted. """ self.assertIn('html5_sources', own_metadata(self.video_descriptor)) attrs_to_strip = { 'show_captions', 'youtube_id_1_0', 'youtube_id_0_75', 'youtube_id_1_25', 'youtube_id_1_5', 'start_time', 'end_time', 'source', 'html5_sources', 'track' } location = self.video_descriptor.location for field_name in attrs_to_strip: delattr(self.video_descriptor, field_name) self.assertNotIn('html5_sources', own_metadata(self.video_descriptor)) self.store.update_item(self.video_descriptor, self.user.id) module = self.store.get_item(location) self.assertNotIn('html5_sources', own_metadata(module)) def test_metadata_persistence(self): # TODO: create the same test as `test_metadata_not_persistence`, # but check persistence for some other module. pass class RerunCourseTest(ContentStoreTestCase): """ Tests for Rerunning a course via the view handler """ def setUp(self): super(RerunCourseTest, self).setUp() self.destination_course_data = { 'org': 'MITx', 'number': '111', 'display_name': 'Robot Super Course', 'run': '2013_Spring' } def post_rerun_request( self, source_course_key, destination_course_data=None, response_code=200, expect_error=False ): """Create and send an ajax post for the rerun request""" # create data to post rerun_course_data = {'source_course_key': unicode(source_course_key)} if not destination_course_data: destination_course_data = self.destination_course_data rerun_course_data.update(destination_course_data) destination_course_key = _get_course_id(self.store, destination_course_data) # post the request course_url = get_url('course_handler', destination_course_key, 'course_key_string') response = self.client.ajax_post(course_url, rerun_course_data) # verify response self.assertEqual(response.status_code, response_code) if not expect_error: json_resp = parse_json(response) self.assertNotIn('ErrMsg', json_resp) destination_course_key = CourseKey.from_string(json_resp['destination_course_key']) return destination_course_key def get_course_listing_elements(self, html, course_key): """Returns the elements in the course listing section of html that have the given course_key""" return html.cssselect('.course-item[data-course-key="{}"]'.format(unicode(course_key))) def get_unsucceeded_course_action_elements(self, html, course_key): """Returns the elements in the unsucceeded course action section that have the given course_key""" return html.cssselect('.courses-processing li[data-course-key="{}"]'.format(unicode(course_key))) def assertInCourseListing(self, course_key): """ Asserts that the given course key is in the accessible course listing section of the html and NOT in the unsucceeded course action section of the html. """ course_listing = lxml.html.fromstring(self.client.get_html('/home/').content) self.assertEqual(len(self.get_course_listing_elements(course_listing, course_key)), 1) self.assertEqual(len(self.get_unsucceeded_course_action_elements(course_listing, course_key)), 0) def assertInUnsucceededCourseActions(self, course_key): """ Asserts that the given course key is in the unsucceeded course action section of the html and NOT in the accessible course listing section of the html. """ course_listing = lxml.html.fromstring(self.client.get_html('/home/').content) self.assertEqual(len(self.get_course_listing_elements(course_listing, course_key)), 0) self.assertEqual(len(self.get_unsucceeded_course_action_elements(course_listing, course_key)), 1) def verify_rerun_course(self, source_course_key, destination_course_key, destination_display_name): """ Verify the contents of the course rerun action """ rerun_state = CourseRerunState.objects.find_first(course_key=destination_course_key) expected_states = { 'state': CourseRerunUIStateManager.State.SUCCEEDED, 'display_name': destination_display_name, 'source_course_key': source_course_key, 'course_key': destination_course_key, 'should_display': True, } for field_name, expected_value in expected_states.iteritems(): self.assertEquals(getattr(rerun_state, field_name), expected_value) # Verify that the creator is now enrolled in the course. self.assertTrue(CourseEnrollment.is_enrolled(self.user, destination_course_key)) # Verify both courses are in the course listing section self.assertInCourseListing(source_course_key) self.assertInCourseListing(destination_course_key) def test_rerun_course_no_videos_in_val(self): """ Test when rerunning a course with no videos, VAL copies nothing """ source_course = CourseFactory.create() destination_course_key = self.post_rerun_request(source_course.id) self.verify_rerun_course(source_course.id, destination_course_key, self.destination_course_data['display_name']) videos = list(get_videos_for_course(destination_course_key)) self.assertEqual(0, len(videos)) self.assertInCourseListing(destination_course_key) def test_rerun_course_success(self): source_course = CourseFactory.create() create_video( dict( edx_video_id="tree-hugger", courses=[unicode(source_course.id)], status='test', duration=2, encoded_videos=[] ) ) destination_course_key = self.post_rerun_request(source_course.id) self.verify_rerun_course(source_course.id, destination_course_key, self.destination_course_data['display_name']) # Verify that the VAL copies videos to the rerun source_videos = list(get_videos_for_course(source_course.id)) target_videos = list(get_videos_for_course(destination_course_key)) self.assertEqual(1, len(source_videos)) self.assertEqual(source_videos, target_videos) def test_rerun_course_resets_advertised_date(self): source_course = CourseFactory.create(advertised_start="01-12-2015") destination_course_key = self.post_rerun_request(source_course.id) destination_course = self.store.get_course(destination_course_key) self.assertEqual(None, destination_course.advertised_start) def test_rerun_of_rerun(self): source_course = CourseFactory.create() rerun_course_key = self.post_rerun_request(source_course.id) rerun_of_rerun_data = { 'org': rerun_course_key.org, 'number': rerun_course_key.course, 'display_name': 'rerun of rerun', 'run': 'rerun2' } rerun_of_rerun_course_key = self.post_rerun_request(rerun_course_key, rerun_of_rerun_data) self.verify_rerun_course(rerun_course_key, rerun_of_rerun_course_key, rerun_of_rerun_data['display_name']) def test_rerun_course_fail_no_source_course(self): existent_course_key = CourseFactory.create().id non_existent_course_key = CourseLocator("org", "non_existent_course", "non_existent_run") destination_course_key = self.post_rerun_request(non_existent_course_key) # Verify that the course rerun action is marked failed rerun_state = CourseRerunState.objects.find_first(course_key=destination_course_key) self.assertEquals(rerun_state.state, CourseRerunUIStateManager.State.FAILED) self.assertIn("Cannot find a course at", rerun_state.message) # Verify that the creator is not enrolled in the course. self.assertFalse(CourseEnrollment.is_enrolled(self.user, non_existent_course_key)) # Verify that the existing course continues to be in the course listings self.assertInCourseListing(existent_course_key) # Verify that the failed course is NOT in the course listings self.assertInUnsucceededCourseActions(destination_course_key) def test_rerun_course_fail_duplicate_course(self): existent_course_key = CourseFactory.create().id destination_course_data = { 'org': existent_course_key.org, 'number': existent_course_key.course, 'display_name': 'existing course', 'run': existent_course_key.run } destination_course_key = self.post_rerun_request( existent_course_key, destination_course_data, expect_error=True ) # Verify that the course rerun action doesn't exist with self.assertRaises(CourseActionStateItemNotFoundError): CourseRerunState.objects.find_first(course_key=destination_course_key) # Verify that the existing course continues to be in the course listing self.assertInCourseListing(existent_course_key) def test_rerun_with_permission_denied(self): with mock.patch.dict('django.conf.settings.FEATURES', {"ENABLE_CREATOR_GROUP": True}): source_course = CourseFactory.create() auth.add_users(self.user, CourseCreatorRole(), self.user) self.user.is_staff = False self.user.save() self.post_rerun_request(source_course.id, response_code=403, expect_error=True) def test_rerun_error(self): error_message = "Mock Error Message" with mock.patch( 'xmodule.modulestore.mixed.MixedModuleStore.clone_course', mock.Mock(side_effect=Exception(error_message)) ): source_course = CourseFactory.create() destination_course_key = self.post_rerun_request(source_course.id) rerun_state = CourseRerunState.objects.find_first(course_key=destination_course_key) self.assertEquals(rerun_state.state, CourseRerunUIStateManager.State.FAILED) self.assertIn(error_message, rerun_state.message) def test_rerun_error_trunc_message(self): """ CourseActionUIState.message is sometimes populated with the contents of Python tracebacks. This test ensures we don't crash when attempting to insert a value exceeding its max_length (note that sqlite does not complain if this happens, but MySQL throws an error). """ with mock.patch( 'xmodule.modulestore.mixed.MixedModuleStore.clone_course', mock.Mock(side_effect=Exception()), ): source_course = CourseFactory.create() message_too_long = "traceback".rjust(CourseRerunState.MAX_MESSAGE_LENGTH * 2, '-') with mock.patch('traceback.format_exc', return_value=message_too_long): destination_course_key = self.post_rerun_request(source_course.id) rerun_state = CourseRerunState.objects.find_first(course_key=destination_course_key) self.assertEquals(rerun_state.state, CourseRerunUIStateManager.State.FAILED) self.assertTrue(rerun_state.message.endswith("traceback")) self.assertEqual(len(rerun_state.message), CourseRerunState.MAX_MESSAGE_LENGTH) def test_rerun_course_wiki_slug(self): """ Test that unique wiki_slug is assigned to rerun course. """ course_data = { 'org': 'edX', 'number': '123', 'display_name': 'Rerun Course', 'run': '2013' } source_wiki_slug = '{0}.{1}.{2}'.format(course_data['org'], course_data['number'], course_data['run']) source_course_key = _get_course_id(self.store, course_data) _create_course(self, source_course_key, course_data) source_course = self.store.get_course(source_course_key) # Verify created course's wiki_slug. self.assertEquals(source_course.wiki_slug, source_wiki_slug) destination_course_data = course_data destination_course_data['run'] = '2013_Rerun' destination_course_key = self.post_rerun_request( source_course.id, destination_course_data=destination_course_data ) self.verify_rerun_course(source_course.id, destination_course_key, destination_course_data['display_name']) destination_course = self.store.get_course(destination_course_key) destination_wiki_slug = '{0}.{1}.{2}'.format( destination_course.id.org, destination_course.id.course, destination_course.id.run ) # Verify rerun course's wiki_slug. self.assertEquals(destination_course.wiki_slug, destination_wiki_slug) class ContentLicenseTest(ContentStoreTestCase): """ Tests around content licenses """ def test_course_license_export(self): content_store = contentstore() root_dir = path(mkdtemp_clean()) self.course.license = "creative-commons: BY SA" self.store.update_item(self.course, None) export_course_to_xml(self.store, content_store, self.course.id, root_dir, 'test_license') fname = "{block}.xml".format(block=self.course.scope_ids.usage_id.block_id) run_file_path = root_dir / "test_license" / "course" / fname run_xml = etree.parse(run_file_path.open()) self.assertEqual(run_xml.getroot().get("license"), "creative-commons: BY SA") def test_video_license_export(self): content_store = contentstore() root_dir = path(mkdtemp_clean()) video_descriptor = ItemFactory.create( parent_location=self.course.location, category='video', license="all-rights-reserved" ) export_course_to_xml(self.store, content_store, self.course.id, root_dir, 'test_license') fname = "{block}.xml".format(block=video_descriptor.scope_ids.usage_id.block_id) video_file_path = root_dir / "test_license" / "video" / fname video_xml = etree.parse(video_file_path.open()) self.assertEqual(video_xml.getroot().get("license"), "all-rights-reserved") def test_license_import(self): course_items = import_course_from_xml( self.store, self.user.id, TEST_DATA_DIR, ['toy'], create_if_not_present=True ) course = course_items[0] self.assertEqual(course.license, "creative-commons: BY") videos = self.store.get_items(course.id, qualifiers={'category': 'video'}) self.assertEqual(videos[0].license, "all-rights-reserved") class EntryPageTestCase(TestCase): """ Tests entry pages that aren't specific to a course. """ def setUp(self): super(EntryPageTestCase, self).setUp() self.client = AjaxEnabledTestClient() def _test_page(self, page, status_code=200): resp = self.client.get_html(page) self.assertEqual(resp.status_code, status_code) def test_how_it_works(self): self._test_page("/howitworks") def test_signup(self): self._test_page("/signup") def test_login(self): self._test_page("/signin") def test_logout(self): # Logout redirects. self._test_page("/logout", 302) class SigninPageTestCase(TestCase): """ Tests that the CSRF token is directly included in the signin form. This is important to make sure that the script is functional independently of any other script. """ def test_csrf_token_is_present_in_form(self): # Expected html: # <form> # ... # <fieldset> # ... # <input name="csrfmiddlewaretoken" value="..."> # ... # </fieldset> # ... #</form> response = self.client.get("/signin") csrf_token = response.cookies.get("csrftoken") form = lxml.html.fromstring(response.content).get_element_by_id("login_form") csrf_input_field = form.find(".//input[@name='csrfmiddlewaretoken']") self.assertIsNotNone(csrf_token) self.assertIsNotNone(csrf_token.value) self.assertIsNotNone(csrf_input_field) self.assertEqual(csrf_token.value, csrf_input_field.attrib["value"]) def _create_course(test, course_key, course_data): """ Creates a course via an AJAX request and verifies the URL returned in the response. """ course_url = get_url('course_handler', course_key, 'course_key_string') response = test.client.ajax_post(course_url, course_data) test.assertEqual(response.status_code, 200) data = parse_json(response) test.assertNotIn('ErrMsg', data) test.assertEqual(data['url'], course_url) def _get_course_id(store, course_data): """Returns the course ID.""" return store.make_course_key(course_data['org'], course_data['number'], course_data['run'])
pepeportela/edx-platform
cms/djangoapps/contentstore/tests/test_contentstore.py
Python
agpl-3.0
96,743
""" Rainbow-shooter ======== {Rainbow-shooter long description} {Link to binaries} Features -------- - item 1 - item 2 Development Version ------------------- Link to git """ import os try: from setuptools import setup except ImportError: from distutils.core import setup setup( name='Rainbow_shooter', version='0.1', url='http://github.com/gnud/rainbow-shooter', license='GPL', author='Damjan Dimitrioski', author_email='[email protected]', description='A slideshow that show colors from a list in fullscreen.', long_description=__doc__, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Users', 'License :: OSI Approved :: GPL License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules' ], packages=['rainbow_shooter'], package_data={ 'rainbow-shooter.share/': ['ui/*'] }, platforms='any' )
gnud/rainbow-shooter
setup.py
Python
gpl-3.0
1,045
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None from collections import Counter class Solution(object): def findFrequentTreeSum(self, root): """ :type root: TreeNode :rtype: List[int] """ if not root: return [] sums = Counter() def postorder(root): ls, rs = 0, 0 if root.left: ls = postorder(root.left) if root.right: rs = postorder(root.right) # visit root now s = root.val + ls + rs sums[s] += 1 return s postorder(root) maxSumCount = max(sums.itervalues()) return [s for s, c in sums.iteritems() if c == maxSumCount] import utils print Solution().findFrequentTreeSum(utils.maketree([5, 2, -3]))
xiaonanln/myleetcode-python
src/508. Most Frequent Subtree Sum - 2.py
Python
apache-2.0
776
# -*- coding: utf-8 -*- from BeautifulSoup import BeautifulSoup from BeautifulSoup import BeautifulStoneSoup import urllib2 import requests import os import sys import re import codecs def htmlTodev(text): def fixup(m): text = m.group(0) if text[:2] == "&#": # character reference try: if text[:3] == "&#x": return unichr(int(text[3:-1], 16)) else: return unichr(int(text[2:-1])) except ValueError: pass else: # named entity try: text = unichr(htmlentitydefs.name2codepoint[text[1:-1]]) except KeyError: pass return text # leave as is return re.sub("&#?\w+;", fixup, text) def devToVel(value): inHex = [ "05", "06", "07", "08", "09", "0a", "0b", "60", "0c", "0f", "10", "13", "14", "02", "01", "03", "3d", "4d" ] outVH = [ "a", "aa", "i", "ii", "u", "uu", ".r", ".rr", ".l", "e", "ai", "o", "au", ".m", "~l", ".h", "'", "" ] matIn = [ "3e", "3f", "40", "41", "42", "43", "44", "62", "47", "48", "4b", "4c" ] consIn = [ "15", "16", "17", "18", "19", "1a", "1b", "1c", "1d", "1e", "1f", "20", "21", "22", "23", "24", "25", "26", "27", "28", "2a", "2b", "2c", "2d", "2e", "2f", "30", "32", "35", "36", "37", "38", "39", "00" ] orig = value.strip().decode("utf-8") output = "" wasCons = False for i in range(len(orig)): origC = orig[i] l = "{0:04x}".format(ord(origC)) lenL = len(l) if lenL == 0: l = "0000" if lenL == 1: l = "000" + l if lenL == 2: l = "00" + l if lenL == 3: l = "0" + l check = l[2:] init = l[0:2] if not init == "09": check = "00" consOut = [ "k", "kh", "g", "gh", "f", "c", "ch", "j", "jh", "~n", ".t", ".th", ".d", ".dh", ".n", "t", "th", "d", "dh", "n", "p", "ph", "b", "bh", "m", "y", "r", "l", "v", "z", ".s", "s", "h", origC + "" ] for j in range (len(inHex)): if check == inHex[j]: if check == "03" or check == "01" or check == "02" or check == "3d": if wasCons: output = output+"a" + outVH[j] else: output = output+outVH[j] else: output = output+outVH[j] wasCons = False for j in range (len(consIn)): if check == consIn[j]: if wasCons: output = output+"a" + consOut[j] else: output = output+consOut[j] if not check == "00": wasCons = True else: wasCons = False if i == len(orig) - 1: output = output+"a" for j in range (len(matIn)): if check == matIn[j]: output = output+outVH[j + 1] wasCons = False return output def getHTMLData(name, url, type): out = open(name+'_'+type+'.html','w') #print url+word resp = requests.get(url) #print resp.text out.write('url: '+url.encode('utf-8')) out.write(resp.text.encode('utf-8')) out.close() return resp.text def writeToFile(merged, split, san, out, result, rule, id): out.write(id+':'+merged+':') for sa in split: out.write(sa+',') out.write(':') if san != None: out.write(san+',') else: out.write(',') out.write(':'+rule+':'+result+'\n') def inriaParse(data): if data != None: soup = BeautifulSoup(data) if soup != None and len(soup.findAll('span', {"class": "devared", "lang": "sa"})) == 3: #result = soup.findAll('span', {"class": "red"})[2].getText() result = htmlTodev(soup.findAll('span', {"class": "devared", "lang": "sa"})[2].getText()).encode('utf-8') #result = str(BeautifulStoneSoup(result.decode("latin-1").encode("utf-8"), convertEntities=BeautifulStoneSoup.ALL_ENTITIES)) return result return '' def getMerged(id, word1, word2, parentDir): inrData = getHTMLData(os.path.join(parentDir,id),'http://sanskrit.inria.fr/cgi-bin/SKT/sktsandhier?lex=SH&l='+devToVel(word1.strip())+'&r='+devToVel(word2.strip())+'&t=VH&k=external','ext.inr') if inrData != None: return inriaParse(inrData) return '' def getFilMerged(id, word1, word2, parentDir): inrFilData = getHTMLData(os.path.join(parentDir,id),'http://sanskrit.inria.fr/cgi-bin/SKT/sktsandhier?lex=SH&l='+devToVel(word1.strip())+'&r='+devToVel(word2.strip())+'&t=VH&k=internal','int.inr') if inrFilData != None: return inriaParse(inrFilData) return '' def getRecMerge(id, word, list, parentDir): if list and len(list) > 0: result = getMerged(id, word, list[0], parentDir) i = 0; if(len(list[1:]) > 0): i=i+1 result = getRecMerge(id+'_'+str(i), result, list[1:], parentDir) return result def getRecFilMerge(id, word, list, parentDir): if list and len(list) > 0: i = 0; result = getFilMerged(id, word, list[0], parentDir) if(len(list[1:]) > 0): i=i+1 result = getRecFilMerge(id+'_'+str(i), result, list[1:], parentDir) return result def compareResult(merged, split, result, out, rule, id): if merged == result: writeToFile(merged, split, result, out, '1', rule, id) else: writeToFile(merged, split, result, out, '0', rule, id) def processFile(filePath): if os.path.isfile(filePath): parentDir = os.path.dirname(os.path.abspath(filePath)) parentDir = os.path.join(parentDir,sys.argv[1]+'_output') if not os.path.exists(parentDir): os.makedirs(parentDir) inrOut = open(filePath+'.ext.inria','w') inrFilOut = open(filePath+'.int.inria','w') for word in open(filePath).readlines(): word = word.strip().split(',') print word[0] wordSplit = word[2].replace('"','').split('+') merged = word[1].replace(',','') result = getRecMerge(word[0], wordSplit[0], wordSplit[1:], parentDir) filResult = getRecFilMerge(word[0], wordSplit[0], wordSplit[1:], parentDir) compareResult(merged, wordSplit, result, inrOut, word[3].strip(), word[0].strip()) compareResult(merged, wordSplit, filResult, inrFilOut, word[3].strip(), word[0].strip()) inrOut.close() inrFilOut.close() def processFolder(folderPath): if os.path.isdir(folderPath): for path in os.listdir(folderPath): print os.path.join(folderPath, path) processFolder(os.path.join(folderPath, path)) else: processFile(folderPath) def main(): path = sys.argv[1] processFolder(path) if __name__ =="__main__": main()
sanskritiitd/sanskrit
merging/inria.py
Python
gpl-3.0
7,253
import unittest class Solution: def __init__(self): self.candidates = None self.num_candidates = 0 self.combination = [] self.result = [] def combinationSum2(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ candidates.sort() self.candidates = candidates self.num_candidates = len(candidates) self._combine(target, 0) return self.result def _combine(self, target, start_index): for i in range(start_index, self.num_candidates): candidate = self.candidates[i] if i > start_index and candidate == self.candidates[i - 1]: continue if candidate == target: self.result.append(self.combination + [candidate]) break elif candidate > target: break self.combination.append(candidate) self._combine(target - candidate, i + 1) self.combination.pop() class Test(unittest.TestCase): def test(self): self._test([10, 1, 2, 7, 6, 1, 5], 8, [ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ]) def _test(self, candidates, target, expected): actual = Solution().combinationSum2(candidates, target) self.assertCountEqual(expected, actual) if __name__ == '__main__': unittest.main()
chrisxue815/leetcode_python
problems/test_0040_backtrack.py
Python
unlicense
1,493
# Spawn Group file created with PSWG Planetary Spawn Tool import sys from java.util import Vector from services.spawn import DynamicSpawnGroup from services.spawn import MobileTemplate def addDynamicGroup(core): dynamicGroup = DynamicSpawnGroup() mobileTemplates = Vector() mobileTemplates.add('hidden_daggers_activist') mobileTemplates.add('hidden_daggers_dissident') mobileTemplates.add('hidden_daggers_extremist') mobileTemplates.add('hidden_daggers_leader') mobileTemplates.add('hidden_daggers_lieutenant') dynamicGroup.setMobiles(mobileTemplates) dynamicGroup.setGroupMembersNumber(3) dynamicGroup.setName('corellia_hidden_daggers') dynamicGroup.setMaxSpawns(-1) dynamicGroup.setMinSpawnDistance(150) core.spawnService.addDynamicGroup('corellia_hidden_daggers', dynamicGroup) return
agry/NGECore2
scripts/mobiles/dynamicgroups/corellia_hidden_daggers.py
Python
lgpl-3.0
803
import django.contrib.sites.managers import django.db.models.manager from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("sites", "0002_alter_domain_unique"), ("enhydris", "0109_remove_is_automatic"), ] operations = [ migrations.AddField( model_name="gentity", name="sites", field=models.ManyToManyField(to="sites.Site"), ), migrations.AlterModelManagers( name="station", managers=[ ("objects", django.db.models.manager.Manager()), ("on_site", django.contrib.sites.managers.CurrentSiteManager()), ], ), ]
openmeteo/enhydris
enhydris/migrations/0110_sites.py
Python
agpl-3.0
723
import unittest import pickle from monty.design_patterns import singleton, cached_class class SingletonTest(unittest.TestCase): def test_singleton(self): @singleton class A: pass a1 = A() a2 = A() self.assertEqual(id(a1), id(a2)) @cached_class class A: def __init__(self, val): self.val = val def __eq__(self, other): return self.val == other.val def __getinitargs__(self): return (self.val,) def __getnewargs__(self): return (self.val,) class CachedClassTest(unittest.TestCase): def test_cached_class(self): a1a = A(1) a1b = A(1) a2 = A(2) self.assertEqual(id(a1a), id(a1b)) self.assertNotEqual(id(a1a), id(a2)) # def test_pickle(self): # a = A(2) # o = pickle.dumps(a) # self.assertEqual(a, pickle.loads(o)) if __name__ == "__main__": unittest.main()
materialsvirtuallab/monty
tests/test_design_patterns.py
Python
mit
949
""" The Fibonacci sequence is defined using the following recursive formula: F(0) = 0 F(1) = 1 F(M) = F(M - 1) + F(M - 2) if M >= 2 A small frog wants to get to the other side of a river. The frog is initially located at one bank of the river (position −1) and wants to get to the other bank (position N). The frog can jump over any distance F(K), where F(K) is the K-th Fibonacci number. Luckily, there are many leaves on the river, and the frog can jump between the leaves, but only in the direction of the bank at position N. The leaves on the river are represented in a zero-indexed array A consisting of N integers. Consecutive elements of array A represent consecutive positions from 0 to N − 1 on the river. Array A contains only 0s and/or 1s: 0 represents a position without a leaf; 1 represents a position containing a leaf. The goal is to count the minimum number of jumps in which the frog can get to the other side of the river (from position −1 to position N). The frog can jump between positions −1 and N (the banks of the river) and every position containing a leaf. For example, consider array A such that: A[0] = 0 A[1] = 0 A[2] = 0 A[3] = 1 A[4] = 1 A[5] = 0 A[6] = 1 A[7] = 0 A[8] = 0 A[9] = 0 A[10] = 0 The frog can make three jumps of length F(5) = 5, F(3) = 2 and F(5) = 5. Write a function: def solution(A) that, given a zero-indexed array A consisting of N integers, returns the minimum number of jumps by which the frog can get to the other side of the river. If the frog cannot reach the other side of the river, the function should return −1. For example, given: A[0] = 0 A[1] = 0 A[2] = 0 A[3] = 1 A[4] = 1 A[5] = 0 A[6] = 1 A[7] = 0 A[8] = 0 A[9] = 0 A[10] = 0 the function should return 3, as explained above. Assume that: N is an integer within the range [0..100,000]; each element of array A is an integer that can have one of the following values: 0, 1. Complexity: expected worst-case time complexity is O(N*log(N)); expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments). Elements of input arrays can be modified. """ def get_fib_seq_up_to_n(N): fib = [0] * (27) fib[1] = 1 for i in range(2, 27): fib[i] = fib[i - 1] + fib[i - 2] if fib[i] > N: return fib[2:i] else: last_valid = i def solution(A): # you can always step on the other shore, this simplifies the algorithm A.append(1) fib_set = get_fib_seq_up_to_n(len(A)) # this array will hold the optimal jump count that reaches this index reachable = [-1] * (len(A)) # get the leafs that can be reached from the starting shore for jump in fib_set: if A[jump - 1] == 1: reachable[jump - 1] = 1 # iterate all the positions until you reach the other shore for idx in range(len(A)): # ignore non-leafs and already found paths if A[idx] == 0 or reachable[idx] > 0: continue # get the optimal jump count to reach this leaf min_idx = -1 min_value = 100000 for jump in fib_set: previous_idx = idx - jump if previous_idx < 0: break if reachable[previous_idx] > 0 and min_value > reachable[ previous_idx]: min_value = reachable[previous_idx] min_idx = previous_idx if min_idx != -1: reachable[idx] = min_value + 1 return reachable[len(A) - 1]
Dineshkarthik/codility_training
Lesson 13 - Fibonacci numbers/fib_frog.py
Python
gpl-3.0
3,640
# Copyright 2013 - Noorul Islam K M # # 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 keystoneclient.auth.identity import v2 as v2_auth from keystoneclient.auth.identity import v3 as v3_auth from keystoneclient import discover from keystoneclient import exceptions as ks_exc from keystoneclient import session from oslo_utils import strutils from urllib import parse as urlparse from solumclient.common.apiclient import auth from solumclient.common.apiclient import exceptions from solumclient.common import exc def _discover_auth_versions(session, auth_url): # discover the API versions the server is supporting based on the # given URL v2_auth_url = None v3_auth_url = None try: ks_discover = discover.Discover(session=session, auth_url=auth_url) v2_auth_url = ks_discover.url_for('2.0') v3_auth_url = ks_discover.url_for('3.0') except ks_exc.DiscoveryFailure: raise except exceptions.ClientException: # Identity service may not support discovery. In that case, # try to determine version from auth_url url_parts = urlparse.urlparse(auth_url) (scheme, netloc, path, params, query, fragment) = url_parts path = path.lower() if path.startswith('/v3'): v3_auth_url = auth_url elif path.startswith('/v2'): v2_auth_url = auth_url else: raise exc.CommandError('Unable to determine the Keystone ' 'version to authenticate with ' 'using the given auth_url.') return v2_auth_url, v3_auth_url def _get_keystone_session(**kwargs): # TODO(fabgia): the heavy lifting here should be really done by Keystone. # Unfortunately Keystone does not support a richer method to perform # discovery and return a single viable URL. A bug against Keystone has # been filed: https://bugs.launchpad.net/python-keystoneclient/+bug/1330677 # first create a Keystone session cacert = kwargs.pop('cacert', None) cert = kwargs.pop('cert', None) key = kwargs.pop('key', None) insecure = kwargs.pop('insecure', False) auth_url = kwargs.pop('auth_url', None) project_id = kwargs.pop('project_id', None) project_name = kwargs.pop('project_name', None) if insecure: verify = False else: verify = cacert or True if cert and key: # passing cert and key together is deprecated in favour of the # requests lib form of having the cert and key as a tuple cert = (cert, key) # create the keystone client session ks_session = session.Session(verify=verify, cert=cert) v2_auth_url, v3_auth_url = _discover_auth_versions(ks_session, auth_url) username = kwargs.pop('username', None) user_id = kwargs.pop('user_id', None) user_domain_name = kwargs.pop('user_domain_name', None) user_domain_id = kwargs.pop('user_domain_id', None) project_domain_name = kwargs.pop('project_domain_name', None) project_domain_id = kwargs.pop('project_domain_id', None) auth = None use_domain = (user_domain_id or user_domain_name or project_domain_id or project_domain_name) use_v3 = v3_auth_url and (use_domain or (not v2_auth_url)) use_v2 = v2_auth_url and not use_domain if use_v3: # the auth_url as v3 specified # e.g. http://no.where:5000/v3 # Keystone will return only v3 as viable option auth = v3_auth.Password( v3_auth_url, username=username, password=kwargs.pop('password', None), user_id=user_id, user_domain_name=user_domain_name, user_domain_id=user_domain_id, project_name=project_name, project_id=project_id, project_domain_name=project_domain_name, project_domain_id=project_domain_id) elif use_v2: # the auth_url as v2 specified # e.g. http://no.where:5000/v2.0 # Keystone will return only v2 as viable option auth = v2_auth.Password( v2_auth_url, username, kwargs.pop('password', None), tenant_id=project_id, tenant_name=project_name) else: raise exc.CommandError('Unable to determine the Keystone version ' 'to authenticate with using the given ' 'auth_url.') ks_session.auth = auth return ks_session def _get_endpoint(ks_session, **kwargs): """Get an endpoint using the provided keystone session.""" # set service specific endpoint types endpoint_type = kwargs.get('endpoint_type') or 'publicURL' service_type = kwargs.get('service_type') or 'application_deployment' endpoint = ks_session.get_endpoint(service_type=service_type, interface=endpoint_type, region_name=kwargs.get('region_name')) return endpoint class KeystoneAuthPlugin(auth.BaseAuthPlugin): opt_names = ['tenant_id', 'region_name', 'auth_token', 'service_type', 'endpoint_type', 'cacert', 'auth_url', 'insecure', 'cert_file', 'key_file', 'cert', 'key', 'tenant_name', 'project_name', 'project_id', 'project_domain_id', 'project_domain_name', 'user_id', 'user_domain_id', 'user_domain_name', 'password', 'username', 'endpoint'] def __init__(self, auth_system=None, **kwargs): self.opt_names.extend(self.common_opt_names) super(KeystoneAuthPlugin, self).__init__(auth_system, **kwargs) def _do_authenticate(self, http_client): token = self.opts.get('token') or self.opts.get('auth_token') endpoint = self.opts.get('endpoint') if not (token and endpoint): project_id = (self.opts.get('project_id') or self.opts.get('tenant_id')) project_name = (self.opts.get('project_name') or self.opts.get('tenant_name')) ks_kwargs = { 'username': self.opts.get('username'), 'password': self.opts.get('password'), 'user_id': self.opts.get('user_id'), 'user_domain_id': self.opts.get('user_domain_id'), 'user_domain_name': self.opts.get('user_domain_name'), 'project_id': project_id, 'project_name': project_name, 'project_domain_name': self.opts.get('project_domain_name'), 'project_domain_id': self.opts.get('project_domain_id'), 'auth_url': self.opts.get('auth_url'), 'cacert': self.opts.get('cacert'), 'cert': self.opts.get('cert'), 'key': self.opts.get('key'), 'insecure': strutils.bool_from_string( self.opts.get('insecure')), 'endpoint_type': self.opts.get('endpoint_type'), } # retrieve session ks_session = _get_keystone_session(**ks_kwargs) token = ks_session.get_token() endpoint = (self.opts.get('endpoint') or _get_endpoint(ks_session, **ks_kwargs)) self.opts['token'] = token self.opts['endpoint'] = endpoint def token_and_endpoint(self, endpoint_type, service_type): token = self.opts.get('token') if callable(token): token = token() return token, self.opts.get('endpoint') def sufficient_options(self): """Check if all required options are present. :raises: AuthPluginOptionsMissing """ has_token = self.opts.get('token') or self.opts.get('auth_token') no_auth = has_token and self.opts.get('endpoint') has_project = (self.opts.get('project_id') or (self.opts.get('project_name') and (self.opts.get('user_domain_name') or self.opts.get('user_domain_id')))) has_tenant = self.opts.get('tenant_id') or self.opts.get('tenant_name') has_credential = (self.opts.get('username') and (has_project or has_tenant) and self.opts.get('password') and self.opts.get('auth_url')) missing = not (no_auth or has_credential) if missing: missing_opts = [] opts = ['token', 'endpoint', 'username', 'password', 'auth_url', 'tenant_id', 'tenant_name'] for opt in opts: if not self.opts.get(opt): missing_opts.append(opt) raise exceptions.AuthPluginOptionsMissing(missing_opts)
openstack/python-solumclient
solumclient/common/auth.py
Python
apache-2.0
9,330
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class SaleConfiguration(models.TransientModel): _inherit = 'sale.config.settings' security_lead = fields.Float(related='company_id.security_lead', string="Sales Safety Days *") module_delivery = fields.Selection([ (0, 'No shipping costs on sales orders'), (1, 'Allow adding shipping costs') ], "Shipping") default_picking_policy = fields.Selection([ (0, 'Ship products when some are available, and allow back orders'), (1, 'Ship all products at once, without back orders') ], "Default Shipping Policy") group_mrp_properties = fields.Selection([ (0, "Don't use manufacturing properties (recommended as its easier)"), (1, 'Allow setting manufacturing order properties per order line (advanced)') ], "Properties on SO Lines", implied_group='sale.group_mrp_properties', help="Allows you to tag sales order lines with properties.") group_route_so_lines = fields.Selection([ (0, 'No order specific routes like MTO or drop shipping'), (1, 'Choose specific routes on sales order lines (advanced)') ], "Order Routing", implied_group='sale_stock.group_route_so_lines') module_sale_order_dates = fields.Selection([ (0, 'Procurements and deliveries dates are based on the sales order dates'), (1, 'Allow to modify the sales order dates to postpone deliveries and procurements') ], "Date") @api.model def get_default_sale_config(self, fields): default_picking_policy = self.env['ir.values'].get_default('sale.order', 'picking_policy') return { 'default_picking_policy': 1 if default_picking_policy == 'one' else 0, } @api.multi def set_sale_defaults(self): default_picking_policy = 'one' if self.default_picking_policy else 'direct' self.env['ir.values'].sudo().set_default('sale.order', 'picking_policy', default_picking_policy) return super(SaleConfiguration, self).set_sale_defaults()
chienlieu2017/it_management
odoo/addons/sale_stock/models/sale_config_settings.py
Python
gpl-3.0
2,165
__author__ = 'sarangis' class IllegalArgumentException(ValueError): pass class InvalidTypeException(ValueError): pass class InvalidInsertionPointException(ValueError): pass class InvalidInstructionException(ValueError): pass class NoBBTerminatorException(ValueError): pass class InvalidUsageModel(ValueError): pass class PassNotRunException(ValueError): pass
ssarangi/spiderjit
src/ir/exceptions.py
Python
mit
396
import doctest doctest.testfile('api_examples.txt')
dtcooper/python-fitparse
tests/doctests.py
Python
mit
53
#!/usr/env/python from __future__ import division, print_function ## Import General Tools import sys import os import argparse import logging import subprocess import datetime import pytz import ephem ##------------------------------------------------------------------------- ## Define Camera Class ##------------------------------------------------------------------------- def Camera(object): '''Class representing the camera configuration ''' def __init__(self, camera='Canon 5D',\ mode=None, aperture=None,\ exposure=None, ISO=None,\ port=None, logger=None): self.camera_type = camera self.mode = mode self.aperture = aperture self.exposure = exposure self.ISO = ISO self.port = port self.logger = logger ## Gphoto self.gphoto = 'sudo /sw/bin/gphoto2' ## Commands if self.camera_type == 'Canon 5D': self.imageformat_cmd = '/main/settings/imageformat' self.imageformat_list = {'RAW': '0'} self.focusmode_cmd = '/main/settings/focusmode' self.focusmode_list = {'manual': '3'} self.mode_cmd = '' self.mode_list = {'Av': 0, 'Tv': 0, 'M': 0} self.aperture_cmd = '' self.aperture_list = {'1.4': 0, '1.8': 0, '2.0': 0, '2.8': 0, '3.5': 0, '4.0': 0, '4.5': 0, '5.6': 0, '6.3': 0, '8.0': 0, } self.exposure_cmd = '' self.exposure_list = {} self.ISO_cmd = '' self.ISO_list = {'50': 0, '100': 0, '200': 0, '800': 0, '1600': 0, '3200': 0, '6400': 0, '12800': 0} def set_image_format(self, format): assert format in self.imageformat_list.keys() gphoto_command = '{} --port {} --set-config {}={}'.format(\ self.gphoto, self.port,\ self.imageformat_cmd, self.imageformat_list[format]) result = subprocess.call(gphoto_command, shell=True) if self.logger: self.logger.debug(result) def set_focus_mode(self, focusmode): assert focusmode in self.focusmode_list.keys() gphoto_command = '{} --port {} --set-config {}={}'.format(\ self.gphoto, self.port,\ self.focusmode_cmd, self.focusmode_list[focusmode]) result = subprocess.call(gphoto_command, shell=True) if self.logger: self.logger.debug(result) def set_mode(self, mode): assert mode in self.mode_list.keys() gphoto_command = '{} --port {} --set-config {}={}'.format(\ self.gphoto, self.port,\ self.mode_cmd, self.mode_list[mode]) result = subprocess.call(gphoto_command, shell=True) if self.logger: self.logger.debug(result) def set_aperture(self, aperture): assert aperture in self.aperture_list.keys() gphoto_command = '{} --port {} --set-config {}={}'.format(\ self.gphoto, self.port,\ self.aperture_cmd, self.aperture_list[aperture]) result = subprocess.call(gphoto_command, shell=True) if self.logger: self.logger.debug(result) def set_exposure(self, exposure): assert exposure in self.exposure_list.keys() gphoto_command = '{} --port {} --set-config {}={}'.format(\ self.gphoto, self.port,\ self.exposure_cmd, self.exposure_list[exposure]) result = subprocess.call(gphoto_command, shell=True) if self.logger: self.logger.debug(result) def set_ISO(self, ISO): assert ISO in self.ISO_list.keys() gphoto_command = '{} --port {} --set-config {}={}'.format(\ self.gphoto, self.port,\ self.ISO_cmd, self.ISO_list[exposure]) result = subprocess.call(gphoto_command, shell=True) if self.logger: self.logger.debug(result) def take_exposure(self): pass ##------------------------------------------------------------------------- ## Time Lapse Program ##------------------------------------------------------------------------- def time_lapse(port='usb:001,011'): logger = logging.getLogger('TimeLapseLogger') logger.setLevel(logging.DEBUG) ## Set up console output LogConsoleHandler = logging.StreamHandler() if args.verbose: LogConsoleHandler.setLevel(logging.DEBUG) else: LogConsoleHandler.setLevel(logging.INFO) LogFormat = logging.Formatter('%(asctime)23s %(levelname)8s: %(message)s') LogConsoleHandler.setFormatter(LogFormat) logger.addHandler(LogConsoleHandler) ## Set up file output today = datetime.datetime.now().strftime('%Y%m%d') LogFileName = os.path.join('/', 'var', 'log', 'TimeLapse', 'log_{}.txt'.format(today)) LogFileHandler = logging.FileHandler(LogFileName) LogFileHandler.setLevel(logging.DEBUG) LogFileHandler.setFormatter(LogFormat) logger.addHandler(LogFileHandler) ##------------------------------------------------------------------------- ## Use ephem to Calculate Sunrise, Sunset, Twilights ##------------------------------------------------------------------------- MLO = ephem.Observer() MLO.lon = "-155:34:33.9" MLO.lat = "+19:32:09.66" MLO.elevation = 3400.0 MLO.temp = 10.0 MLO.pressure = 680.0 MKO = ephem.Observer() MKO.lon = "-155:28:33.7" MKO.lat = "+19:49:31.81" MKO.elevation = 4200.0 MKO.temp = 1.0 MKO.pressure = 625.0 UTC = pytz.utc HST = pytz.timezone('Pacific/Honolulu') Observatory = MKO now = datetime.datetime.now(UTC) Observatory.date = now Observatory.date = datetime.datetime(2013, 8, 23, 8, 0, 0) the_Sun = ephem.Sun() the_Sun.compute(Observatory) if (the_Sun.alt < 0) and (now.astimezone(HST).hour < 12): today_noon = HST.localize(datetime.datetime(now.astimezone(HST).year, now.astimezone(HST).month, now.astimezone(HST).day-1, 12, 0, 0)).astimezone(UTC) Observatory.date = today_noon elif (the_Sun.alt < 0) and (now.astimezone(HST).hour >= 12): today_noon = HST.localize(datetime.datetime(now.astimezone(HST).year, now.astimezone(HST).month, now.astimezone(HST).day, 12, 0, 0)).astimezone(UTC) Observatory.date = today_noon Observatory.horizon = '0.0' sunset = UTC.localize(Observatory.next_setting(ephem.Sun()).datetime()) sunrise = UTC.localize(Observatory.next_rising(ephem.Sun()).datetime()) Observatory.horizon = '-6.0' civil_twilight_end = UTC.localize(Observatory.next_setting(ephem.Sun(), use_center=True).datetime()) civil_twilight_begin = UTC.localize(Observatory.next_rising(ephem.Sun(), use_center=True).datetime()) Observatory.horizon = '-12.0' nautical_twilight_end = UTC.localize(Observatory.next_setting(ephem.Sun(), use_center=True).datetime()) nautical_twilight_begin = UTC.localize(Observatory.next_rising(ephem.Sun(), use_center=True).datetime()) Observatory.horizon = '-18.0' astronomical_twilight_end = UTC.localize(Observatory.next_setting(ephem.Sun(), use_center=True).datetime()) astronomical_twilight_begin = UTC.localize(Observatory.next_rising(ephem.Sun(), use_center=True).datetime()) logger.info('Sunset: {}'.format(sunset.astimezone(HST).strftime('%Y/%m/%d %H:%M:%S HST'))) logger.info('Civil Twilight End: {}'.format(civil_twilight_end.astimezone(HST).strftime('%Y/%m/%d %H:%M:%S HST'))) logger.info('Nautical Twilight End: {}'.format(nautical_twilight_end.astimezone(HST).strftime('%Y/%m/%d %H:%M:%S HST'))) logger.info('Astronomical Twilight End: {}'.format(astronomical_twilight_end.astimezone(HST).strftime('%Y/%m/%d %H:%M:%S HST'))) logger.info('Astronomical Twilight Begin: {}'.format(astronomical_twilight_begin.astimezone(HST).strftime('%Y/%m/%d %H:%M:%S HST'))) logger.info('Nautical Twilight Begin: {}'.format(nautical_twilight_begin.astimezone(HST).strftime('%Y/%m/%d %H:%M:%S HST'))) logger.info('Civil Twilight Begin: {}'.format(civil_twilight_begin.astimezone(HST).strftime('%Y/%m/%d %H:%M:%S HST'))) logger.info('Sunrise: {}'.format(sunrise.astimezone(HST).strftime('%Y/%m/%d %H:%M:%S HST'))) sys.exit(0) ##------------------------------------------------------------------------- ## Configure Camera ##------------------------------------------------------------------------- cam = Camera(camera='Canon 5D', port=args.port, logger=logger) logger.info('Setting image format to RAW') cam.set_image_format('Raw') logger.info('Setting focus mode to manual') cam.set_focus_mode('manual') ##------------------------------------------------------------------------- ## Enter Main Time Lapse Loop ##------------------------------------------------------------------------- while True: now = datetime.datetime.now(tz=pytz.utc) if (now < sunset) or (now > sunrise): mode = 'Av' logger.info('It is day. Mode: {}'.format(mode)) cam.set_mode(mode) elif (now > sunset) and (now < civil_twilight_end): mode = 'Av' logger.info('It is evening (civil) twilight. Mode = {}'.format(mode)) cam.set_mode(mode) elif (now > civil_twilight_end) and (now < nautical_twilight_end): mode = 'Av' logger.info('It is evening (nautical) twilight. Mode = {}'.format(mode)) cam.set_mode(mode) elif (now > nautical_twilight_end) and (now < astronomical_twilight_end): mode = 'M' aperture = '2.0' exposure = '20' ISO = 1600 logger.info('It is evening (astronomical) twilight. Mode = {}. Av = {}. Tv = {}. ISO = {}.'.format(mode, aperture, exposure, iso)) cam.set_mode(mode) cam.set_aperture(aperture) cam.set_exposure(exposure) cam.set_ISO(ISO) elif now > astronomical_twilight_end: mode = 'M' aperture = '2.0' exposure = '20' ISO = 1600 logger.info('It is fully dark. Mode = {}. Av = {}. Tv = {}. ISO = {}.'.format(mode, aperture, exposure, iso)) cam.set_mode(mode) cam.set_aperture(aperture) cam.set_exposure(exposure) cam.set_ISO(ISO) cam.take_exposure() if __name__ == '__main__': ##------------------------------------------------------------------------- ## Parse Command Line Arguments ##------------------------------------------------------------------------- ## create a parser object for understanding command-line arguments parser = argparse.ArgumentParser( description="Program description.") ## add flags parser.add_argument("-v", "--verbose", action="store_true", dest="verbose", default=False, help="Be verbose! (default = False)") ## add arguments parser.add_argument("--port", type=str, dest="port", help="The port (use 'sudo gphoto2 --auto-detect' to find port.") args = parser.parse_args() time_lapse(port=args.port)
joshwalawender/RasPiProjects
DSLR_Control.py
Python
bsd-2-clause
11,902
""" This class interfaces with the Student Web Service, Term resource. """ import logging from datetime import datetime from restclients.sws import get_resource, QUARTER_SEQ, get_current_sws_version, parse_sws_date from restclients.models.sws import Term as TermModel from restclients.exceptions import DataFailureException from restclients.models.sws import TimeScheduleConstruction term_res_url_prefix = "/student/v5/term" logger = logging.getLogger(__name__) def get_term_by_year_and_quarter(year, quarter): """ Returns a restclients.models.sws.Term object, for the passed year and quarter. """ url = "%s/%s,%s.json" % (term_res_url_prefix, str(year), quarter.lower()) return _json_to_term_model(get_resource(url)) def get_current_term(): """ Returns a restclients.models.sws.Term object, for the current term. """ url = "%s/current.json" % term_res_url_prefix term = _json_to_term_model(get_resource(url)) # A term doesn't become "current" until 2 days before the start of # classes. That's too late to be useful, so if we're after the last # day of grade submission window, use the next term resource. if datetime.now() > term.grade_submission_deadline: return get_next_term() return term def get_next_term(): """ Returns a restclients.models.sws.Term object, for the next term. """ url = "%s/next.json" % term_res_url_prefix return _json_to_term_model(get_resource(url)) def get_previous_term(): """ Returns a restclients.models.sws.Term object, for the previous term. """ url = "%s/previous.json" % term_res_url_prefix return _json_to_term_model(get_resource(url)) def get_term_before(aterm): """ Returns a restclients.models.sws.Term object, for the term before the term given. """ prev_year = aterm.year prev_quarter = QUARTER_SEQ[QUARTER_SEQ.index(aterm.quarter) - 1] if prev_quarter == "autumn": prev_year -= 1 return get_term_by_year_and_quarter(prev_year, prev_quarter) def get_term_after(aterm): """ Returns a restclients.models.sws.Term object, for the term after the term given. """ next_year = aterm.year if aterm.quarter == "autumn": next_quarter = QUARTER_SEQ[0] else: next_quarter = QUARTER_SEQ[QUARTER_SEQ.index(aterm.quarter) + 1] if next_quarter == "winter": next_year += 1 return get_term_by_year_and_quarter(next_year, next_quarter) def get_term_by_date(date): """ Returns a term for the datetime.date object given. """ year = date.year term = None for quarter in ('autumn', 'summer', 'spring', 'winter'): term = get_term_by_year_and_quarter(year, quarter) if date >= term.first_day_quarter: break # If we're in a year, before the start of winter quarter, we need to go # to the previous year's autumn term: if date < term.first_day_quarter: term = get_term_by_year_and_quarter(year - 1, 'autumn') # Autumn quarter should always last through the end of the year, # with winter of the next year starting in January. But this makes sure # we catch it if not. term_after = get_term_after(term) if term_after.first_day_quarter > date: return term else: return term_after pass def _json_to_term_model(term_data): """ Returns a term model created from the passed json data. param: term_data loaded json data """ strptime = datetime.strptime day_format = "%Y-%m-%d" datetime_format = "%Y-%m-%dT%H:%M:%S" term = TermModel() term.year = term_data["Year"] term.quarter = term_data["Quarter"] term.last_day_add = parse_sws_date(term_data["LastAddDay"]) term.first_day_quarter = parse_sws_date(term_data["FirstDay"]) term.last_day_instruction = parse_sws_date(term_data["LastDayOfClasses"]) term.last_day_drop = parse_sws_date(term_data["LastDropDay"]) term.census_day = parse_sws_date(term_data["CensusDay"]) if term_data["ATermLastDay"] is not None: term.aterm_last_date = parse_sws_date(term_data["ATermLastDay"]) if term_data["BTermFirstDay"] is not None: term.bterm_first_date = parse_sws_date(term_data["BTermFirstDay"]) if term_data["LastAddDayATerm"] is not None: term.aterm_last_day_add = parse_sws_date(term_data["LastAddDayATerm"]) if term_data["LastAddDayBTerm"] is not None: term.bterm_last_day_add = parse_sws_date(term_data["LastAddDayBTerm"]) term.last_final_exam_date = parse_sws_date(term_data["LastFinalExamDay"]) term.grading_period_open = strptime( term_data["GradingPeriodOpen"], datetime_format) if term_data["GradingPeriodOpenATerm"] is not None: term.aterm_grading_period_open = strptime( term_data["GradingPeriodOpenATerm"], datetime_format) term.grading_period_close = strptime( term_data["GradingPeriodClose"], datetime_format) term.grade_submission_deadline = strptime( term_data["GradeSubmissionDeadline"], datetime_format) term.registration_services_start = parse_sws_date(term_data["RegistrationServicesStart"]) term.registration_period1_start = parse_sws_date(term_data["RegistrationPeriods"][0]["StartDate"]) term.registration_period1_end = parse_sws_date(term_data["RegistrationPeriods"][0]["EndDate"]) term.registration_period2_start = parse_sws_date(term_data["RegistrationPeriods"][1]["StartDate"]) term.registration_period2_end = parse_sws_date(term_data["RegistrationPeriods"][1]["EndDate"]) term.registration_period3_start = parse_sws_date(term_data["RegistrationPeriods"][2]["StartDate"]) term.registration_period3_end = parse_sws_date(term_data["RegistrationPeriods"][2]["EndDate"]) term.time_schedule_construction = [] for campus in term_data["TimeScheduleConstruction"]: tsc = TimeScheduleConstruction( campus=campus.lower(), is_on=(term_data["TimeScheduleConstruction"][campus] is True)) term.time_schedule_construction.append(tsc) term.clean_fields() return term
uw-it-cte/uw-restclients
restclients/sws/v5/term.py
Python
apache-2.0
6,171
import numpy as np from numba import cuda, float32 from numba.cuda.testing import CUDATestCase import unittest class TestFastMathOption(CUDATestCase): def test_kernel(self): def foo(arr, val): i = cuda.grid(1) if i < arr.size: arr[i] = float32(i) / val fastver = cuda.jit("void(float32[:], float32)", fastmath=True)(foo) precver = cuda.jit("void(float32[:], float32)")(foo) self.assertIn('div.full.ftz.f32', fastver.ptx) self.assertNotIn('div.full.ftz.f32', precver.ptx) def test_device(self): # fastmath option is ignored for device function @cuda.jit("float32(float32, float32)", device=True) def foo(a, b): return a / b def bar(arr, val): i = cuda.grid(1) if i < arr.size: arr[i] = foo(i, val) fastver = cuda.jit("void(float32[:], float32)", fastmath=True)(bar) precver = cuda.jit("void(float32[:], float32)")(bar) self.assertIn('div.full.ftz.f32', fastver.ptx) self.assertNotIn('div.full.ftz.f32', precver.ptx) if __name__ == '__main__': unittest.main()
sklam/numba
numba/cuda/tests/cudapy/test_fastmath.py
Python
bsd-2-clause
1,178
# -*- coding: utf-8 -*- """ Emotiv acquisition : Reverse engineering and original crack code written by Cody Brocious (http://github.com/daeken) Kyle Machulis (http://github.com/qdot) Many thanks for their contribution. Need python-crypto. """ import multiprocessing as mp import numpy as np import msgpack import time from collections import OrderedDict from .base import DeviceBase import platform WINDOWS = (platform.system() == "Windows") try: import pywinusb.hid as hid except: pass import os from subprocess import check_output from Crypto.Cipher import AES from Crypto import Random import Queue tasks = Queue.Queue() _channel_names = [ 'F3', 'F4', 'P7', 'FC6', 'F7', 'F8','T7','P8','FC5','AF4','T8','O2','O1','AF3'] sensorBits = { 'F3': [10, 11, 12, 13, 14, 15, 0, 1, 2, 3, 4, 5, 6, 7], 'FC5': [28, 29, 30, 31, 16, 17, 18, 19, 20, 21, 22, 23, 8, 9], 'AF3': [46, 47, 32, 33, 34, 35, 36, 37, 38, 39, 24, 25, 26, 27], 'F7': [48, 49, 50, 51, 52, 53, 54, 55, 40, 41, 42, 43, 44, 45], 'T7': [66, 67, 68, 69, 70, 71, 56, 57, 58, 59, 60, 61, 62, 63], 'P7': [84, 85, 86, 87, 72, 73, 74, 75, 76, 77, 78, 79, 64, 65], 'O1': [102, 103, 88, 89, 90, 91, 92, 93, 94, 95, 80, 81, 82, 83], 'O2': [140, 141, 142, 143, 128, 129, 130, 131, 132, 133, 134, 135, 120, 121], 'P8': [158, 159, 144, 145, 146, 147, 148, 149, 150, 151, 136, 137, 138, 139], 'T8': [160, 161, 162, 163, 164, 165, 166, 167, 152, 153, 154, 155, 156, 157], 'F8': [178, 179, 180, 181, 182, 183, 168, 169, 170, 171, 172, 173, 174, 175], 'AF4': [196, 197, 198, 199, 184, 185, 186, 187, 188, 189, 190, 191, 176, 177], 'FC6': [214, 215, 200, 201, 202, 203, 204, 205, 206, 207, 192, 193, 194, 195], 'F4': [216, 217, 218, 219, 220, 221, 222, 223, 208, 209, 210, 211, 212, 213] } quality_bits = [99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112] def create_analog_subdevice_param(channel_names): n = len(channel_names) d = { 'type' : 'AnalogInput', 'nb_channel' : n, 'params' :{ }, 'by_channel_params' : { 'channel_indexes' : range(n), 'channel_names' : channel_names, } } return d def get_info(device): info = { } info['class'] = 'EmotivMultiSignals' if WINDOWS: # EMOTIV info['device_path'] = device.device_path info['board_name'] = '{} #{}'.format(device.vendor_name, device.serial_number).replace('\n', '').replace('\r', '') info['serial'] = device.serial_number info['hid'] = device else: info['device_path'] = device name = device_path.strip('/dev/') realInputPath = os.path.realpath("/sys/class/hidraw/" + name) path = '/'.join(realInputPath.split('/')[:-4]) with open(path + "/manufacturer", 'r') as f: manufacturer = f.readline() with open(path + "/serial", 'r') as f: serial = f.readline().strip() info['board_name'] = '{} #{}'.format(manufacturer, serial).replace('\n', '').replace('\r', '') info['serial'] = serial # PYACQ info['global_params'] = {'buffer_length' : 60.,} info['subdevices'] = [ ] info['subdevices'].append(create_analog_subdevice_param(_channel_names)) quality_name = ['Quality {}'.format(n) for n in _channel_names] info['subdevices'].append(create_analog_subdevice_param(quality_name)) info['subdevices'].append(create_analog_subdevice_param([ 'X','Y'])) return info def dump(obj): for attr in dir(obj): print "obj.%s = %s" % (attr, getattr(obj, attr)) class EmotivMultiSignals(DeviceBase): def __init__(self, **kargs): DeviceBase.__init__(self, **kargs) @classmethod def get_available_devices(cls): devices = OrderedDict() if WINDOWS: try: for device in hid.find_all_hid_devices(): print "device : ", device if (device.product_name == 'Emotiv RAW DATA' or device.product_name == 'EPOC BCI'): devices['Emotiv '+device.serial_number] = get_info(device) finally: pass else: serials = { } for name in os.listdir("/sys/class/hidraw"): realInputPath = os.path.realpath("/sys/class/hidraw/" + name) path = '/'.join(realInputPath.split('/')[:-4]) try: with open(path + "/manufacturer", 'r') as f: manufacturer = f.readline() if "emotiv" in manufacturer.lower(): with open(path + "/serial", 'r') as f: serial = f.readline().strip() if serial not in serials: serials[serial] = [ ] serials[serial].append(name) except IOError as e: print "Couldn't open file: %s" % e for serial, names in serials.items(): device_path = '/dev/'+names[1] info = get_info(device_path) devices['Emotiv '+device_path] = info return devices def configure(self, buffer_length = 60, subdevices = None, ): self.params = {'buffer_length' : buffer_length, 'subdevices' : subdevices, } self.__dict__.update(self.params) self.configured = True def initialize(self): devices = EmotivMultiSignals.get_available_devices() self.device = devices.values()[0] if self.subdevices is None: self.subdevices = self.device['subdevices'] self.sampling_rate = 128. self.packet_size = 1 l = int(self.sampling_rate*self.buffer_length) self.buffer_length = (l - l%self.packet_size)/self.sampling_rate self.name = '{}'.format(self.device['board_name']) self.streams = [ ] for s, sub in enumerate(self.subdevices): stream = self.streamhandler.new_AnalogSignalSharedMemStream(name = self.name+str(s) , sampling_rate = self.sampling_rate, nb_channel = sub['nb_channel'], buffer_length = self.buffer_length, packet_size = self.packet_size, dtype = np.float64, channel_names = sub['by_channel_params']['channel_names'], channel_indexes = sub['by_channel_params']['channel_indexes'], ) self.streams.append(stream) def start(self): self.stop_flag = mp.Value('i', 0) #flag pultiproc = global self.process = mp.Process(target = emotiv_mainLoop, args=(self.stop_flag, self.streams, self.device) ) self.process.start() print 'FakeMultiAnalogChannel started:', self.name self.running = True def stop(self): self.stop_flag.value = 1 self.process.join() print 'FakeMultiAnalogChannel stopped:', self.name self.running = False def close(self): if WINDOWS: self.device['hid'].close() else: pass # for ii in self.streams: # self.streams[ii].stop() def setupCrypto(serial): type = 0 #feature[5] type &= 0xF type = 0 #I believe type == True is for the Dev headset, I'm not using that. That's the point of this library in the first place I thought. k = ['\0'] * 16 k[0] = serial[-1] k[1] = '\0' k[2] = serial[-2] if type: k[3] = 'H' k[4] = serial[-1] k[5] = '\0' k[6] = serial[-2] k[7] = 'T' k[8] = serial[-3] k[9] = '\x10' k[10] = serial[-4] k[11] = 'B' else: k[3] = 'T' k[4] = serial[-3] k[5] = '\x10' k[6] = serial[-4] k[7] = 'B' k[8] = serial[-1] k[9] = '\0' k[10] = serial[-2] k[11] = 'H' k[12] = serial[-3] k[13] = '\0' k[14] = serial[-4] k[15] = 'P' #It doesn't make sense to have more than one greenlet handling this as data needs to be in order anyhow. I guess you could assign an ID or something #to each packet but that seems like a waste also or is it? The ID might be useful if your using multiple headsets or usb sticks. key = ''.join(k) iv = Random.new().read(AES.block_size) cipher = AES.new(key, AES.MODE_ECB, iv) return cipher def get_level(data, bits): level = 0 for i in range(13, -1, -1): level <<= 1 b, o = (bits[i] / 8) + 1, bits[i] % 8 level |= (ord(data[b]) >> o) & 1 return level def emotiv_mainLoop(stop_flag, streams, device): import zmq abs_pos = pos = 0 #setup cryto cipher = setupCrypto(device['serial']) streamChan, streamImp, streamGyro = streams #Data channels socket context = zmq.Context() socket_chan = context.socket(zmq.PUB) socket_chan.bind("tcp://*:{}".format(streamChan['port'])) #Impedance channels socket socket_imp = context.socket(zmq.PUB) socket_imp.bind("tcp://*:{}".format(streamImp['port'])) #Gyro channels socket socket_gyro = context.socket(zmq.PUB) socket_gyro.bind("tcp://*:{}".format(streamGyro['port'])) packet_size = streamChan['packet_size'] sampling_rate = streamChan['sampling_rate'] np_arr_chan = streamChan['shared_array'].to_numpy_array() np_arr_imp = streamImp['shared_array'].to_numpy_array() np_arr_gyro = streamGyro['shared_array'].to_numpy_array() half_size = np_arr_chan.shape[1]/2 # same for the others impedance_qualities = { } for name in _channel_names + ['X', 'Y', 'Unknown']: impedance_qualities[name] = 0. if WINDOWS: device['hid'].open() device['hid'].set_raw_data_handler(emotiv_handler) else: hidraw = open(device['device_path']) while True: # READ DATA if WINDOWS: crypted_data = tasks.get(True) else: crypted_data = hidraw.read(32) # PROCESS data = cipher.decrypt(crypted_data[:16]) + cipher.decrypt(crypted_data[16:]) # current impedance quality sensor_num = ord(data[0]) num_to_name = { 0 : 'F3', 1:'FC5', 2 : 'AF3', 3 : 'F7', 4:'T7', 5 : 'P7', 6 : 'O1', 7 : 'O2', 8: 'P8', 9 : 'T8', 10: 'F8', 11 : 'AF4', 12 : 'FC6', 13: 'F4', 14 : 'F8', 15:'AF4', 64 : 'F3', 65 : 'FC5', 66 : 'AF3', 67 : 'F7', 68 : 'T7', 69 : 'P7', 70 : 'O1', 71 : 'O2', 72: 'P8', 73 : 'T8', 74: 'F8', 75 : 'AF4', 76 : 'FC6', 77: 'F4', 78 : 'F8', 79:'AF4', 80 : 'FC6', } if sensor_num in num_to_name: sensor_name = num_to_name[sensor_num] impedance_qualities[sensor_name] = get_level(data, quality_bits) / 540 for c, channel_name in enumerate(_channel_names): bits = sensorBits[channel_name] # channel value value = get_level(data, bits) np_arr_chan[c,pos] = value np_arr_chan[c,pos+half_size] = value #channel qualities np_arr_imp[c,pos] = impedance_qualities[channel_name] np_arr_imp[c,pos+half_size] = impedance_qualities[channel_name] gyroX = ord(data[29]) - 106 gyroY = ord(data[30]) - 105 np_arr_gyro[:,pos] = [gyroX, gyroY] np_arr_gyro[:,pos+half_size] = [gyroX, gyroY] abs_pos += packet_size pos = abs_pos%half_size socket_chan.send(msgpack.dumps(abs_pos)) socket_imp.send(msgpack.dumps(abs_pos)) socket_gyro.send(msgpack.dumps(abs_pos)) if stop_flag.value: print 'will stop' break # Windows handler def emotiv_handler(data): """ Receives packets from headset for Windows. Sends them to the crypto process """ assert data[0] == 0 tasks.put_nowait(''.join(map(chr, data[1:]))) return True Emotiv = EmotivMultiSignals
Hemisphere-Project/Telemir-DatabitMe
Telemir-EEG/pyacq/pyacq/core/devices/emotiv.py
Python
gpl-2.0
12,623
#!/usr/bin/env python # coding=utf-8 import tornado.web class BaseHandler(tornado.web.RequestHandler): def __init__(self, *argc, **argkw): super(BaseHandler, self).__init__(*argc, **argkw) self.jinja2 = self.setting.get("jinja2") @property def db(self): return self.application.db @property def user_model(self): return self.application.user_model @property def topic_model(self): return self.application.topic_model @property def reply_model(self): return self.application.reply_model @property def node_model(self): return self.application.node_model @property def notification_model(self): return self.application.notification_model @property def like_model return self.application.like_model @property def loader return self.application.loader @property def mc return self.application.mc def get_current_user(self): user_id = self.get_secure_cookie("user") if not user_id: return None return self.user_model.get_user_by_uid(int(user_id)) def render(self, template_name, **template_vars): html = self.render_string(template_name, **template_vars) self.write(html) def render_string(self, template_name, **template_vars): template_vars["xsrf_form_html"] = self.xsrf_form_html template_vars["current_user"] = self.current_user template_vars["request"] = self.request template_vars["request_handler"] = self template = self.jinja2.get_template(template_name) return template.render(**template_vars) def render_from_string(self, template_string, **template_vars): template = self.jinja2.from_string(template_string) return template.render(**template_vars)
yiyangyi/cc98-tornado
handler/base.py
Python
mit
1,656
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import datetime from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('app', '0025_auto_20150923_0843'), ] operations = [ migrations.CreateModel( name='BlogEntry', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=100)), ('text', models.CharField(max_length=10000)), ('pub_date', models.DateField()), ('author', models.ForeignKey(to='app.Account')), ], options={ 'abstract': False, }, ), migrations.CreateModel( name='BlogEntryTag', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=100)), ('desc', models.CharField(max_length=500)), ], options={ 'abstract': False, }, ), migrations.AddField( model_name='mission', name='finalize_date', field=models.DateField(default=datetime.datetime(2012, 1, 6, 22, 12, 50, 101184, tzinfo=utc)), preserve_default=False, ), migrations.AlterField( model_name='neurorequest', name='closed_date', field=models.DateField(), ), migrations.AddField( model_name='blogentry', name='tags', field=models.ManyToManyField(to='app.BlogEntryTag'), ), ]
XcomConvent/xcom40k-shades
xcom40k/app/migrations/0026_auto_20120106_2212.py
Python
apache-2.0
1,819
#*************************************************************************** #* * #* Copyright (c) 2011, 2012 * #* Jose Luis Cercos Pita <[email protected]> * #* * #* This program is free software; you can redistribute it and/or modify * #* it under the terms of the GNU Lesser General Public License (LGPL) * #* as published by the Free Software Foundation; either version 2 of * #* the License, or (at your option) any later version. * #* for detail see the LICENCE text file. * #* * #* This program is distributed in the hope that it will be useful, * #* but WITHOUT ANY WARRANTY; without even the implied warranty of * #* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * #* GNU Library General Public License for more details. * #* * #* You should have received a copy of the GNU Library 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 * #* * #*************************************************************************** class PlotWorkbench(Workbench): """Workbench of Plot module.""" from plotUtils import Paths import PlotGui Icon = 'Icon.svg' MenuText = "Plot" ToolTip = ("The Plot module is used to edit/save output plots performed " "by other tools") def Initialize(self): from PySide import QtCore, QtGui cmdlst = ["Plot_SaveFig", "Plot_Axes", "Plot_Series", "Plot_Grid", "Plot_Legend", "Plot_Labels", "Plot_Positions"] self.appendToolbar(str(QtCore.QT_TRANSLATE_NOOP( "Plot", "Plot edition tools")), cmdlst) self.appendMenu(str(QtCore.QT_TRANSLATE_NOOP( "Plot", "Plot")), cmdlst) try: import matplotlib except ImportError: from PySide import QtCore, QtGui msg = QtGui.QApplication.translate( "plot_console", "matplotlib not found, Plot module will be disabled", None, QtGui.QApplication.UnicodeUTF8) FreeCAD.Console.PrintMessage(msg + '\n') Gui.addWorkbench(PlotWorkbench())
yantrabuddhi/FreeCAD
src/Mod/Plot/InitGui.py
Python
lgpl-2.1
2,920
# coding=utf-8 # pylint: disable-msg=E1101,W0612 from collections import OrderedDict from datetime import datetime, timedelta import numpy as np from numpy import nan import numpy.ma as ma import pytest from pandas._libs import lib from pandas._libs.tslib import iNaT from pandas.compat import PY36, long, lrange, range, zip from pandas.core.dtypes.common import ( is_categorical_dtype, is_datetime64tz_dtype) import pandas as pd from pandas import ( Categorical, DataFrame, Index, IntervalIndex, MultiIndex, NaT, Series, Timestamp, date_range, isna, period_range, timedelta_range) from pandas.api.types import CategoricalDtype from pandas.core.arrays import period_array import pandas.util.testing as tm from pandas.util.testing import assert_series_equal class TestSeriesConstructors(): def test_invalid_dtype(self): # GH15520 msg = 'not understood' invalid_list = [pd.Timestamp, 'pd.Timestamp', list] for dtype in invalid_list: with tm.assert_raises_regex(TypeError, msg): Series([], name='time', dtype=dtype) def test_scalar_conversion(self): # Pass in scalar is disabled scalar = Series(0.5) assert not isinstance(scalar, float) # Coercion assert float(Series([1.])) == 1.0 assert int(Series([1.])) == 1 assert long(Series([1.])) == 1 def test_constructor(self, datetime_series, empty_series): assert datetime_series.index.is_all_dates # Pass in Series derived = Series(datetime_series) assert derived.index.is_all_dates assert tm.equalContents(derived.index, datetime_series.index) # Ensure new index is not created assert id(datetime_series.index) == id(derived.index) # Mixed type Series mixed = Series(['hello', np.NaN], index=[0, 1]) assert mixed.dtype == np.object_ assert mixed[1] is np.NaN assert not empty_series.index.is_all_dates assert not Series({}).index.is_all_dates pytest.raises(Exception, Series, np.random.randn(3, 3), index=np.arange(3)) mixed.name = 'Series' rs = Series(mixed).name xp = 'Series' assert rs == xp # raise on MultiIndex GH4187 m = MultiIndex.from_arrays([[1, 2], [3, 4]]) pytest.raises(NotImplementedError, Series, m) @pytest.mark.parametrize('input_class', [list, dict, OrderedDict]) def test_constructor_empty(self, input_class): empty = Series() empty2 = Series(input_class()) # these are Index() and RangeIndex() which don't compare type equal # but are just .equals assert_series_equal(empty, empty2, check_index_type=False) # With explicit dtype: empty = Series(dtype='float64') empty2 = Series(input_class(), dtype='float64') assert_series_equal(empty, empty2, check_index_type=False) # GH 18515 : with dtype=category: empty = Series(dtype='category') empty2 = Series(input_class(), dtype='category') assert_series_equal(empty, empty2, check_index_type=False) if input_class is not list: # With index: empty = Series(index=lrange(10)) empty2 = Series(input_class(), index=lrange(10)) assert_series_equal(empty, empty2) # With index and dtype float64: empty = Series(np.nan, index=lrange(10)) empty2 = Series(input_class(), index=lrange(10), dtype='float64') assert_series_equal(empty, empty2) # GH 19853 : with empty string, index and dtype str empty = Series('', dtype=str, index=range(3)) empty2 = Series('', index=range(3)) assert_series_equal(empty, empty2) @pytest.mark.parametrize('input_arg', [np.nan, float('nan')]) def test_constructor_nan(self, input_arg): empty = Series(dtype='float64', index=lrange(10)) empty2 = Series(input_arg, index=lrange(10)) assert_series_equal(empty, empty2, check_index_type=False) @pytest.mark.parametrize('dtype', [ 'f8', 'i8', 'M8[ns]', 'm8[ns]', 'category', 'object', 'datetime64[ns, UTC]', ]) @pytest.mark.parametrize('index', [None, pd.Index([])]) def test_constructor_dtype_only(self, dtype, index): # GH-20865 result = pd.Series(dtype=dtype, index=index) assert result.dtype == dtype assert len(result) == 0 def test_constructor_no_data_index_order(self): result = pd.Series(index=['b', 'a', 'c']) assert result.index.tolist() == ['b', 'a', 'c'] def test_constructor_dtype_str_na_values(self, string_dtype): # https://github.com/pandas-dev/pandas/issues/21083 ser = Series(['x', None], dtype=string_dtype) result = ser.isna() expected = Series([False, True]) tm.assert_series_equal(result, expected) assert ser.iloc[1] is None ser = Series(['x', np.nan], dtype=string_dtype) assert np.isnan(ser.iloc[1]) def test_constructor_series(self): index1 = ['d', 'b', 'a', 'c'] index2 = sorted(index1) s1 = Series([4, 7, -5, 3], index=index1) s2 = Series(s1, index=index2) assert_series_equal(s2, s1.sort_index()) def test_constructor_iterable(self): # GH 21987 class Iter(): def __iter__(self): for i in range(10): yield i expected = Series(list(range(10)), dtype='int64') result = Series(Iter(), dtype='int64') assert_series_equal(result, expected) def test_constructor_sequence(self): # GH 21987 expected = Series(list(range(10)), dtype='int64') result = Series(range(10), dtype='int64') assert_series_equal(result, expected) def test_constructor_single_str(self): # GH 21987 expected = Series(['abc']) result = Series('abc') assert_series_equal(result, expected) def test_constructor_list_like(self): # make sure that we are coercing different # list-likes to standard dtypes and not # platform specific expected = Series([1, 2, 3], dtype='int64') for obj in [[1, 2, 3], (1, 2, 3), np.array([1, 2, 3], dtype='int64')]: result = Series(obj, index=[0, 1, 2]) assert_series_equal(result, expected) @pytest.mark.parametrize('input_vals', [ ([1, 2]), (['1', '2']), (list(pd.date_range('1/1/2011', periods=2, freq='H'))), (list(pd.date_range('1/1/2011', periods=2, freq='H', tz='US/Eastern'))), ([pd.Interval(left=0, right=5)]), ]) def test_constructor_list_str(self, input_vals, string_dtype): # GH 16605 # Ensure that data elements from a list are converted to strings # when dtype is str, 'str', or 'U' result = Series(input_vals, dtype=string_dtype) expected = Series(input_vals).astype(string_dtype) assert_series_equal(result, expected) def test_constructor_list_str_na(self, string_dtype): result = Series([1.0, 2.0, np.nan], dtype=string_dtype) expected = Series(['1.0', '2.0', np.nan], dtype=object) assert_series_equal(result, expected) assert np.isnan(result[2]) def test_constructor_generator(self): gen = (i for i in range(10)) result = Series(gen) exp = Series(lrange(10)) assert_series_equal(result, exp) gen = (i for i in range(10)) result = Series(gen, index=lrange(10, 20)) exp.index = lrange(10, 20) assert_series_equal(result, exp) def test_constructor_map(self): # GH8909 m = map(lambda x: x, range(10)) result = Series(m) exp = Series(lrange(10)) assert_series_equal(result, exp) m = map(lambda x: x, range(10)) result = Series(m, index=lrange(10, 20)) exp.index = lrange(10, 20) assert_series_equal(result, exp) def test_constructor_categorical(self): cat = pd.Categorical([0, 1, 2, 0, 1, 2], ['a', 'b', 'c'], fastpath=True) res = Series(cat) tm.assert_categorical_equal(res.values, cat) # can cast to a new dtype result = Series(pd.Categorical([1, 2, 3]), dtype='int64') expected = pd.Series([1, 2, 3], dtype='int64') tm.assert_series_equal(result, expected) # GH12574 cat = Series(pd.Categorical([1, 2, 3]), dtype='category') assert is_categorical_dtype(cat) assert is_categorical_dtype(cat.dtype) s = Series([1, 2, 3], dtype='category') assert is_categorical_dtype(s) assert is_categorical_dtype(s.dtype) def test_constructor_categorical_with_coercion(self): factor = Categorical(['a', 'b', 'b', 'a', 'a', 'c', 'c', 'c']) # test basic creation / coercion of categoricals s = Series(factor, name='A') assert s.dtype == 'category' assert len(s) == len(factor) str(s.values) str(s) # in a frame df = DataFrame({'A': factor}) result = df['A'] tm.assert_series_equal(result, s) result = df.iloc[:, 0] tm.assert_series_equal(result, s) assert len(df) == len(factor) str(df.values) str(df) df = DataFrame({'A': s}) result = df['A'] tm.assert_series_equal(result, s) assert len(df) == len(factor) str(df.values) str(df) # multiples df = DataFrame({'A': s, 'B': s, 'C': 1}) result1 = df['A'] result2 = df['B'] tm.assert_series_equal(result1, s) tm.assert_series_equal(result2, s, check_names=False) assert result2.name == 'B' assert len(df) == len(factor) str(df.values) str(df) # GH8623 x = DataFrame([[1, 'John P. Doe'], [2, 'Jane Dove'], [1, 'John P. Doe']], columns=['person_id', 'person_name']) x['person_name'] = Categorical(x.person_name ) # doing this breaks transform expected = x.iloc[0].person_name result = x.person_name.iloc[0] assert result == expected result = x.person_name[0] assert result == expected result = x.person_name.loc[0] assert result == expected def test_constructor_categorical_dtype(self): result = pd.Series(['a', 'b'], dtype=CategoricalDtype(['a', 'b', 'c'], ordered=True)) assert is_categorical_dtype(result) is True tm.assert_index_equal(result.cat.categories, pd.Index(['a', 'b', 'c'])) assert result.cat.ordered result = pd.Series(['a', 'b'], dtype=CategoricalDtype(['b', 'a'])) assert is_categorical_dtype(result) tm.assert_index_equal(result.cat.categories, pd.Index(['b', 'a'])) assert result.cat.ordered is False # GH 19565 - Check broadcasting of scalar with Categorical dtype result = Series('a', index=[0, 1], dtype=CategoricalDtype(['a', 'b'], ordered=True)) expected = Series(['a', 'a'], index=[0, 1], dtype=CategoricalDtype(['a', 'b'], ordered=True)) tm.assert_series_equal(result, expected, check_categorical=True) def test_categorical_sideeffects_free(self): # Passing a categorical to a Series and then changing values in either # the series or the categorical should not change the values in the # other one, IF you specify copy! cat = Categorical(["a", "b", "c", "a"]) s = Series(cat, copy=True) assert s.cat is not cat s.cat.categories = [1, 2, 3] exp_s = np.array([1, 2, 3, 1], dtype=np.int64) exp_cat = np.array(["a", "b", "c", "a"], dtype=np.object_) tm.assert_numpy_array_equal(s.__array__(), exp_s) tm.assert_numpy_array_equal(cat.__array__(), exp_cat) # setting s[0] = 2 exp_s2 = np.array([2, 2, 3, 1], dtype=np.int64) tm.assert_numpy_array_equal(s.__array__(), exp_s2) tm.assert_numpy_array_equal(cat.__array__(), exp_cat) # however, copy is False by default # so this WILL change values cat = Categorical(["a", "b", "c", "a"]) s = Series(cat) assert s.values is cat s.cat.categories = [1, 2, 3] exp_s = np.array([1, 2, 3, 1], dtype=np.int64) tm.assert_numpy_array_equal(s.__array__(), exp_s) tm.assert_numpy_array_equal(cat.__array__(), exp_s) s[0] = 2 exp_s2 = np.array([2, 2, 3, 1], dtype=np.int64) tm.assert_numpy_array_equal(s.__array__(), exp_s2) tm.assert_numpy_array_equal(cat.__array__(), exp_s2) def test_unordered_compare_equal(self): left = pd.Series(['a', 'b', 'c'], dtype=CategoricalDtype(['a', 'b'])) right = pd.Series(pd.Categorical(['a', 'b', np.nan], categories=['a', 'b'])) tm.assert_series_equal(left, right) def test_constructor_maskedarray(self): data = ma.masked_all((3, ), dtype=float) result = Series(data) expected = Series([nan, nan, nan]) assert_series_equal(result, expected) data[0] = 0.0 data[2] = 2.0 index = ['a', 'b', 'c'] result = Series(data, index=index) expected = Series([0.0, nan, 2.0], index=index) assert_series_equal(result, expected) data[1] = 1.0 result = Series(data, index=index) expected = Series([0.0, 1.0, 2.0], index=index) assert_series_equal(result, expected) data = ma.masked_all((3, ), dtype=int) result = Series(data) expected = Series([nan, nan, nan], dtype=float) assert_series_equal(result, expected) data[0] = 0 data[2] = 2 index = ['a', 'b', 'c'] result = Series(data, index=index) expected = Series([0, nan, 2], index=index, dtype=float) assert_series_equal(result, expected) data[1] = 1 result = Series(data, index=index) expected = Series([0, 1, 2], index=index, dtype=int) assert_series_equal(result, expected) data = ma.masked_all((3, ), dtype=bool) result = Series(data) expected = Series([nan, nan, nan], dtype=object) assert_series_equal(result, expected) data[0] = True data[2] = False index = ['a', 'b', 'c'] result = Series(data, index=index) expected = Series([True, nan, False], index=index, dtype=object) assert_series_equal(result, expected) data[1] = True result = Series(data, index=index) expected = Series([True, True, False], index=index, dtype=bool) assert_series_equal(result, expected) data = ma.masked_all((3, ), dtype='M8[ns]') result = Series(data) expected = Series([iNaT, iNaT, iNaT], dtype='M8[ns]') assert_series_equal(result, expected) data[0] = datetime(2001, 1, 1) data[2] = datetime(2001, 1, 3) index = ['a', 'b', 'c'] result = Series(data, index=index) expected = Series([datetime(2001, 1, 1), iNaT, datetime(2001, 1, 3)], index=index, dtype='M8[ns]') assert_series_equal(result, expected) data[1] = datetime(2001, 1, 2) result = Series(data, index=index) expected = Series([datetime(2001, 1, 1), datetime(2001, 1, 2), datetime(2001, 1, 3)], index=index, dtype='M8[ns]') assert_series_equal(result, expected) def test_series_ctor_plus_datetimeindex(self): rng = date_range('20090415', '20090519', freq='B') data = {k: 1 for k in rng} result = Series(data, index=rng) assert result.index is rng def test_constructor_default_index(self): s = Series([0, 1, 2]) tm.assert_index_equal(s.index, pd.Index(np.arange(3))) @pytest.mark.parametrize('input', [[1, 2, 3], (1, 2, 3), list(range(3)), pd.Categorical(['a', 'b', 'a']), (i for i in range(3)), map(lambda x: x, range(3))]) def test_constructor_index_mismatch(self, input): # GH 19342 # test that construction of a Series with an index of different length # raises an error msg = 'Length of passed values is 3, index implies 4' with pytest.raises(ValueError, match=msg): Series(input, index=np.arange(4)) def test_constructor_numpy_scalar(self): # GH 19342 # construction with a numpy scalar # should not raise result = Series(np.array(100), index=np.arange(4), dtype='int64') expected = Series(100, index=np.arange(4), dtype='int64') tm.assert_series_equal(result, expected) def test_constructor_broadcast_list(self): # GH 19342 # construction with single-element container and index # should raise pytest.raises(ValueError, Series, ['foo'], index=['a', 'b', 'c']) def test_constructor_corner(self): df = tm.makeTimeDataFrame() objs = [df, df] s = Series(objs, index=[0, 1]) assert isinstance(s, Series) def test_constructor_sanitize(self): s = Series(np.array([1., 1., 8.]), dtype='i8') assert s.dtype == np.dtype('i8') s = Series(np.array([1., 1., np.nan]), copy=True, dtype='i8') assert s.dtype == np.dtype('f8') def test_constructor_copy(self): # GH15125 # test dtype parameter has no side effects on copy=True for data in [[1.], np.array([1.])]: x = Series(data) y = pd.Series(x, copy=True, dtype=float) # copy=True maintains original data in Series tm.assert_series_equal(x, y) # changes to origin of copy does not affect the copy x[0] = 2. assert not x.equals(y) assert x[0] == 2. assert y[0] == 1. @pytest.mark.parametrize( "index", [ pd.date_range('20170101', periods=3, tz='US/Eastern'), pd.date_range('20170101', periods=3), pd.timedelta_range('1 day', periods=3), pd.period_range('2012Q1', periods=3, freq='Q'), pd.Index(list('abc')), pd.Int64Index([1, 2, 3]), pd.RangeIndex(0, 3)], ids=lambda x: type(x).__name__) def test_constructor_limit_copies(self, index): # GH 17449 # limit copies of input s = pd.Series(index) # we make 1 copy; this is just a smoke test here assert s._data.blocks[0].values is not index def test_constructor_pass_none(self): s = Series(None, index=lrange(5)) assert s.dtype == np.float64 s = Series(None, index=lrange(5), dtype=object) assert s.dtype == np.object_ # GH 7431 # inference on the index s = Series(index=np.array([None])) expected = Series(index=Index([None])) assert_series_equal(s, expected) def test_constructor_pass_nan_nat(self): # GH 13467 exp = Series([np.nan, np.nan], dtype=np.float64) assert exp.dtype == np.float64 tm.assert_series_equal(Series([np.nan, np.nan]), exp) tm.assert_series_equal(Series(np.array([np.nan, np.nan])), exp) exp = Series([pd.NaT, pd.NaT]) assert exp.dtype == 'datetime64[ns]' tm.assert_series_equal(Series([pd.NaT, pd.NaT]), exp) tm.assert_series_equal(Series(np.array([pd.NaT, pd.NaT])), exp) tm.assert_series_equal(Series([pd.NaT, np.nan]), exp) tm.assert_series_equal(Series(np.array([pd.NaT, np.nan])), exp) tm.assert_series_equal(Series([np.nan, pd.NaT]), exp) tm.assert_series_equal(Series(np.array([np.nan, pd.NaT])), exp) def test_constructor_cast(self): msg = "could not convert string to float" with tm.assert_raises_regex(ValueError, msg): Series(["a", "b", "c"], dtype=float) def test_constructor_unsigned_dtype_overflow(self, uint_dtype): # see gh-15832 msg = 'Trying to coerce negative values to unsigned integers' with tm.assert_raises_regex(OverflowError, msg): Series([-1], dtype=uint_dtype) def test_constructor_coerce_float_fail(self, any_int_dtype): # see gh-15832 msg = "Trying to coerce float values to integers" with tm.assert_raises_regex(ValueError, msg): Series([1, 2, 3.5], dtype=any_int_dtype) def test_constructor_coerce_float_valid(self, float_dtype): s = Series([1, 2, 3.5], dtype=float_dtype) expected = Series([1, 2, 3.5]).astype(float_dtype) assert_series_equal(s, expected) def test_constructor_dtype_no_cast(self): # see gh-1572 s = Series([1, 2, 3]) s2 = Series(s, dtype=np.int64) s2[1] = 5 assert s[1] == 5 def test_constructor_datelike_coercion(self): # GH 9477 # incorrectly inferring on dateimelike looking when object dtype is # specified s = Series([Timestamp('20130101'), 'NOV'], dtype=object) assert s.iloc[0] == Timestamp('20130101') assert s.iloc[1] == 'NOV' assert s.dtype == object # the dtype was being reset on the slicing and re-inferred to datetime # even thought the blocks are mixed belly = '216 3T19'.split() wing1 = '2T15 4H19'.split() wing2 = '416 4T20'.split() mat = pd.to_datetime('2016-01-22 2019-09-07'.split()) df = pd.DataFrame( {'wing1': wing1, 'wing2': wing2, 'mat': mat}, index=belly) result = df.loc['3T19'] assert result.dtype == object result = df.loc['216'] assert result.dtype == object def test_constructor_datetimes_with_nulls(self): # gh-15869 for arr in [np.array([None, None, None, None, datetime.now(), None]), np.array([None, None, datetime.now(), None])]: result = Series(arr) assert result.dtype == 'M8[ns]' def test_constructor_dtype_datetime64(self): s = Series(iNaT, dtype='M8[ns]', index=lrange(5)) assert isna(s).all() # in theory this should be all nulls, but since # we are not specifying a dtype is ambiguous s = Series(iNaT, index=lrange(5)) assert not isna(s).all() s = Series(nan, dtype='M8[ns]', index=lrange(5)) assert isna(s).all() s = Series([datetime(2001, 1, 2, 0, 0), iNaT], dtype='M8[ns]') assert isna(s[1]) assert s.dtype == 'M8[ns]' s = Series([datetime(2001, 1, 2, 0, 0), nan], dtype='M8[ns]') assert isna(s[1]) assert s.dtype == 'M8[ns]' # GH3416 dates = [ np.datetime64(datetime(2013, 1, 1)), np.datetime64(datetime(2013, 1, 2)), np.datetime64(datetime(2013, 1, 3)), ] s = Series(dates) assert s.dtype == 'M8[ns]' s.iloc[0] = np.nan assert s.dtype == 'M8[ns]' # GH3414 related pytest.raises(TypeError, lambda x: Series( Series(dates).astype('int') / 1000000, dtype='M8[ms]')) pytest.raises(TypeError, lambda x: Series(dates, dtype='datetime64')) # invalid dates can be help as object result = Series([datetime(2, 1, 1)]) assert result[0] == datetime(2, 1, 1, 0, 0) result = Series([datetime(3000, 1, 1)]) assert result[0] == datetime(3000, 1, 1, 0, 0) # don't mix types result = Series([Timestamp('20130101'), 1], index=['a', 'b']) assert result['a'] == Timestamp('20130101') assert result['b'] == 1 # GH6529 # coerce datetime64 non-ns properly dates = date_range('01-Jan-2015', '01-Dec-2015', freq='M') values2 = dates.view(np.ndarray).astype('datetime64[ns]') expected = Series(values2, index=dates) for dtype in ['s', 'D', 'ms', 'us', 'ns']: values1 = dates.view(np.ndarray).astype('M8[{0}]'.format(dtype)) result = Series(values1, dates) assert_series_equal(result, expected) # GH 13876 # coerce to non-ns to object properly expected = Series(values2, index=dates, dtype=object) for dtype in ['s', 'D', 'ms', 'us', 'ns']: values1 = dates.view(np.ndarray).astype('M8[{0}]'.format(dtype)) result = Series(values1, index=dates, dtype=object) assert_series_equal(result, expected) # leave datetime.date alone dates2 = np.array([d.date() for d in dates.to_pydatetime()], dtype=object) series1 = Series(dates2, dates) tm.assert_numpy_array_equal(series1.values, dates2) assert series1.dtype == object # these will correctly infer a datetime s = Series([None, pd.NaT, '2013-08-05 15:30:00.000001']) assert s.dtype == 'datetime64[ns]' s = Series([np.nan, pd.NaT, '2013-08-05 15:30:00.000001']) assert s.dtype == 'datetime64[ns]' s = Series([pd.NaT, None, '2013-08-05 15:30:00.000001']) assert s.dtype == 'datetime64[ns]' s = Series([pd.NaT, np.nan, '2013-08-05 15:30:00.000001']) assert s.dtype == 'datetime64[ns]' # tz-aware (UTC and other tz's) # GH 8411 dr = date_range('20130101', periods=3) assert Series(dr).iloc[0].tz is None dr = date_range('20130101', periods=3, tz='UTC') assert str(Series(dr).iloc[0].tz) == 'UTC' dr = date_range('20130101', periods=3, tz='US/Eastern') assert str(Series(dr).iloc[0].tz) == 'US/Eastern' # non-convertible s = Series([1479596223000, -1479590, pd.NaT]) assert s.dtype == 'object' assert s[2] is pd.NaT assert 'NaT' in str(s) # if we passed a NaT it remains s = Series([datetime(2010, 1, 1), datetime(2, 1, 1), pd.NaT]) assert s.dtype == 'object' assert s[2] is pd.NaT assert 'NaT' in str(s) # if we passed a nan it remains s = Series([datetime(2010, 1, 1), datetime(2, 1, 1), np.nan]) assert s.dtype == 'object' assert s[2] is np.nan assert 'NaN' in str(s) def test_constructor_with_datetime_tz(self): # 8260 # support datetime64 with tz dr = date_range('20130101', periods=3, tz='US/Eastern') s = Series(dr) assert s.dtype.name == 'datetime64[ns, US/Eastern]' assert s.dtype == 'datetime64[ns, US/Eastern]' assert is_datetime64tz_dtype(s.dtype) assert 'datetime64[ns, US/Eastern]' in str(s) # export result = s.values assert isinstance(result, np.ndarray) assert result.dtype == 'datetime64[ns]' exp = pd.DatetimeIndex(result) exp = exp.tz_localize('UTC').tz_convert(tz=s.dt.tz) tm.assert_index_equal(dr, exp) # indexing result = s.iloc[0] assert result == Timestamp('2013-01-01 00:00:00-0500', tz='US/Eastern', freq='D') result = s[0] assert result == Timestamp('2013-01-01 00:00:00-0500', tz='US/Eastern', freq='D') result = s[Series([True, True, False], index=s.index)] assert_series_equal(result, s[0:2]) result = s.iloc[0:1] assert_series_equal(result, Series(dr[0:1])) # concat result = pd.concat([s.iloc[0:1], s.iloc[1:]]) assert_series_equal(result, s) # short str assert 'datetime64[ns, US/Eastern]' in str(s) # formatting with NaT result = s.shift() assert 'datetime64[ns, US/Eastern]' in str(result) assert 'NaT' in str(result) # long str t = Series(date_range('20130101', periods=1000, tz='US/Eastern')) assert 'datetime64[ns, US/Eastern]' in str(t) result = pd.DatetimeIndex(s, freq='infer') tm.assert_index_equal(result, dr) # inference s = Series([pd.Timestamp('2013-01-01 13:00:00-0800', tz='US/Pacific'), pd.Timestamp('2013-01-02 14:00:00-0800', tz='US/Pacific')]) assert s.dtype == 'datetime64[ns, US/Pacific]' assert lib.infer_dtype(s) == 'datetime64' s = Series([pd.Timestamp('2013-01-01 13:00:00-0800', tz='US/Pacific'), pd.Timestamp('2013-01-02 14:00:00-0800', tz='US/Eastern')]) assert s.dtype == 'object' assert lib.infer_dtype(s) == 'datetime' # with all NaT s = Series(pd.NaT, index=[0, 1], dtype='datetime64[ns, US/Eastern]') expected = Series(pd.DatetimeIndex(['NaT', 'NaT'], tz='US/Eastern')) assert_series_equal(s, expected) @pytest.mark.parametrize("arr_dtype", [np.int64, np.float64]) @pytest.mark.parametrize("dtype", ["M8", "m8"]) @pytest.mark.parametrize("unit", ['ns', 'us', 'ms', 's', 'h', 'm', 'D']) def test_construction_to_datetimelike_unit(self, arr_dtype, dtype, unit): # tests all units # gh-19223 dtype = "{}[{}]".format(dtype, unit) arr = np.array([1, 2, 3], dtype=arr_dtype) s = Series(arr) result = s.astype(dtype) expected = Series(arr.astype(dtype)) tm.assert_series_equal(result, expected) @pytest.mark.parametrize('arg', ['2013-01-01 00:00:00', pd.NaT, np.nan, None]) def test_constructor_with_naive_string_and_datetimetz_dtype(self, arg): # GH 17415: With naive string result = Series([arg], dtype='datetime64[ns, CET]') expected = Series(pd.Timestamp(arg)).dt.tz_localize('CET') assert_series_equal(result, expected) def test_construction_interval(self): # construction from interval & array of intervals index = IntervalIndex.from_breaks(np.arange(3), closed='right') result = Series(index) repr(result) str(result) tm.assert_index_equal(Index(result.values), index) result = Series(index.values) tm.assert_index_equal(Index(result.values), index) def test_construction_consistency(self): # make sure that we are not re-localizing upon construction # GH 14928 s = Series(pd.date_range('20130101', periods=3, tz='US/Eastern')) result = Series(s, dtype=s.dtype) tm.assert_series_equal(result, s) result = Series(s.dt.tz_convert('UTC'), dtype=s.dtype) tm.assert_series_equal(result, s) result = Series(s.values, dtype=s.dtype) tm.assert_series_equal(result, s) def test_constructor_infer_period(self): data = [pd.Period('2000', 'D'), pd.Period('2001', 'D'), None] result = pd.Series(data) expected = pd.Series(period_array(data)) tm.assert_series_equal(result, expected) assert result.dtype == 'Period[D]' data = np.asarray(data, dtype=object) tm.assert_series_equal(result, expected) assert result.dtype == 'Period[D]' def test_constructor_period_incompatible_frequency(self): data = [pd.Period('2000', 'D'), pd.Period('2001', 'A')] result = pd.Series(data) assert result.dtype == object assert result.tolist() == data def test_constructor_periodindex(self): # GH7932 # converting a PeriodIndex when put in a Series pi = period_range('20130101', periods=5, freq='D') s = Series(pi) assert s.dtype == 'Period[D]' expected = Series(pi.astype(object)) assert_series_equal(s, expected) def test_constructor_dict(self): d = {'a': 0., 'b': 1., 'c': 2.} result = Series(d, index=['b', 'c', 'd', 'a']) expected = Series([1, 2, nan, 0], index=['b', 'c', 'd', 'a']) assert_series_equal(result, expected) pidx = tm.makePeriodIndex(100) d = {pidx[0]: 0, pidx[1]: 1} result = Series(d, index=pidx) expected = Series(np.nan, pidx) expected.iloc[0] = 0 expected.iloc[1] = 1 assert_series_equal(result, expected) def test_constructor_dict_order(self): # GH19018 # initialization ordering: by insertion order if python>= 3.6, else # order by value d = {'b': 1, 'a': 0, 'c': 2} result = Series(d) if PY36: expected = Series([1, 0, 2], index=list('bac')) else: expected = Series([0, 1, 2], index=list('abc')) tm.assert_series_equal(result, expected) @pytest.mark.parametrize("value", [2, np.nan, None, float('nan')]) def test_constructor_dict_nan_key(self, value): # GH 18480 d = {1: 'a', value: 'b', float('nan'): 'c', 4: 'd'} result = Series(d).sort_values() expected = Series(['a', 'b', 'c', 'd'], index=[1, value, np.nan, 4]) assert_series_equal(result, expected) # MultiIndex: d = {(1, 1): 'a', (2, np.nan): 'b', (3, value): 'c'} result = Series(d).sort_values() expected = Series(['a', 'b', 'c'], index=Index([(1, 1), (2, np.nan), (3, value)])) assert_series_equal(result, expected) def test_constructor_dict_datetime64_index(self): # GH 9456 dates_as_str = ['1984-02-19', '1988-11-06', '1989-12-03', '1990-03-15'] values = [42544017.198965244, 1234565, 40512335.181958228, -1] def create_data(constructor): return dict(zip((constructor(x) for x in dates_as_str), values)) data_datetime64 = create_data(np.datetime64) data_datetime = create_data(lambda x: datetime.strptime(x, '%Y-%m-%d')) data_Timestamp = create_data(Timestamp) expected = Series(values, (Timestamp(x) for x in dates_as_str)) result_datetime64 = Series(data_datetime64) result_datetime = Series(data_datetime) result_Timestamp = Series(data_Timestamp) assert_series_equal(result_datetime64, expected) assert_series_equal(result_datetime, expected) assert_series_equal(result_Timestamp, expected) def test_constructor_list_of_tuples(self): data = [(1, 1), (2, 2), (2, 3)] s = Series(data) assert list(s) == data def test_constructor_tuple_of_tuples(self): data = ((1, 1), (2, 2), (2, 3)) s = Series(data) assert tuple(s) == data def test_constructor_dict_of_tuples(self): data = {(1, 2): 3, (None, 5): 6} result = Series(data).sort_values() expected = Series([3, 6], index=MultiIndex.from_tuples([(1, 2), (None, 5)])) tm.assert_series_equal(result, expected) def test_constructor_set(self): values = {1, 2, 3, 4, 5} pytest.raises(TypeError, Series, values) values = frozenset(values) pytest.raises(TypeError, Series, values) # https://github.com/pandas-dev/pandas/issues/22698 @pytest.mark.filterwarnings("ignore:elementwise comparison:FutureWarning") def test_fromDict(self): data = {'a': 0, 'b': 1, 'c': 2, 'd': 3} series = Series(data) assert tm.is_sorted(series.index) data = {'a': 0, 'b': '1', 'c': '2', 'd': datetime.now()} series = Series(data) assert series.dtype == np.object_ data = {'a': 0, 'b': '1', 'c': '2', 'd': '3'} series = Series(data) assert series.dtype == np.object_ data = {'a': '0', 'b': '1'} series = Series(data, dtype=float) assert series.dtype == np.float64 def test_fromValue(self, datetime_series): nans = Series(np.NaN, index=datetime_series.index) assert nans.dtype == np.float_ assert len(nans) == len(datetime_series) strings = Series('foo', index=datetime_series.index) assert strings.dtype == np.object_ assert len(strings) == len(datetime_series) d = datetime.now() dates = Series(d, index=datetime_series.index) assert dates.dtype == 'M8[ns]' assert len(dates) == len(datetime_series) # GH12336 # Test construction of categorical series from value categorical = Series(0, index=datetime_series.index, dtype="category") expected = Series(0, index=datetime_series.index).astype("category") assert categorical.dtype == 'category' assert len(categorical) == len(datetime_series) tm.assert_series_equal(categorical, expected) def test_constructor_dtype_timedelta64(self): # basic td = Series([timedelta(days=i) for i in range(3)]) assert td.dtype == 'timedelta64[ns]' td = Series([timedelta(days=1)]) assert td.dtype == 'timedelta64[ns]' td = Series([timedelta(days=1), timedelta(days=2), np.timedelta64( 1, 's')]) assert td.dtype == 'timedelta64[ns]' # mixed with NaT td = Series([timedelta(days=1), NaT], dtype='m8[ns]') assert td.dtype == 'timedelta64[ns]' td = Series([timedelta(days=1), np.nan], dtype='m8[ns]') assert td.dtype == 'timedelta64[ns]' td = Series([np.timedelta64(300000000), pd.NaT], dtype='m8[ns]') assert td.dtype == 'timedelta64[ns]' # improved inference # GH5689 td = Series([np.timedelta64(300000000), NaT]) assert td.dtype == 'timedelta64[ns]' # because iNaT is int, not coerced to timedelta td = Series([np.timedelta64(300000000), iNaT]) assert td.dtype == 'object' td = Series([np.timedelta64(300000000), np.nan]) assert td.dtype == 'timedelta64[ns]' td = Series([pd.NaT, np.timedelta64(300000000)]) assert td.dtype == 'timedelta64[ns]' td = Series([np.timedelta64(1, 's')]) assert td.dtype == 'timedelta64[ns]' # these are frequency conversion astypes # for t in ['s', 'D', 'us', 'ms']: # pytest.raises(TypeError, td.astype, 'm8[%s]' % t) # valid astype td.astype('int64') # invalid casting pytest.raises(TypeError, td.astype, 'int32') # this is an invalid casting def f(): Series([timedelta(days=1), 'foo'], dtype='m8[ns]') pytest.raises(Exception, f) # leave as object here td = Series([timedelta(days=i) for i in range(3)] + ['foo']) assert td.dtype == 'object' # these will correctly infer a timedelta s = Series([None, pd.NaT, '1 Day']) assert s.dtype == 'timedelta64[ns]' s = Series([np.nan, pd.NaT, '1 Day']) assert s.dtype == 'timedelta64[ns]' s = Series([pd.NaT, None, '1 Day']) assert s.dtype == 'timedelta64[ns]' s = Series([pd.NaT, np.nan, '1 Day']) assert s.dtype == 'timedelta64[ns]' # GH 16406 def test_constructor_mixed_tz(self): s = Series([Timestamp('20130101'), Timestamp('20130101', tz='US/Eastern')]) expected = Series([Timestamp('20130101'), Timestamp('20130101', tz='US/Eastern')], dtype='object') assert_series_equal(s, expected) def test_NaT_scalar(self): series = Series([0, 1000, 2000, iNaT], dtype='M8[ns]') val = series[3] assert isna(val) series[2] = val assert isna(series[2]) def test_NaT_cast(self): # GH10747 result = Series([np.nan]).astype('M8[ns]') expected = Series([NaT]) assert_series_equal(result, expected) def test_constructor_name_hashable(self): for n in [777, 777., 'name', datetime(2001, 11, 11), (1, ), u"\u05D0"]: for data in [[1, 2, 3], np.ones(3), {'a': 0, 'b': 1}]: s = Series(data, name=n) assert s.name == n def test_constructor_name_unhashable(self): for n in [['name_list'], np.ones(2), {1: 2}]: for data in [['name_list'], np.ones(2), {1: 2}]: pytest.raises(TypeError, Series, data, name=n) def test_auto_conversion(self): series = Series(list(date_range('1/1/2000', periods=10))) assert series.dtype == 'M8[ns]' def test_convert_non_ns(self): # convert from a numpy array of non-ns timedelta64 arr = np.array([1, 2, 3], dtype='timedelta64[s]') s = Series(arr) expected = Series(pd.timedelta_range('00:00:01', periods=3, freq='s')) assert_series_equal(s, expected) # convert from a numpy array of non-ns datetime64 # note that creating a numpy datetime64 is in LOCAL time!!!! # seems to work for M8[D], but not for M8[s] s = Series(np.array(['2013-01-01', '2013-01-02', '2013-01-03'], dtype='datetime64[D]')) assert_series_equal(s, Series(date_range('20130101', periods=3, freq='D'))) # s = Series(np.array(['2013-01-01 00:00:01','2013-01-01 # 00:00:02','2013-01-01 00:00:03'],dtype='datetime64[s]')) # assert_series_equal(s,date_range('20130101 # 00:00:01',period=3,freq='s')) @pytest.mark.parametrize( "index", [ date_range('1/1/2000', periods=10), timedelta_range('1 day', periods=10), period_range('2000-Q1', periods=10, freq='Q')], ids=lambda x: type(x).__name__) def test_constructor_cant_cast_datetimelike(self, index): # floats are not ok msg = "Cannot cast {}.*? to ".format( # strip Index to convert PeriodIndex -> Period # We don't care whether the error message says # PeriodIndex or PeriodArray type(index).__name__.rstrip("Index") ) with tm.assert_raises_regex(TypeError, msg): Series(index, dtype=float) # ints are ok # we test with np.int64 to get similar results on # windows / 32-bit platforms result = Series(index, dtype=np.int64) expected = Series(index.astype(np.int64)) tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "index", [ date_range('1/1/2000', periods=10), timedelta_range('1 day', periods=10), period_range('2000-Q1', periods=10, freq='Q')], ids=lambda x: type(x).__name__) def test_constructor_cast_object(self, index): s = Series(index, dtype=object) exp = Series(index).astype(object) tm.assert_series_equal(s, exp) s = Series(pd.Index(index, dtype=object), dtype=object) exp = Series(index).astype(object) tm.assert_series_equal(s, exp) s = Series(index.astype(object), dtype=object) exp = Series(index).astype(object) tm.assert_series_equal(s, exp) @pytest.mark.parametrize("dtype", [ np.datetime64, np.timedelta64, ]) def test_constructor_generic_timestamp_no_frequency(self, dtype): # see gh-15524, gh-15987 msg = "dtype has no unit. Please pass in" with tm.assert_raises_regex(ValueError, msg): Series([], dtype=dtype) @pytest.mark.parametrize("dtype,msg", [ ("m8[ps]", "cannot convert timedeltalike"), ("M8[ps]", "cannot convert datetimelike"), ]) def test_constructor_generic_timestamp_bad_frequency(self, dtype, msg): # see gh-15524, gh-15987 with tm.assert_raises_regex(TypeError, msg): Series([], dtype=dtype) @pytest.mark.parametrize('dtype', [None, 'uint8', 'category']) def test_constructor_range_dtype(self, dtype): # GH 16804 expected = Series([0, 1, 2, 3, 4], dtype=dtype or 'int64') result = Series(range(5), dtype=dtype) tm.assert_series_equal(result, expected) def test_constructor_tz_mixed_data(self): # GH 13051 dt_list = [Timestamp('2016-05-01 02:03:37'), Timestamp('2016-04-30 19:03:37-0700', tz='US/Pacific')] result = Series(dt_list) expected = Series(dt_list, dtype=object) tm.assert_series_equal(result, expected)
harisbal/pandas
pandas/tests/series/test_constructors.py
Python
bsd-3-clause
44,946
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2016-11-15 17:45 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('ovp_projects', '0011_auto_20161115_1744'), ] operations = [ migrations.RenameModel( old_name='Role', new_name='VolunteerRole', ), ]
OpenVolunteeringPlatform/django-ovp-projects
ovp_projects/migrations/0012_auto_20161115_1745.py
Python
agpl-3.0
405
#!/usr/bin/python # -*- coding: utf-8 -*- """ This file is part of XBMC Mega Pack Addon. Copyright (C) 2014 Wolverine ([email protected]) 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/gpl-3.0.html """ class Languages_Slovenian(): '''Class that manages this specific menu context.''' def open(self, plugin, menu): menu.add_xplugins(plugin.get_xplugins(dictionaries=["Channels", "Events", "Live", "Movies", "Sports", "TVShows"], languages=["Slovenian"]))
xbmcmegapack/plugin.video.megapack.dev
resources/lib/menus/home_languages_slovenian.py
Python
gpl-3.0
1,115
# Copyright (C) 2014 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY expressed or implied, including the implied warranties of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. You should have received a copy of the # GNU General Public License along with this program; if not, write to the # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. Any Red Hat trademarks that are incorporated in the # source code or documentation are not subject to the GNU General Public # License and may only be used or replicated with the express permission of # Red Hat, Inc. # from __future__ import absolute_import from __future__ import unicode_literals from tests.support import mock, RepoStub import dnf.cli import dnf.repodict import dnf.sack import dnf.subject import download import unittest import hawkey import tempfile import os class PkgStub: def __init__(self, n, e, v, r, a, repo_id, src_name=""): """Mocking dnf.package.Package.""" self.name = n self.version = v self.release = r self.arch = a self.epoch = e self.reponame = repo_id self.src_name = src_name def __str__(self): return '%s : %s' % (self.fullname, self.reponame) @property def evr(self): if self.epoch != '0': return '%s:%s-%s' % (self.epoch, self.version, self.release) else: return '%s-%s' % (self.version, self.release) @property def source_debug_name(self): """ returns name of debuginfo package for source package of given package e.g. krb5-libs -> krb5-debuginfo """ return "{}-debuginfo".format(self.source_name) @property def source_name(self): """" returns name of source package e.g. krb5-libs -> krb5 """ if self.sourcerpm is not None: # trim suffix first srcname = dnf.util.rtrim(self.sourcerpm, ".src.rpm") # source package filenames may not contain epoch, handle both cases srcname = dnf.util.rtrim(srcname, "-{}".format(self.evr)) srcname = dnf.util.rtrim(srcname, "-{0.version}-{0.release}".format(self)) else: srcname = None return srcname @property def sourcerpm(self): name = self.src_name or self.name # special cases for debuginfo tests if name == "kernel-PAE": name = "kernel" elif name == "krb5-libs": name = "krb5" if self.arch != 'src': return '%s-%s.src.rpm' % (name, self.evr) else: return '%s-%s.%s.rpm' % (name, self.evr, self.arch) @property def fullname(self): return '%s-%s.%s' % (self.name, self.evr, self.arch) def localPkg(self): return '/tmp/dnf/%s-%s.%s.rpm' % (self.name, self.evr, self.arch) @property def from_cmdline(self): return True @property def debug_name(self): """ returns name of debuginfo package for given package e.g. kernel-PAE -> kernel-PAE-debuginfo """ return "{}-debuginfo".format(self.name) class NoSrcStub(PkgStub): """ Pkg with no source rpm""" @property def sourcerpm(self): return None class QueryStub(object): """Mocking dnf.query.Query.""" def __init__(self, inst, avail, latest, sources, debuginfo): self._inst = inst self._avail = avail self._latest = latest self._sources = sources self._debuginfo = debuginfo self._all = [] self._all.extend(inst) self._all.extend(avail) self._all.extend(sources) self._all.extend(debuginfo) self._filter = {} self._pkg_spec = None def available(self): self._filter = {'available' : True} return self def installed(self): self._filter = {'installed' : True } return self def latest(self): self._filter = {'latest' : True } return self def filter(self, **kwargs): self._filter = kwargs return self def _stub_filter(self, **kwargs): results = self._all if 'available' in kwargs: results = self._avail elif 'installed' in kwargs: results = self._inst elif 'latest' in kwargs: results = self._latest name = None if 'name' in kwargs: name = kwargs['name'] self._pkg_spec = None elif self._pkg_spec: name = self._pkg_spec if name: results = [pkg for pkg in results if pkg.name == name] if 'arch' in kwargs: arch = kwargs['arch'] results = [pkg for pkg in results if pkg.arch == arch] if 'version' in kwargs: version = kwargs['version'] results = [pkg for pkg in results if pkg.version == version] return results def run(self): return self._stub_filter(**self._filter) def __len__(self): results = self.run() return len(results) def __getitem__(self, key): return self.run()[key] PACKAGES_AVAIL = [ PkgStub('foo', '0', '1.0', '1', 'noarch', 'test-repo'), PkgStub('foo', '0', '2.0', '1', 'noarch', 'test-repo'), PkgStub('bar', '0', '1.0', '1', 'noarch', 'test-repo'), PkgStub('bar', '0', '2.0', '1', 'noarch', 'test-repo'), PkgStub('foobar', '0', '1.0', '1', 'noarch', 'test-repo'), PkgStub('foobar', '0', '2.0', '1', 'noarch', 'test-repo'), PkgStub('kernel-PAE', '0', '4.0', '1', 'x86_64', 'test-repo'), PkgStub('krb5-libs', '0', '1.12', '1', 'x86_64', 'test-repo'), ] PACKAGES_DEBUGINFO = [ PkgStub('foo-debuginfo', '0', '1.0', '1', 'noarch', 'test-repo-debuginfo'), PkgStub('foo-debuginfo', '0', '2.0', '1', 'noarch', 'test-repo-debuginfo'), PkgStub('bar-debuginfo', '0', '1.0', '1', 'noarch', 'test-repo-debuginfo'), PkgStub('bar-debuginfo', '0', '2.0', '1', 'noarch', 'test-repo-debuginfo'), PkgStub('kernel-PAE-debuginfo', '0', '4.0', '1', 'x86_64', 'test-repo-debuginfo'), PkgStub('krb5-debuginfo', '0', '1.12', '1', 'x86_64', 'test-repo-debuginfo'), ] PACKAGES_LASTEST = [ PACKAGES_AVAIL[1], PACKAGES_AVAIL[3], PACKAGES_AVAIL[5], PACKAGES_AVAIL[6], PACKAGES_AVAIL[7], PACKAGES_DEBUGINFO[1], PACKAGES_DEBUGINFO[3], PACKAGES_DEBUGINFO[4], PACKAGES_DEBUGINFO[5], ] PACKAGES_INST = [ PkgStub('foo', '0', '1.0', '1', 'noarch', '@System'), PkgStub('foobar', '0', '1.0', '1', 'noarch', '@System') ] PACKAGES_SOURCE = [ PkgStub('foo', '0', '1.0', '1', 'src', 'test-repo-source'), PkgStub('foo', '0', '2.0', '1', 'src', 'test-repo-source'), PkgStub('bar', '0', '1.0', '1', 'src', 'test-repo-source'), PkgStub('bar', '0', '2.0', '1', 'src', 'test-repo-source'), PkgStub('foobar', '0', '1.0', '1', 'src', 'test-repo-source'), PkgStub('foobar', '0', '2.0', '1', 'src', 'test-repo-source'), PkgStub('kernel', '0', '4.0', '1', 'src', 'test-repo-source'), PkgStub('krb5', '0', '1.12', '1', 'src', 'test-repo-source'), ] class SackStub(dnf.sack.Sack): def query(self): return QueryStub(PACKAGES_INST, PACKAGES_AVAIL, PACKAGES_LASTEST, PACKAGES_SOURCE, PACKAGES_DEBUGINFO) class SubjectStub(dnf.subject.Subject): def __init__(self, pkg_spec, ignore_case=False): super(self.__class__, self).__init__(pkg_spec, ignore_case) self.pkg_spec = pkg_spec def get_best_query(self, sack, with_provides=True, forms=None): Q = QueryStub(PACKAGES_INST, PACKAGES_AVAIL, PACKAGES_LASTEST, PACKAGES_SOURCE, PACKAGES_DEBUGINFO) Q._pkg_spec = self.pkg_spec return Q class DownloadCommandTest(unittest.TestCase): def setUp(self): cli = mock.MagicMock() self.cmd = download.DownloadCommand(cli) self.cmd.cli.base = dnf.cli.cli.BaseCli() self.cmd.cli.base.add_remote_rpms = mock.MagicMock() self.cmd.cli.base.download_packages = mock.Mock() # point the Sack and Subject to out stubs # b/c these are used in the _get_query methods self.orig_sack = self.cmd.cli.base.sack self.cmd.cli.base._sack = SackStub() self.orig_subject = dnf.subject.Subject dnf.subject.Subject = SubjectStub self.cmd.opts = mock.Mock() self.cmd.opts.resolve = False self.cmd.opts.arches = [] repo = RepoStub('foo') repo.enable() self.cmd.base.repos.add(repo) repo = RepoStub('foo-source') repo.disable() self.cmd.base.repos.add(repo) repo = RepoStub('bar') repo.enable() self.cmd.base.repos.add(repo) repo = RepoStub('foobar-source') repo.disable() self.cmd.base.repos.add(repo) repo = RepoStub('foo-debuginfo') repo.disable() self.cmd.base.repos.add(repo) def tearDown(self): # restore the default values self.cmd.cli.base._sack = self.orig_sack dnf.subject.Subject = self.orig_subject def test_enable_source_repos(self): repos = self.cmd.base.repos self.assertTrue(repos['foo'].enabled) self.assertFalse(repos['foo-source'].enabled) self.assertTrue(repos['bar'].enabled) self.assertFalse(repos['foobar-source'].enabled) repos.enable_source_repos() self.assertTrue(repos['foo-source'].enabled) self.assertTrue(repos['foo'].enabled) self.assertTrue(repos['bar'].enabled) self.assertFalse(repos['foobar-source'].enabled) def test_enable_debuginfo_repos(self): repos = self.cmd.base.repos self.assertFalse(repos['foo-debuginfo'].enabled) repos.enable_debug_repos() self.assertTrue(repos['foo-debuginfo'].enabled) def test_get_source_packages(self): pkg = PkgStub('foo', '0', '1.0', '1', 'noarch', 'test-repo') found = self.cmd._get_source_packages([pkg]) self.assertEqual(found[0], 'foo-1.0-1.src.rpm') def test_no_source_rpm(self): # test pkgs with no source rpm pkg = NoSrcStub('foo', '0', '1.0', '1', 'noarch', 'test-repo') found = self.cmd._get_source_packages([pkg]) self.assertEqual(len(found), 0) def test_get_query(self): found = self.cmd._get_query('foo') self.assertEqual(len(found), 1) self.assertEqual(found[0].name, 'foo') found = self.cmd._get_query('bar') self.assertEqual(len(found), 1) self.assertEqual(found[0].name, 'bar') def test_get_query_with_local_rpm(self): try: (fs, rpm_path) = tempfile.mkstemp('foobar-99.99-1.x86_64.rpm') # b/c self.cmd.cli.base.add_remote_rpms is a mock object it # will not update the available packages while testing. # it is expected to hit this exception with self.assertRaises(dnf.exceptions.PackageNotFoundError): self.cmd._get_query(rpm_path) self.cmd.cli.base.add_remote_rpms.assert_called_with([rpm_path]) finally: os.remove(rpm_path) def test_get_query_source(self): pkgs = self.cmd._get_query_source('foo-2.0-1.src.rpm') self.assertEqual(len(pkgs), 1) self.assertEqual(pkgs[0].arch, 'src') self.assertEqual(pkgs[0].reponame, 'test-repo-source') def test_get_packages(self): pkgs = self.cmd._get_packages(['bar']) self.assertEqual(len(pkgs), 1) self.assertEqual(pkgs[0].name, 'bar') pkgs = self.cmd._get_packages(['bar', 'foo']) self.assertEqual(len(pkgs), 2) self.assertEqual(pkgs[0].name, 'bar') self.assertEqual(pkgs[1].name, 'foo') strict_orig = self.cmd.base.conf.strict self.cmd.base.conf.strict = True with self.assertRaises(dnf.exceptions.Error): pkgs = self.cmd._get_packages(['notfound']) pkgs = self.cmd._get_packages(['notfound', 'bar']) self.cmd.base.conf.strict = False pkgs = self.cmd._get_packages(['notfound']) self.assertEqual(len(pkgs), 0) pkgs = self.cmd._get_packages(['notfound', 'bar']) self.assertEqual(len(pkgs), 1) self.cmd.base.conf.strict = strict_orig self.assertEqual(pkgs[0].name, 'bar') pkgs = self.cmd._get_packages(['foo-2.0-1.src.rpm'], source=True) self.assertEqual(len(pkgs), 1) self.assertEqual(pkgs[0].arch, 'src') self.assertEqual(pkgs[0].reponame, 'test-repo-source') def test_download_rpms(self): pkgs = self.cmd._get_pkg_objs_rpms(['foo']) locations = self.cmd._do_downloads(pkgs) self.assertEqual(len(locations), 1) self.assertEqual(locations[0], '/tmp/dnf/foo-2.0-1.noarch.rpm') pkgs = self.cmd._get_pkg_objs_rpms(['foo', 'bar']) locations = self.cmd._do_downloads(pkgs) self.assertEqual(len(locations), 2) self.assertEqual(locations[0], '/tmp/dnf/bar-2.0-1.noarch.rpm') self.assertEqual(locations[1], '/tmp/dnf/foo-2.0-1.noarch.rpm') self.assertTrue(self.cmd.base.download_packages.called) def test_download_source(self): pkgs = self.cmd._get_pkg_objs_source(['foo']) locations = self.cmd._do_downloads(pkgs) self.assertEqual(len(locations), 1) self.assertEqual(locations[0], '/tmp/dnf/foo-2.0-1.src.rpm') pkgs = self.cmd._get_pkg_objs_source(['foo', 'bar']) locations = self.cmd._do_downloads(pkgs) self.assertEqual(len(locations), 2) self.assertEqual(locations[0], '/tmp/dnf/bar-2.0-1.src.rpm') self.assertEqual(locations[1], '/tmp/dnf/foo-2.0-1.src.rpm') def test_download_debuginfo(self): pkgs = self.cmd._get_pkg_objs_debuginfo(['kernel-PAE']) locations = self.cmd._do_downloads(pkgs) self.assertEqual(len(locations), 1) self.assertEqual(locations[0], '/tmp/dnf/kernel-PAE-debuginfo-4.0-1.x86_64.rpm') pkgs = self.cmd._get_pkg_objs_debuginfo(['krb5-libs']) locations = self.cmd._do_downloads(pkgs) self.assertEqual(len(locations), 1) self.assertEqual(locations[0], '/tmp/dnf/krb5-debuginfo-1.12-1.x86_64.rpm') pkgs = self.cmd._get_pkg_objs_debuginfo(['foo']) locations = self.cmd._do_downloads(pkgs) self.assertEqual(len(locations), 1) self.assertEqual(locations[0], '/tmp/dnf/foo-debuginfo-2.0-1.noarch.rpm') pkgs = self.cmd._get_pkg_objs_debuginfo(['foo', 'bar']) locations = self.cmd._do_downloads(pkgs) self.assertEqual(len(locations), 2) self.assertEqual(locations[0], '/tmp/dnf/bar-debuginfo-2.0-1.noarch.rpm') self.assertEqual(locations[1], '/tmp/dnf/foo-debuginfo-2.0-1.noarch.rpm')
fedora-copr/dnf-plugins-core
tests/test_download.py
Python
gpl-2.0
15,115
try: import pymysql pymysql.install_as_MySQLdb() except ImportError: pass #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "montasola.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
mlvander/montasola
manage.py
Python
mit
339
#!/usr/bin/python # -*- coding: utf-8 -*- # # --- BEGIN_HEADER --- # # cp - [insert a few words of module description on this line] # Copyright (C) 2003-2009 The MiG Project lead by Brian Vinter # # This file is part of MiG. # # MiG 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. # # MiG is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # -- END_HEADER --- # import cgi import cgitb cgitb.enable() from shared.functionality.cp import main from shared.cgiscriptstub import run_cgi_script run_cgi_script(main)
heromod/migrid
mig/cgi-bin/cp.py
Python
gpl-2.0
1,092
import json from django.http import HttpResponse from django.contrib.auth.models import User from django.shortcuts import get_object_or_404 from apps.exercises.models import Attempts from apps.maps.models import Graphs from apps.ki.utils import performInference from apps.research.utils import getParticipantByUID, studyFilter def knowledge_inference(request, gid=""): if request.method == "GET": g = get_object_or_404(Graphs, pk=gid) if not request.user.is_authenticated(): return HttpResponse(status=403) u, uc = User.objects.get_or_create(pk=request.user.pk) p = getParticipantByUID(request.user.pk, gid) if g.study_active and p is None: return HttpResponse(status=401) ex = Attempts.objects.filter(graph=g).filter(submitted=True) ex = studyFilter(g, p, u, ex) inferences = [] if ex.count() > 1: r = [e.get_correctness() for e in ex] inferences = performInference(g.concept_dict, r) return HttpResponse(json.dumps(inferences), mimetype='application/json') else: return HttpResponse(status=405)
danallan/octal-application
server/apps/ki/views.py
Python
gpl-3.0
1,125
import base64 import hashlib import heapq import itertools import os import re import string from itertools import zip_longest from time import sleep from typing import Any, Callable, Iterator, List, Optional, Sequence, Set, Tuple, TypeVar from django.conf import settings T = TypeVar('T') def statsd_key(val: Any, clean_periods: bool=False) -> str: if not isinstance(val, str): val = str(val) if ':' in val: val = val.split(':')[0] val = val.replace('-', "_") if clean_periods: val = val.replace('.', '_') return val class StatsDWrapper: """Transparently either submit metrics to statsd or do nothing without erroring out""" # Backported support for gauge deltas # as our statsd server supports them but supporting # pystatsd is not released yet def _our_gauge(self, stat: str, value: float, rate: float=1, delta: bool=False) -> None: """Set a gauge value.""" from django_statsd.clients import statsd if delta: value_str = f'{value:+g}|g' else: value_str = f'{value:g}|g' statsd._send(stat, value_str, rate) def __getattr__(self, name: str) -> Any: # Hand off to statsd if we have it enabled # otherwise do nothing if name in ['timer', 'timing', 'incr', 'decr', 'gauge']: if settings.STATSD_HOST != '': from django_statsd.clients import statsd if name == 'gauge': return self._our_gauge else: return getattr(statsd, name) else: return lambda *args, **kwargs: None raise AttributeError statsd = StatsDWrapper() # Runs the callback with slices of all_list of a given batch_size def run_in_batches(all_list: Sequence[T], batch_size: int, callback: Callable[[Sequence[T]], None], sleep_time: int=0, logger: Optional[Callable[[str], None]]=None) -> None: if len(all_list) == 0: return limit = (len(all_list) // batch_size) + 1 for i in range(limit): start = i*batch_size end = (i+1) * batch_size if end >= len(all_list): end = len(all_list) batch = all_list[start:end] if logger: logger(f"Executing {end-start} in batch {i+1} of {limit}") callback(batch) if i != limit - 1: sleep(sleep_time) def make_safe_digest(string: str, hash_func: Callable[[bytes], Any]=hashlib.sha1) -> str: """ return a hex digest of `string`. """ # hashlib.sha1, md5, etc. expect bytes, so non-ASCII strings must # be encoded. return hash_func(string.encode('utf-8')).hexdigest() def log_statsd_event(name: str) -> None: """ Sends a single event to statsd with the desired name and the current timestamp This can be used to provide vertical lines in generated graphs, for example when doing a prod deploy, bankruptcy request, or other one-off events Note that to draw this event as a vertical line in graphite you can use the drawAsInfinite() command """ event_name = f"events.{name}" statsd.incr(event_name) def generate_random_token(length: int) -> str: return str(base64.b16encode(os.urandom(length // 2)).decode('utf-8').lower()) def generate_api_key() -> str: choices = string.ascii_letters + string.digits altchars = ''.join([choices[ord(os.urandom(1)) % 62] for _ in range(2)]).encode("utf-8") api_key = base64.b64encode(os.urandom(24), altchars=altchars).decode("utf-8") return api_key def has_api_key_format(key: str) -> bool: return bool(re.fullmatch(r"([A-Za-z0-9]){32}", key)) def query_chunker(queries: List[Any], id_collector: Optional[Set[int]]=None, chunk_size: int=1000, db_chunk_size: Optional[int]=None) -> Iterator[Any]: ''' This merges one or more Django ascending-id queries into a generator that returns chunks of chunk_size row objects during each yield, preserving id order across all results.. Queries should satisfy these conditions: - They should be Django filters. - They should return Django objects with "id" attributes. - They should be disjoint. The generator also populates id_collector, which we use internally to enforce unique ids, but which the caller can pass in to us if they want the side effect of collecting all ids. ''' if db_chunk_size is None: db_chunk_size = chunk_size // len(queries) assert db_chunk_size >= 2 assert chunk_size >= 2 if id_collector is not None: assert(len(id_collector) == 0) else: id_collector = set() def chunkify(q: Any, i: int) -> Iterator[Tuple[int, int, Any]]: q = q.order_by('id') min_id = -1 while True: assert db_chunk_size is not None # Hint for mypy, but also workaround for mypy bug #3442. rows = list(q.filter(id__gt=min_id)[0:db_chunk_size]) if len(rows) == 0: break for row in rows: yield (row.id, i, row) min_id = rows[-1].id iterators = [chunkify(q, i) for i, q in enumerate(queries)] merged_query = heapq.merge(*iterators) while True: tup_chunk = list(itertools.islice(merged_query, 0, chunk_size)) if len(tup_chunk) == 0: break # Do duplicate-id management here. tup_ids = {tup[0] for tup in tup_chunk} assert len(tup_ids) == len(tup_chunk) assert len(tup_ids.intersection(id_collector)) == 0 id_collector.update(tup_ids) yield [row for row_id, i, row in tup_chunk] def process_list_in_batches(lst: List[Any], chunk_size: int, process_batch: Callable[[List[Any]], None]) -> None: offset = 0 while True: items = lst[offset:offset+chunk_size] if not items: break process_batch(items) offset += chunk_size def split_by(array: List[Any], group_size: int, filler: Any) -> List[List[Any]]: """ Group elements into list of size `group_size` and fill empty cells with `filler`. Recipe from https://docs.python.org/3/library/itertools.html """ args = [iter(array)] * group_size return list(map(list, zip_longest(*args, fillvalue=filler)))
brainwane/zulip
zerver/lib/utils.py
Python
apache-2.0
6,519
##################################################################### # -*- coding: iso-8859-1 -*- # # # # Frets on Fire # # Copyright (C) 2006 Sami Kyöstilä # # 2008 myfingershurt # # # # This program is free software; you can redistribute it and/or # # modify it under the terms of the GNU General Public License # # as published by the Free Software Foundation; either version 2 # # of the License, or (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program; if not, write to the Free Software # # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # # MA 02110-1301, USA. # ##################################################################### import pygame import numpy as np from fofix.core import Log from fofix.core.Task import Task from fofix.core.MixStream import VorbisFileMixStream #stump: get around some strangeness in pygame when py2exe'd... if not hasattr(pygame.mixer, 'music'): import sys __import__('pygame.mixer_music') pygame.mixer.music = sys.modules['pygame.mixer_music'] class Audio: def pre_open(self, frequency = 22050, bits = 16, stereo = True, bufferSize = 1024): pygame.mixer.pre_init(frequency, -bits, stereo and 2 or 1, bufferSize) return True def open(self, frequency = 22050, bits = 16, stereo = True, bufferSize = 1024): try: pygame.mixer.quit() except: pass try: pygame.mixer.init(frequency, -bits, stereo and 2 or 1, bufferSize) except: Log.warn("Audio setup failed. Trying with default configuration.") pygame.mixer.init() Log.debug("Audio configuration: %s" % str(pygame.mixer.get_init())) #myfingershurt: ensuring we have enough audio channels! pygame.mixer.set_num_channels(10) return True #myfingershurt: def findChannel(self): return pygame.mixer.find_channel() def getChannelCount(self): return pygame.mixer.get_num_channels() def getChannel(self, n): return Channel(n) def close(self): try: pygame.mixer.quit() except: pass def pause(self): pygame.mixer.pause() def unpause(self): pygame.mixer.unpause() class Music(object): def __init__(self, fileName): pygame.mixer.music.load(fileName) @staticmethod def setEndEvent(event = None): if event: pygame.mixer.music.set_endevent(event) else: pygame.mixer.music.set_endevent() #MFH - to set NO event. def play(self, loops = -1, pos = 0.0): pygame.mixer.music.play(loops, pos) def stop(self): pygame.mixer.music.stop() def rewind(self): pygame.mixer.music.rewind() def pause(self): pygame.mixer.music.pause() def unpause(self): pygame.mixer.music.unpause() def setVolume(self, volume): pygame.mixer.music.set_volume(volume) def fadeout(self, time): pygame.mixer.music.fadeout(time) def isPlaying(self): return pygame.mixer.music.get_busy() def getPosition(self): return pygame.mixer.music.get_pos() class Channel(object): def __init__(self, id): self.channel = pygame.mixer.Channel(id) self.id = id def play(self, sound): self.channel.play(sound.sound) def stop(self): self.channel.stop() def setVolume(self, volume): self.channel.set_volume(volume) def fadeout(self, time): self.channel.fadeout(time) class Sound(object): def __init__(self, fileName): self.sound = pygame.mixer.Sound(fileName) def isPlaying(self): #MFH - adding function to check if sound is playing return self.sound.get_num_channels() def play(self, loops = 0): self.sound.play(loops) def stop(self): self.sound.stop() def setVolume(self, volume): self.sound.set_volume(volume) def fadeout(self, time): self.sound.fadeout(time) #stump: mic passthrough class MicrophonePassthroughStream(Sound, Task): def __init__(self, engine, mic): Task.__init__(self) self.engine = engine self.channel = None self.mic = mic self.playing = False self.volume = 1.0 def __del__(self): self.stop() def play(self): if not self.playing: self.engine.addTask(self, synchronized=False) self.playing = True def stop(self): if self.playing: self.channel.stop() self.engine.removeTask(self) self.playing = False def setVolume(self, vol): self.volume = vol def run(self, ticks): chunk = ''.join(self.mic.passthroughQueue) self.mic.passthroughQueue = [] if chunk == '': return data = np.frombuffer(chunk, dtype=np.float32) * 32767.0 playbuf = np.zeros((len(data), 2), dtype=np.int16) playbuf[:, 0] = data playbuf[:, 1] = data snd = pygame.mixer.Sound(buffer(playbuf)) if self.channel is None or not self.channel.get_busy(): self.channel = snd.play() else: self.channel.queue(snd) self.channel.set_volume(self.volume) class StreamingSound(object): def __init__(self, channel, fileName): self._mixstream = VorbisFileMixStream(fileName) self._channel = channel def play(self): self._mixstream.play(self._channel.id) def stop(self): self._mixstream.stop() self._channel.stop() def setVolume(self, volume): self._channel.setVolume(volume) def isPlaying(self): return self._mixstream.is_playing() def fadeout(self, time): # TODO self.stop() def getPosition(self): return self._mixstream.get_position() def setPosition(self, position): return self._mixstream.seek(position) def setPitchBendSemitones(self, semitones): self._mixstream.set_pitch_semitones(semitones) def setSpeed(self, factor): self._mixstream.set_speed(factor)
mdsitton/fofix
fofix/core/Audio.py
Python
gpl-2.0
7,008
# Copyright 2014: Mirantis Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from boto import exception as boto_exception from neutronclient.common import exceptions as neutron_exceptions from saharaclient.api import base as saharaclient_base from rally.common import log as logging from rally.plugins.openstack.context.cleanup import base from rally.plugins.openstack import scenario from rally.plugins.openstack.scenarios.keystone import utils as kutils from rally.plugins.openstack.wrappers import keystone as keystone_wrapper LOG = logging.getLogger(__name__) def get_order(start): return iter(range(start, start + 99)) class SynchronizedDeletion(object): def is_deleted(self): return True class QuotaMixin(SynchronizedDeletion): def id(self): return self.raw_resource def delete(self): self._manager().delete(self.raw_resource) def list(self): return [self.tenant_uuid] if self.tenant_uuid else [] # HEAT @base.resource("heat", "stacks", order=100, tenant_resource=True) class HeatStack(base.ResourceManager): pass # NOVA _nova_order = get_order(200) @base.resource("nova", "servers", order=next(_nova_order)) class NovaServer(base.ResourceManager): def list(self): """List all servers.""" if hasattr(self._manager().api, "api_version"): # NOTE(andreykurilin): novaclient v2.27.0 includes ability to # return all servers(see https://review.openstack.org/#/c/217101 # for more details). This release can be identified by presence # of "api_version" property of ``novaclient.client.Client`` cls. return self._manager().list(limit=-1) else: # FIXME(andreykurilin): Remove code below, when minimum version of # novaclient in requirements will allow it. # NOTE(andreykurilin): Nova API returns only limited number( # 'osapi_max_limit' option in nova.conf) of servers, so we need # to use 'marker' option to list all pages of servers. result = [] marker = None while True: servers = self._manager().list(marker=marker) if not servers: break result.extend(servers) marker = servers[-1].id return result def delete(self): if getattr(self.raw_resource, "OS-EXT-STS:locked", False): self.raw_resource.unlock() super(NovaServer, self).delete() @base.resource("nova", "floating_ips", order=next(_nova_order)) class NovaFloatingIPs(SynchronizedDeletion, base.ResourceManager): pass @base.resource("nova", "keypairs", order=next(_nova_order)) class NovaKeypair(SynchronizedDeletion, base.ResourceManager): pass @base.resource("nova", "security_groups", order=next(_nova_order)) class NovaSecurityGroup(SynchronizedDeletion, base.ResourceManager): def list(self): return filter(lambda x: x.name != "default", super(NovaSecurityGroup, self).list()) @base.resource("nova", "quotas", order=next(_nova_order), admin_required=True, tenant_resource=True) class NovaQuotas(QuotaMixin, base.ResourceManager): pass @base.resource("nova", "floating_ips_bulk", order=next(_nova_order), admin_required=True) class NovaFloatingIpsBulk(SynchronizedDeletion, base.ResourceManager): def id(self): return self.raw_resource.address def list(self): return [floating_ip for floating_ip in self._manager().list() if floating_ip.pool.startswith("rally_fip_pool_")] @base.resource("nova", "networks", order=next(_nova_order), admin_required=True) class NovaNetworks(SynchronizedDeletion, base.ResourceManager): def list(self): return [net for net in self._manager().list() if net.label.startswith("rally_novanet")] # EC2 _ec2_order = get_order(250) class EC2Mixin(object): def _manager(self): return getattr(self.user, self._service)() @base.resource("ec2", "servers", order=next(_ec2_order)) class EC2Server(EC2Mixin, base.ResourceManager): def is_deleted(self): try: instances = self._manager().get_only_instances( instance_ids=[self.id()]) except boto_exception.EC2ResponseError as e: # NOTE(wtakase): Nova EC2 API returns 'InvalidInstanceID.NotFound' # if instance not found. In this case, we consider # instance has already been deleted. return getattr(e, "error_code") == "InvalidInstanceID.NotFound" # NOTE(wtakase): After instance deletion, instance can be 'terminated' # state. If all instance states are 'terminated', this # returns True. And if get_only_instaces() returns empty # list, this also returns True because we consider # instance has already been deleted. return all(map(lambda i: i.state == "terminated", instances)) def delete(self): self._manager().terminate_instances(instance_ids=[self.id()]) def list(self): return self._manager().get_only_instances() # NEUTRON _neutron_order = get_order(300) @base.resource(service=None, resource=None, admin_required=True) class NeutronMixin(SynchronizedDeletion, base.ResourceManager): # Neutron has the best client ever, so we need to override everything def supports_extension(self, extension): exts = self._manager().list_extensions().get("extensions", []) if any(ext.get("alias") == extension for ext in exts): return True return False def _manager(self): client = self._admin_required and self.admin or self.user return getattr(client, self._service)() def id(self): return self.raw_resource["id"] def delete(self): delete_method = getattr(self._manager(), "delete_%s" % self._resource) delete_method(self.id()) def list(self): resources = self._resource + "s" list_method = getattr(self._manager(), "list_%s" % resources) return filter(lambda r: r["tenant_id"] == self.tenant_uuid, list_method({"tenant_id": self.tenant_uuid})[resources]) class NeutronLbaasV1Mixin(NeutronMixin): def list(self): if self.supports_extension("lbaas"): return super(NeutronLbaasV1Mixin, self).list() return [] @base.resource("neutron", "port", order=next(_neutron_order), tenant_resource=True) class NeutronPort(NeutronMixin): def delete(self): if (self.raw_resource["device_owner"] == "network:router_interface" or self.raw_resource["device_owner"] == "network:router_interface_distributed"): self._manager().remove_interface_router( self.raw_resource["device_id"], {"port_id": self.raw_resource["id"]}) else: try: self._manager().delete_port(self.id()) except neutron_exceptions.PortNotFoundClient: # Port can be already auto-deleted, skip silently LOG.debug("Port %s was not deleted. Skip silently because " "port can be already auto-deleted." % self.id()) @base.resource("neutron", "router", order=next(_neutron_order), tenant_resource=True) class NeutronRouter(NeutronMixin): pass @base.resource("neutron", "vip", order=next(_neutron_order), tenant_resource=True) class NeutronV1Vip(NeutronLbaasV1Mixin): pass @base.resource("neutron", "pool", order=next(_neutron_order), tenant_resource=True) class NeutronV1Pool(NeutronLbaasV1Mixin): pass @base.resource("neutron", "subnet", order=next(_neutron_order), tenant_resource=True) class NeutronSubnet(NeutronMixin): pass @base.resource("neutron", "network", order=next(_neutron_order), tenant_resource=True) class NeutronNetwork(NeutronMixin): pass @base.resource("neutron", "floatingip", order=next(_neutron_order), tenant_resource=True) class NeutronFloatingIP(NeutronMixin): pass @base.resource("neutron", "quota", order=next(_neutron_order), admin_required=True, tenant_resource=True) class NeutronQuota(QuotaMixin, NeutronMixin): def delete(self): self._manager().delete_quota(self.tenant_uuid) # CINDER _cinder_order = get_order(400) @base.resource("cinder", "backups", order=next(_cinder_order), tenant_resource=True) class CinderVolumeBackup(base.ResourceManager): pass @base.resource("cinder", "volume_snapshots", order=next(_cinder_order), tenant_resource=True) class CinderVolumeSnapshot(base.ResourceManager): pass @base.resource("cinder", "transfers", order=next(_cinder_order), tenant_resource=True) class CinderVolumeTransfer(base.ResourceManager): pass @base.resource("cinder", "volumes", order=next(_cinder_order), tenant_resource=True) class CinderVolume(base.ResourceManager): pass @base.resource("cinder", "quotas", order=next(_cinder_order), admin_required=True, tenant_resource=True) class CinderQuotas(QuotaMixin, base.ResourceManager): pass # MANILA _manila_order = get_order(450) @base.resource("manila", "shares", order=next(_manila_order), tenant_resource=True) class ManilaShare(base.ResourceManager): pass @base.resource("manila", "share_networks", order=next(_manila_order), tenant_resource=True) class ManilaShareNetwork(base.ResourceManager): pass @base.resource("manila", "security_services", order=next(_manila_order), tenant_resource=True) class ManilaSecurityService(base.ResourceManager): pass # GLANCE @base.resource("glance", "images", order=500, tenant_resource=True) class GlanceImage(base.ResourceManager): def list(self): return self._manager().list(owner=self.tenant_uuid) # SAHARA _sahara_order = get_order(600) @base.resource("sahara", "job_executions", order=next(_sahara_order), tenant_resource=True) class SaharaJobExecution(SynchronizedDeletion, base.ResourceManager): pass @base.resource("sahara", "jobs", order=next(_sahara_order), tenant_resource=True) class SaharaJob(SynchronizedDeletion, base.ResourceManager): pass @base.resource("sahara", "job_binary_internals", order=next(_sahara_order), tenant_resource=True) class SaharaJobBinaryInternals(SynchronizedDeletion, base.ResourceManager): pass @base.resource("sahara", "job_binaries", order=next(_sahara_order), tenant_resource=True) class SaharaJobBinary(SynchronizedDeletion, base.ResourceManager): pass @base.resource("sahara", "data_sources", order=next(_sahara_order), tenant_resource=True) class SaharaDataSource(SynchronizedDeletion, base.ResourceManager): pass @base.resource("sahara", "clusters", order=next(_sahara_order), tenant_resource=True) class SaharaCluster(base.ResourceManager): # Need special treatment for Sahara Cluster because of the way the # exceptions are described in: # https://github.com/openstack/python-saharaclient/blob/master/ # saharaclient/api/base.py#L145 def is_deleted(self): try: self._manager().get(self.id()) return False except saharaclient_base.APIException as e: return e.error_code == 404 @base.resource("sahara", "cluster_templates", order=next(_sahara_order), tenant_resource=True) class SaharaClusterTemplate(SynchronizedDeletion, base.ResourceManager): pass @base.resource("sahara", "node_group_templates", order=next(_sahara_order), tenant_resource=True) class SaharaNodeGroup(SynchronizedDeletion, base.ResourceManager): pass # CEILOMETER @base.resource("ceilometer", "alarms", order=700, tenant_resource=True) class CeilometerAlarms(SynchronizedDeletion, base.ResourceManager): def id(self): return self.raw_resource.alarm_id def list(self): query = [{ "field": "project_id", "op": "eq", "value": self.tenant_uuid }] return self._manager().list(q=query) # ZAQAR @base.resource("zaqar", "queues", order=800) class ZaqarQueues(SynchronizedDeletion, base.ResourceManager): def list(self): return self.user.zaqar().queues() # DESIGNATE _designate_order = get_order(900) @base.resource("designate", "domains", order=next(_designate_order)) class Designate(SynchronizedDeletion, base.ResourceManager): pass @base.resource("designate", "servers", order=next(_designate_order), admin_required=True, perform_for_admin_only=True) class DesignateServer(SynchronizedDeletion, base.ResourceManager): pass # SWIFT _swift_order = get_order(1000) class SwiftMixin(SynchronizedDeletion, base.ResourceManager): def _manager(self): client = self._admin_required and self.admin or self.user return getattr(client, self._service)() def id(self): return self.raw_resource def delete(self): delete_method = getattr(self._manager(), "delete_%s" % self._resource) # NOTE(weiwu): *self.raw_resource is required because for deleting # container we are passing only container name, to delete object we # should pass as first argument container and second is object name. delete_method(*self.raw_resource) @base.resource("swift", "object", order=next(_swift_order), tenant_resource=True) class SwiftObject(SwiftMixin): def list(self): object_list = [] containers = self._manager().get_account(full_listing=True)[1] for con in containers: objects = self._manager().get_container(con["name"], full_listing=True)[1] for obj in objects: raw_resource = [con["name"], obj["name"]] object_list.append(raw_resource) return object_list @base.resource("swift", "container", order=next(_swift_order), tenant_resource=True) class SwiftContainer(SwiftMixin): def list(self): containers = self._manager().get_account(full_listing=True)[1] return [[con["name"]] for con in containers] # MISTRAL @base.resource("mistral", "workbooks", order=1100, tenant_resource=True) class MistralWorkbooks(SynchronizedDeletion, base.ResourceManager): def delete(self): self._manager().delete(self.raw_resource.name) # MURANO _murano_order = get_order(1200) @base.resource("murano", "environments", tenant_resource=True, order=next(_murano_order)) class MuranoEnvironments(base.ResourceManager): pass @base.resource("murano", "packages", tenant_resource=True, order=next(_murano_order)) class MuranoPackages(base.ResourceManager): def list(self): return filter(lambda x: x.name != "Core library", super(MuranoPackages, self).list()) # IRONIC _ironic_order = get_order(1300) @base.resource("ironic", "node", admin_required=True, order=next(_ironic_order), perform_for_admin_only=True) class IronicNodes(base.ResourceManager): def id(self): return self.raw_resource.uuid # FUEL @base.resource("fuel", "environment", order=1400, admin_required=True, perform_for_admin_only=True) class FuelEnvironment(base.ResourceManager): """Fuel environment. That is the only resource that can be deleted by fuelclient explicitly. """ def id(self): return self.raw_resource["id"] def is_deleted(self): return not self._manager().get(self.id()) def list(self): return [env for env in self._manager().list() if env["name"].startswith( scenario.OpenStackScenario.RESOURCE_NAME_PREFIX)] # KEYSTONE _keystone_order = get_order(9000) class KeystoneMixin(SynchronizedDeletion): def _manager(self): return keystone_wrapper.wrap(getattr(self.admin, self._service)()) def delete(self): delete_method = getattr(self._manager(), "delete_%s" % self._resource) delete_method(self.id()) def list(self): # TODO(boris-42): We should use such stuff in all list commands. resources = self._resource + "s" list_method = getattr(self._manager(), "list_%s" % resources) return filter(kutils.is_temporary, list_method()) @base.resource("keystone", "user", order=next(_keystone_order), admin_required=True, perform_for_admin_only=True) class KeystoneUser(KeystoneMixin, base.ResourceManager): pass @base.resource("keystone", "project", order=next(_keystone_order), admin_required=True, perform_for_admin_only=True) class KeystoneProject(KeystoneMixin, base.ResourceManager): pass @base.resource("keystone", "service", order=next(_keystone_order), admin_required=True, perform_for_admin_only=True) class KeystoneService(KeystoneMixin, base.ResourceManager): pass @base.resource("keystone", "role", order=next(_keystone_order), admin_required=True, perform_for_admin_only=True) class KeystoneRole(KeystoneMixin, base.ResourceManager): pass @base.resource("keystone", "ec2", tenant_resource=True, order=next(_keystone_order)) class KeystoneEc2(SynchronizedDeletion, base.ResourceManager): def list(self): return self._manager().list(self.raw_resource)
aplanas/rally
rally/plugins/openstack/context/cleanup/resources.py
Python
apache-2.0
18,435
import os import sublime from sublime_plugin import WindowCommand, TextCommand from ..git_command import GitCommand from ...common import util COMMIT_HELP_TEXT_EXTRA = """ ## You may also reference or close a GitHub issue with this commit. To do so, ## type `#` followed by the `tab` key. You will be shown a list of issues ## related to the current repo. You may also type `owner/repo#` plus the `tab` ## key to reference an issue in a different GitHub repo. """ COMMIT_HELP_TEXT_ALT = """ ## To make a commit, type your commit message and close the window. To cancel ## the commit, delete the commit message and close the window. To sign off on ## the commit, press {key}-S. """.format(key=util.super_key) + COMMIT_HELP_TEXT_EXTRA COMMIT_HELP_TEXT = """ ## To make a commit, type your commit message and press {key}-ENTER. To cancel ## the commit, close the window. To sign off on the commit, press {key}-S. """.format(key=util.super_key) + COMMIT_HELP_TEXT_EXTRA COMMIT_SIGN_TEXT = """ Signed-off-by: {name} <{email}> """ COMMIT_TITLE = "COMMIT: {}" class GsCommitCommand(WindowCommand, GitCommand): """ Display a transient window to capture the user's desired commit message. If the user is amending the previous commit, pre-populate the commit message area with the previous commit message. """ def run(self, **kwargs): sublime.set_timeout_async(lambda: self.run_async(**kwargs), 0) def run_async(self, repo_path=None, include_unstaged=False, amend=False): repo_path = repo_path or self.repo_path view = self.window.new_file() view.settings().set("git_savvy.get_long_text_view", True) view.settings().set("git_savvy.commit_view", True) view.settings().set("git_savvy.commit_view.include_unstaged", include_unstaged) view.settings().set("git_savvy.commit_view.amend", amend) view.settings().set("git_savvy.repo_path", repo_path) savvy_settings = sublime.load_settings("GitSavvy.sublime-settings") if savvy_settings.get("use_syntax_for_commit_editmsg"): syntax_file = util.file.get_syntax_for_file("COMMIT_EDITMSG") view.set_syntax_file(syntax_file) else: view.set_syntax_file("Packages/GitSavvy/syntax/make_commit.tmLanguage") title = COMMIT_TITLE.format(os.path.basename(repo_path)) view.set_name(title) if not savvy_settings.get("prompt_on_abort_commit"): view.set_scratch(True) view.run_command("gs_commit_initialize_view") class GsCommitInitializeViewCommand(TextCommand, GitCommand): """ Fill the view with the commit view help message, and optionally the previous commit message if amending. """ def run(self, edit): merge_msg_path = os.path.join(self.repo_path, ".git", "MERGE_MSG") savvy_settings = sublime.load_settings("GitSavvy.sublime-settings") help_text = (COMMIT_HELP_TEXT_ALT if savvy_settings.get("commit_on_close") else COMMIT_HELP_TEXT) self.view.settings().set("git_savvy.commit_view.help_text", help_text) option_amend = self.view.settings().get("git_savvy.commit_view.amend") if option_amend: last_commit_message = self.git("log", "-1", "--pretty=%B") initial_text = last_commit_message + help_text elif os.path.exists(merge_msg_path): with open(merge_msg_path, "r") as f: initial_text = f.read() + help_text else: initial_text = help_text commit_help_extra_file = savvy_settings.get("commit_help_extra_file") or ".commit_help" commit_help_extra_path = os.path.join(self.repo_path, commit_help_extra_file) if os.path.exists(commit_help_extra_path): with open(commit_help_extra_path, "r", encoding="utf-8") as f: initial_text += f.read() if savvy_settings.get("show_commit_diff"): if option_amend: initial_text += self.git("diff", "--no-color", "HEAD^") else: initial_text += self.git("diff", "--no-color", "--cached") self.view.run_command("gs_replace_view_text", { "text": initial_text, "nuke_cursors": True }) class GsCommitViewDoCommitCommand(TextCommand, GitCommand): """ Take the text of the current view (minus the help message text) and make a commit using the text for the commit message. """ def run(self, edit): sublime.set_timeout_async(self.run_async, 0) def run_async(self): view_text = self.view.substr(sublime.Region(0, self.view.size())) help_text = self.view.settings().get("git_savvy.commit_view.help_text") commit_message = view_text.split(help_text)[0] include_unstaged = self.view.settings().get("git_savvy.commit_view.include_unstaged") show_panel_overrides = \ sublime.load_settings("GitSavvy.sublime-settings").get("show_panel_for") self.git( "commit", "-q" if "commit" not in show_panel_overrides else None, "-a" if include_unstaged else None, "--amend" if self.view.settings().get("git_savvy.commit_view.amend") else None, "-F", "-", stdin=commit_message ) self.view.window().focus_view(self.view) self.view.set_scratch(True) # ignore dirty on actual commit self.view.window().run_command("close_file") class GsCommitViewSignCommand(TextCommand, GitCommand): """ Sign off on the commit with full name and email. """ def run(self, edit): view_text = self.view.substr(sublime.Region(0, self.view.size())) help_text = self.view.settings().get("git_savvy.commit_view.help_text") view_text_list = view_text.split(help_text) config_name = self.git("config", "user.name").strip() config_email = self.git("config", "user.email").strip() sign_text = COMMIT_SIGN_TEXT.format(name=config_name, email=config_email) view_text_list[0] += sign_text self.view.run_command("gs_replace_view_text", { "text": help_text.join(view_text_list), "nuke_cursors": True }) class GsCommitViewCloseCommand(TextCommand, GitCommand): """ Perform commit action on commit view close if `commit_on_close` setting is enabled. """ def run(self, edit): savvy_settings = sublime.load_settings("GitSavvy.sublime-settings") if savvy_settings.get("commit_on_close"): view_text = self.view.substr(sublime.Region(0, self.view.size())) help_text = self.view.settings().get("git_savvy.commit_view.help_text") message_txt = (view_text.split(help_text)[0] if help_text in view_text else "") message_txt = message_txt.strip() if message_txt: self.view.run_command("gs_commit_view_do_commit")
jmanuel1/GitSavvy
core/commands/commit.py
Python
mit
7,089
#!/usr/bin/env python3 # -*- coding : utf-8 -*- def fact1(n): # equals to n * n-1 * n-2 * .....* 3 * 2 * 1 if n == 1: return 1 return n * fact1(n - 1) # input int could be small , because of avoiding stack overflow. # tail-recursive func , to avoid overflowing def fact2(n): return fact2_iter(n,1) def fact2_iter(num,product): if num == 1 : return product return fact2_iter(num - 1 , num * product) # however , most interpreters donnot optimize for tail-recursive func , so useless.
kmahyyg/learn_py3
usage/recursive_func.py
Python
agpl-3.0
532
# -*- coding: utf-8 -*- from util_graph import * if __name__ == '__main__': get_shortest_path('./data/graph/graph.dat', './data/graph/CC.csv')
lifei96/Medium-crawler-with-data-analyzer
User_Crawler/get_shortest_path.py
Python
mit
150
"""add item system lookup tables Revision ID: 274d3d938628 Revises: 9b1f868a7343 Create Date: 2017-07-26 21:28:41.772392 Copyright (c) 2016-2017 Tony Lechner and contributors testrattingcapitals.com 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. testrattingcapitals.com 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 testrattingcapitals.com. If not, see <http://www.gnu.org/licenses/>. """ from alembic import op import csv import sqlalchemy as sa from testrattingcapitals.db import Context from testrattingcapitals.schema import EveItem, EveSolarSystem # revision identifiers, used by Alembic. revision = '274d3d938628' down_revision = '9b1f868a7343' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('eve_item', sa.Column('id', sa.Integer(), nullable=True), sa.Column('name', sa.Text(), nullable=True), sa.PrimaryKeyConstraint('id') ) op.create_table('eve_system', sa.Column('id', sa.Integer(), nullable=True), sa.Column('constellation_id', sa.Integer(), nullable=True), sa.Column('region_id', sa.Integer(), nullable=True), sa.Column('name', sa.String(length=50), nullable=True), sa.PrimaryKeyConstraint('id') ) # ### end Alembic commands ### _upgrade_import_eve_items() _upgrade_import_eve_solar_systems() def _upgrade_import_eve_items(): with open('./migrations/data/inventory_type_dump_20170727_0211.csv', 'r', newline='') as file_handler: with Context() as db_context: reader = csv.reader(file_handler) through_header = False for row in reader: if not through_header: # skip the header through_header = True continue db_context.session.add(EveItem(id=int(row[0]), name=row[2])) db_context.session.commit() def _upgrade_import_eve_solar_systems(): with open('./migrations/data/solar_system_dump_20170727_0211.csv', 'r', newline='') as file_handler: with Context() as db_context: reader = csv.reader(file_handler) through_header = False for row in reader: if not through_header: # skip the header through_header = True continue db_context.session.add(EveSolarSystem( id=int(row[2]), constellation_id=int(row[1]), region_id=int(row[0]), name=row[3]) ) db_context.session.commit() def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('eve_system') op.drop_table('eve_item') # ### end Alembic commands ###
tonymke/testrattingcapitals.com
server/migrations/versions/274d3d938628_add_item_system_lookup_tables.py
Python
agpl-3.0
3,264
""" .. _ex-time-freq-global-field-power: =========================================================== Explore event-related dynamics for specific frequency bands =========================================================== The objective is to show you how to explore spectrally localized effects. For this purpose we adapt the method described in [1]_ and use it on the somato dataset. The idea is to track the band-limited temporal evolution of spatial patterns by using the :term:`Global Field Power(GFP) <GFP>`. We first bandpass filter the signals and then apply a Hilbert transform. To reveal oscillatory activity the evoked response is then subtracted from every single trial. Finally, we rectify the signals prior to averaging across trials by taking the magniude of the Hilbert. Then the :term:`GFP` is computed as described in [2]_, using the sum of the squares but without normalization by the rank. Baselining is subsequently applied to make the :term:`GFPs <GFP>` comparable between frequencies. The procedure is then repeated for each frequency band of interest and all :term:`GFPs <GFP>` are visualized. To estimate uncertainty, non-parametric confidence intervals are computed as described in [3]_ across channels. The advantage of this method over summarizing the Space x Time x Frequency output of a Morlet Wavelet in frequency bands is relative speed and, more importantly, the clear-cut comparability of the spectral decomposition (the same type of filter is used across all bands). We will use this dataset: :ref:`somato-dataset` References ---------- .. [1] Hari R. and Salmelin R. Human cortical oscillations: a neuromagnetic view through the skull (1997). Trends in Neuroscience 20 (1), pp. 44-49. .. [2] Engemann D. and Gramfort A. (2015) Automated model selection in covariance estimation and spatial whitening of MEG and EEG signals, vol. 108, 328-342, NeuroImage. .. [3] Efron B. and Hastie T. Computer Age Statistical Inference (2016). Cambrdige University Press, Chapter 11.2. """ # noqa: E501 # Authors: Denis A. Engemann <[email protected]> # Stefan Appelhoff <[email protected]> # # License: BSD (3-clause) import os.path as op import numpy as np import matplotlib.pyplot as plt import mne from mne.datasets import somato from mne.baseline import rescale from mne.stats import bootstrap_confidence_interval ############################################################################### # Set parameters data_path = somato.data_path() subject = '01' task = 'somato' raw_fname = op.join(data_path, 'sub-{}'.format(subject), 'meg', 'sub-{}_task-{}_meg.fif'.format(subject, task)) # let's explore some frequency bands iter_freqs = [ ('Theta', 4, 7), ('Alpha', 8, 12), ('Beta', 13, 25), ('Gamma', 30, 45) ] ############################################################################### # We create average power time courses for each frequency band # set epoching parameters event_id, tmin, tmax = 1, -1., 3. baseline = None # get the header to extract events raw = mne.io.read_raw_fif(raw_fname) events = mne.find_events(raw, stim_channel='STI 014') frequency_map = list() for band, fmin, fmax in iter_freqs: # (re)load the data to save memory raw = mne.io.read_raw_fif(raw_fname, preload=True) raw.pick_types(meg='grad', eog=True) # we just look at gradiometers # bandpass filter raw.filter(fmin, fmax, n_jobs=1, # use more jobs to speed up. l_trans_bandwidth=1, # make sure filter params are the same h_trans_bandwidth=1) # in each band and skip "auto" option. # epoch epochs = mne.Epochs(raw, events, event_id, tmin, tmax, baseline=baseline, reject=dict(grad=4000e-13, eog=350e-6), preload=True) # remove evoked response epochs.subtract_evoked() # get analytic signal (envelope) epochs.apply_hilbert(envelope=True) frequency_map.append(((band, fmin, fmax), epochs.average())) del epochs del raw ############################################################################### # Now we can compute the Global Field Power # We can track the emergence of spatial patterns compared to baseline # for each frequency band, with a bootstrapped confidence interval. # # We see dominant responses in the Alpha and Beta bands. # Helper function for plotting spread def stat_fun(x): """Return sum of squares.""" return np.sum(x ** 2, axis=0) # Plot fig, axes = plt.subplots(4, 1, figsize=(10, 7), sharex=True, sharey=True) colors = plt.get_cmap('winter_r')(np.linspace(0, 1, 4)) for ((freq_name, fmin, fmax), average), color, ax in zip( frequency_map, colors, axes.ravel()[::-1]): times = average.times * 1e3 gfp = np.sum(average.data ** 2, axis=0) gfp = mne.baseline.rescale(gfp, times, baseline=(None, 0)) ax.plot(times, gfp, label=freq_name, color=color, linewidth=2.5) ax.axhline(0, linestyle='--', color='grey', linewidth=2) ci_low, ci_up = bootstrap_confidence_interval(average.data, random_state=0, stat_fun=stat_fun) ci_low = rescale(ci_low, average.times, baseline=(None, 0)) ci_up = rescale(ci_up, average.times, baseline=(None, 0)) ax.fill_between(times, gfp + ci_up, gfp - ci_low, color=color, alpha=0.3) ax.grid(True) ax.set_ylabel('GFP') ax.annotate('%s (%d-%dHz)' % (freq_name, fmin, fmax), xy=(0.95, 0.8), horizontalalignment='right', xycoords='axes fraction') ax.set_xlim(-1000, 3000) axes.ravel()[-1].set_xlabel('Time [ms]')
mne-tools/mne-tools.github.io
0.20/_downloads/2a0dcf3becdbea26da3b5a186ec2924a/plot_time_frequency_global_field_power.py
Python
bsd-3-clause
5,686
# -*- coding: utf-8 -*- from nbx.utils.format import moneyfmt, timeago def dateformat_filter(date, format='%d/%m/%Y'): if date: return date.strftime(format) return '' def timeago_filter(date): if date: return timeago(date) return '' def moneyfmt_filter(value, places=2, curr='', sep='.', dp=',', pos='', neg='-', trailneg=''): return moneyfmt(value, places, curr, sep, dp, pos, neg, trailneg) def cuitfmt_filter(value): return value[:2] + '-' + value[2:11] + '-' + value[-1]
coyotevz/nbx
nbx/jinjafilters.py
Python
gpl-3.0
540
#!/usr/bin/env python3 import asyncio import multiprocessing import functools import vulners from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor vulners_api = vulners.Vulners(api_key="YOUR_API_KEY_HERE") loop = asyncio.get_event_loop() # pool = ProcessPoolExecutor(max_workers=multiprocessing.cpu_count()) pool = ThreadPoolExecutor(max_workers=multiprocessing.cpu_count()) async def get_collection(): print('Get collections') # using default executor return await loop.run_in_executor(None, vulners_api.collections) async def search(query, **kwargs): # run using own executor print('Run search `%s`.' % query) ret = await loop.run_in_executor(pool, functools.partial(vulners_api.search, query, **kwargs)) print('Searching `%s` done.' % query) return ret async def main(): collection_names = await get_collection() queries = ["type:%s" % collection for collection in collection_names[:20]] futures = [asyncio.ensure_future(search(query, limit=10)) for query in queries] results = await asyncio.wait(futures) print(results) loop.run_until_complete(main()) loop.close()
vulnersCom/api
samples/asyncio_example.py
Python
gpl-3.0
1,150
if hasattr(context, 'portal_type') and context.portal_type == 'FormSaveData2ContentEntry': return context.getValue('infective-larvae-1000-l3-request-limit-5-shipments-year') else: return None
uwosh/uwosh.filariasis
uwosh/filariasis/skins/uwosh.filariasis/getDIInfectiveLarvae.py
Python
gpl-2.0
196
# Copyright (c) 2014 Ignacio Rodriguez <[email protected]> # 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 os import sys import json import tempfile from gettext import gettext as _ from gi.repository import Gdk from gi.repository import GLib from gi.repository import GObject from gi.repository import Gtk from sugar3 import env from sugar3 import profile from sugar3.datastore import datastore from sugar3.graphics.alert import NotifyAlert from sugar3.graphics.icon import Icon from sugar3.graphics.menuitem import MenuItem from sugar3.graphics.palette import Palette from sugar3.graphics.palettemenu import PaletteMenuBox from sugar3.graphics.palettemenu import PaletteMenuItem from jarabe.journal import journalwindow from jarabe.journal import model from jarabe.journal.journalactivity import get_journal from jarabe.journal.misc import _get_icon_for_mime from jarabe.journal.volumestoolbar import ExtensionButton from jarabe.webservice import account from jarabe.webservice import accountsmanager GOOGLE_API = os.path.join(env.get_profile_path(), 'extensions', 'webservice') sys.path.append(GOOGLE_API) ICONS_PATH = os.path.join(env.get_profile_path(), 'extensions', 'webservice', 'sugargdrive', 'icons') theme = Gtk.IconTheme.get_default() theme.append_search_path(ICONS_PATH) ACCOUNT_DESCRIPTION = _('Upload to Google Drive') ACCOUNT_NAME = _('Sugar Google Drive') ACCOUNT_ICON = 'sugargdrive' USER_FILES = os.path.join(env.get_profile_path(), 'gdrive_files') class FilesModel(Gtk.ListStore): def __init__(self, account, display_alert, load_files, journal_button, listview): Gtk.ListStore.__init__(self, str, bool, str, object, str, str, str, int, object, object, object, bool, str, str, str, str) self._account = account self._display_alert = display_alert self._load_files = load_files self._journal_button = journal_button self._listview = listview def do_drag_data_get(self, path, selection): data = self.get_iter(path) mime_type = self.get_value(data, 13) fileid = self.get_value(data, 14) title = self.get_value(data, 15) data = self._account.download_file(fileid, self._display_alert) fd, file_path = tempfile.mkstemp(dir="/tmp/") os.close(fd) if data[0]: f = open(file_path, 'w') f.write(data[0]) f.close() jobject = datastore.create() jobject.metadata['title'] = title jobject.metadata['icon-color'] = profile.get_color().to_string() jobject.metadata['mime_type'] = mime_type if data[1]: jobject.metadata['activity'] = data[1] if data[0]: jobject.file_path = file_path datastore.write(jobject) self._load_files() self._journal_button.set_active(True) self._listview.refresh() class ExtensionPalette(Palette): def __init__(self): label = GLib.markup_escape_text(ACCOUNT_NAME) account_icon = Icon(icon_name=ACCOUNT_ICON, xo_color=profile.get_color(), icon_size=Gtk.IconSize.MENU) Palette.__init__(self, primary_text=label, icon=account_icon) self.menu_box = PaletteMenuBox() self.menu_item = PaletteMenuItem(_('Update'), 'view-refresh') self.menu_box.append_item(self.menu_item) self.set_content(self.menu_box) self.menu_box.show_all() def set_item_cb(self, callback): self.menu_item.connect('activate', callback) class SharedJournalEntry(): def get_share_menu(self, get_uid_list): raise NotImplementedError def set_metadata(self, metadata): raise NotImplementedError class Account(account.Account): def __init__(self): self.upload = accountsmanager.get_service('sugargdrive') self._shared_journal_entry = None self._journal = None self._model = None self._alert = None self._listview = None self._volume_button = None def get_description(self): return ACCOUNT_DESCRIPTION def add_journal_button(self): if not self._journal: palette = ExtensionPalette() self._journal = get_journal() self._listview = self._journal.get_list_view() self._volumes_toolbar = self._journal.get_volumes_toolbar() self._volume_button = ExtensionButton(ACCOUNT_ICON, ICONS_PATH) self._volume_button.connect('toggled', self._journal_toggled) self._volume_button.connect('load-files', self._load_files) self._volume_button.connect('data-upload', self._upload_file) self._volumes_toolbar.add_extension_button(self._volume_button, ACCOUNT_NAME, palette) palette.set_item_cb(self.update_files) def get_token_state(self): return self.STATE_VALID def get_shared_journal_entry(self): if self._shared_journal_entry is None: self._shared_journal_entry = _SharedJournalEntry(self) return self._shared_journal_entry def _journal_toggled(self, widget): self._journal.get_window().set_cursor(None) option = widget.props.active if option: new_option = False else: new_option = True self._listview.use_options(new_option) def _load_files(self, *kwargs): if not self._model: journal_button = self._volumes_toolbar._volume_buttons[0] self._model = FilesModel(self.upload, self._display_alert_cb, self._load_files, journal_button, self._listview) self._model.clear() self._listview.tree_view.set_model(self._model) def internal_callback(): files = [] if os.path.exists(USER_FILES): f = open(USER_FILES, 'r') try: data = json.load(f) except: files = [] os.remove(USER_FILES) self._journal.get_window().set_cursor(None) f.close() data = [] isdict = False if isinstance(data, dict): isdict = True if isdict: data = data['items'] for userfile in data: txt = '<span weight="bold">%s</span>' % ( GLib.markup_escape_text(userfile['title'])) icon_name = _get_icon_for_mime(userfile['mimeType']) link = userfile['alternateLink'] itter = self._model.insert(-1, [ '', False, icon_name, profile.get_color(), txt, '', '', 50, profile.get_color(), profile.get_color(), profile.get_color(), True, link, userfile['mimeType'], userfile['id'], userfile['title']]) files.append(itter) if len(files) == 0 or not os.path.exists(USER_FILES): self._listview._show_message(_('No files in your ' 'account, please update your file list ' 'clicking in the toolbar menu option.'), icon_name=ACCOUNT_ICON) else: self._listview._clear_message() self._journal.get_window().set_cursor(None) self._listview._show_message(_('Loading files...'), icon_name=ACCOUNT_ICON) cursor = Gdk.Cursor.new(Gdk.CursorType.WATCH) self._journal.get_window().set_cursor(cursor) GObject.idle_add(internal_callback) def _upload_file(self, widget, metadata): account = self._shared_journal_entry._menu account.connect('transfer-state-changed', self._display_alert_cb) account.upload_file(None, metadata) def _display_alert_cb(self, widget, title, message): if self._alert is None: self._alert = NotifyAlert() self._alert.connect('response', self.__alert_response_cb) journalwindow.get_journal_window().add_alert(self._alert) self._alert.show() self._alert.props.title = title self._alert.props.msg = message def __alert_response_cb(self, alert, response_id): journalwindow.get_journal_window().remove_alert(alert) self._alert = None def update_files(self, widget): self._listview._show_message(_('Updating file list...'), icon_name=ACCOUNT_ICON) cursor = Gdk.Cursor.new(Gdk.CursorType.WATCH) self._journal.get_window().set_cursor(cursor) if not self._volume_button.props.active: self._volume_button.set_active(True) self._journal_toggled(self._volume_button) def internal_callback(): inst = self.upload.Upload() inst.update_files(self._display_alert_cb, self._load_files) self._listview._clear_message() self._journal.get_window().set_cursor(None) GObject.idle_add(internal_callback) class _SharedJournalEntry(SharedJournalEntry): __gsignals__ = { 'transfer-state-changed': (GObject.SignalFlags.RUN_FIRST, None, ([str, str])), } def __init__(self, account): self._account = account self._alert = None def get_share_menu(self, get_uid_list): self._menu = _ShareMenu(self._account, get_uid_list, True) self._connect_transfer_signals(self._menu) return self._menu def _connect_transfer_signals(self, transfer_widget): transfer_widget.connect('transfer-state-changed', self._account._display_alert_cb) class _ShareMenu(MenuItem): __gsignals__ = { 'transfer-state-changed': (GObject.SignalFlags.RUN_FIRST, None, ([str, str])), } def __init__(self, account, get_uid_list, is_active): MenuItem.__init__(self, ACCOUNT_DESCRIPTION) self._account = account self.set_image(Icon(icon_name=ACCOUNT_ICON, icon_size=Gtk.IconSize.MENU)) self.show() self._get_uid_list = get_uid_list self.connect('activate', self.upload_file) def _get_metadata(self): return model.get(self._get_uid_list()[0]) def _get_data(self, metadata=None): if not metadata: metadata = self._get_metadata() jobject = datastore.get(metadata['uid']) path = str(jobject.file_path) return path def _get_description(self, metadata=None): if not metadata: metadata = self._get_metadata() description = "" if 'description' in metadata: description = str(metadata['description']) return description def _get_title(self, metadata=None): if not metadata: metadata = self._get_metadata() title = _('Sugar upload') if 'title' in metadata: title = str(metadata['title']) return title def _get_activity(self, metadata=None): if not metadata: metadata = self._get_metadata() activity = '' if 'activity' in metadata: activity = str(metadata['activity']) return activity def upload_file(self, menu_item, metadata=None): path = self._get_data(metadata) title = self._get_title(metadata) description = self._get_description(metadata) activity = self._get_activity(metadata) self.emit('transfer-state-changed', _('Google drive'), _('Upload started')) upload = self._account.upload.Upload() upload.connect('upload-error', self.upload_error) upload.connect('upload-finished', self.upload_completed) upload.upload(path, title, description, activity) def upload_completed(self, widget, link): metadata = self._get_metadata() tags = '%s %s' % (metadata.get('tags', ''), link) ds_object = datastore.get(metadata['uid']) ds_object.metadata['tags'] = tags datastore.write(ds_object, update_mtime=False) self.emit('transfer-state-changed', _('Google drive'), _('Upload finished. Link saved in tags of entry.')) def upload_error(self, widget, msg): self.emit('transfer-state-changed', _('Google drive'), msg) def get_account(): return Account()
i5o/sugar-gdrive
extensions/webservice/sugargdrive/account.py
Python
gpl-3.0
13,236
import numpy as np import matplotlib.pyplot as plt import h5py from sklearn import svm file1='artificial_data.h5' ########### cargar datos de entrenamiento y datos de prueba########### hf = h5py.File(file1, "r") X1 = np.array(hf.get('X1')); Y1=np.array(hf.get('lab1')); X2 = np.array(hf.get('X2')); Y2=np.array(hf.get('lab2')); hf.close() #datos consolidados en una sola variable X=np.vstack((X1,X2)) #Y=np.append(np.zeros(Y1.size).astype(int),np.ones(Y2.size).astype(int)) Y=np.hstack((Y1,Y2)) XX=[] YY=[] labels = np.unique(Y) count=0 target_train=[] target_test =[] for ii in labels: N=np.sum(Y==ii) indx = np.random.permutation(N) train = int(0.8*N) indx=indx+count XX.append(X[indx[:train],:]) YY.append(X[indx[train:],:]) target_train.append(Y[indx[:train]]) target_test.append(Y[indx[train:]]) count=count+N ################################################################## # datos separados por conjuntos XX=np.vstack(XX) YY=np.vstack(YY) target_train=np.hstack(target_train) target_test=np.hstack(target_test) #generar clasificador clf = svm.SVC(gamma='scale', decision_function_shape='ovo') clf.fit(XX, target_train) #evaluar prediction=clf.predict(YY) result=np.sum(prediction==target_test)/float(target_test.size) print(result)
miltonsarria/dsp-python
examples_classify/ex1_select_classifier.py
Python
mit
1,319
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 encoding=utf-8 import os from django.conf.urls.defaults import * import rapidsms.contrib.scheduler.views as views urlpatterns = patterns('', url(r'^scheduler/$', views.index, name="scheduler"), url(r'^scheduler/(?P<pk>\d+)/$', views.edit), )
rapidsms/rapidsms-contrib-apps-dev
scheduler/urls.py
Python
bsd-3-clause
303
import fileinput import string import sys import os # BGP #fortran_compiler = '/bgsys/drivers/ppcfloor/comm/bin/mpixlf77_r' #fortran_opt_flags = '-O5 -qhot -qprefetch -qcache=auto -qalign=4k -qunroll=yes -qmaxmem=-1 -qalias=noaryovrlp:nopteovrlp -qnoextname -qnosmp -qreport=hotlist -c' #src_dir = '/gpfs/home/jhammond/spaghetty/python/archive/src/' #lst_dir = '/gpfs/home/jhammond/spaghetty/python/archive/lst/' # Goldstone old #fortran_compiler = 'ifort' #fortran_opt_flags = '-O3 -mtune=core2 -msse3 -align -c' #src_dir = '/home/jeff/code/spaghetty/trunk/python/archive/src/' fortran_compiler = 'ifort' fortran_link_flags = '-O1 -xT -mtune=core2 -align -pad' opt_set = [[],[],[],[],[],[],[],[],[]] opt_set[0] = '-O3 -xT -mtune=core2 -align -pad'# -unroll-aggressive -vec-guard-write -opt-streaming-stores always' opt_set[1] = '-O1' opt_set[2] = '-O2' opt_set[3] = '-O3 -align -pad' opt_set[4] = '-O3 -unroll-aggressive' opt_set[5] = '-O3 -parallel' opt_set[6] = '-O3 -xT -mtune=core2' opt_set[7] = '-O3 -vec-guard-write' opt_set[8] = '-O3 -opt-streaming-stores always' #opt_set_num = 3 #fortran_opt_flags = opt_set[opt_set_num] #src_dir = '/home/jeff/code/spaghetty/trunk/python/archive/src_optset'+str(opt_set_num)+'/' #lib_name = 'tce_sort_optset'+str(opt_set_num)+'.a' def perm(l): sz = len(l) if sz <= 1: return [l] return [p[:i]+[l[0]]+p[i:] for i in xrange(sz) for p in perm(l[1:])] #indices = ['1','2','3','4'] indices = ['4','3','2','1'] #all_permutations = perm(indices) #all_permutations = [indices] transpose_list = [indices] #transpose_list = perm(indices) #loop_list = [indices] loop_list = perm(indices) for opt_set_num in range(0,1): print 'opt_set_num = '+str(opt_set_num) fortran_opt_flags = opt_set[opt_set_num] src_dir = '/home/jeff/code/spaghetty/trunk/python/archive/src_optset'+str(opt_set_num)+'_unroll/' os.system('mkdir '+src_dir) exe_dir = '/home/jeff/code/spaghetty/trunk/python/archive/exe_optset'+str(opt_set_num)+'_unroll/' os.system('mkdir '+exe_dir) lib_name = 'tce_sort_optset'+str(opt_set_num)+'_unroll.a' for transpose_order in transpose_list: A = transpose_order[0] B = transpose_order[1] C = transpose_order[2] D = transpose_order[3] for loop_order in loop_list: a = loop_order[0] b = loop_order[1] c = loop_order[2] d = loop_order[3] subroutine_name = 'transpose_'+A+B+C+D+'_loop_'+a+b+c+d source_name = subroutine_name+'.F' #print source_name source_file = open(source_name,'w') source_file.write(' subroutine '+subroutine_name+'(unsorted,sorted,\n') source_file.write(' & dim1,dim2,dim3,dim4,factor)\n') source_file.write(' implicit none\n') source_file.write(' integer dim1,dim2,dim3,dim4\n') source_file.write(' integer old_offset,new_offset\n') source_file.write(' integer j1,j2,j3,j4\n') source_file.write(' double precision sorted(dim1*dim2*dim3*dim4)\n') source_file.write(' double precision unsorted(dim1*dim2*dim3*dim4)\n') source_file.write(' double precision factor\n') #source_file.write('cdir$ ivdep\n') stra = 1 strb = 1 strc = 1 strd = 1 str1 = 0 str2 = 0 str3 = 0 str4 = 0 strA = 0 strB = 0 strC = 0 strD = 0 source_file.write(' do j'+a+' = 1,dim'+a+','+str(stra)+'\n') source_file.write(' do j'+b+' = 1,dim'+b+','+str(strb)+'\n') source_file.write(' do j'+c+' = 1,dim'+c+','+str(strc)+'\n') source_file.write(' do j'+d+' = 1,dim'+d+','+str(strd)+'\n') #source_file.write(' old_offset = '+str(str4)+'+j4+dim4*('+str(str3)+'+j3-1+dim3*('+str(str2)+'+j2-1+dim2*('+str(str1)+'+j1-1)))\n') #source_file.write(' new_offset = '+str(strD)+'+j'+D+'+dim'+D+'*('+str(strC)+'+j'+C+'-1+dim'+C+'*('+str(strB)+'+j'+B+'-1+dim'+B+'*('+str(strA)+'+j'+A+'-1)))\n') #source_file.write(' sorted(new_offset) = unsorted(old_offset) * factor\n') source_file.write(' sorted('+str(str4)+'+j4+dim4*('+str(str3)+'+j3-1+dim3*('+str(str2)+'+j2-1+dim2*('+str(str1)+'+j1-1)))) = \n') source_file.write(' & unsorted('+str(strD)+'+j'+D+'+dim'+D+'*('+str(strC)+'+j'+C+'-1+dim'+C+'*('+str(strB)+'+j'+B+'-1+dim'+B+'*('+str(strA)+'+j'+A+'-1))))\n') source_file.write(' enddo\n') source_file.write(' enddo\n') source_file.write(' enddo\n') source_file.write(' enddo\n') source_file.write(' return\n') source_file.write(' end\n') source_file.close() print fortran_compiler+' '+fortran_opt_flags+' -c '+source_name os.system(fortran_compiler+' '+fortran_opt_flags+' -c '+source_name) os.system('ar -r '+lib_name+' '+subroutine_name+'.o') os.system('rm '+subroutine_name+'.o') os.system('mv '+subroutine_name+'.F '+src_dir) #os.system('mv '+subroutine_name+'.lst '+lst_dir)
jeffhammond/spaghetty
branches/spaghetty3/python/archive/generate_source_new_unrolling.py
Python
bsd-2-clause
5,442
def percDown(self,i): while (i * 2) <= self.currentSize: mc = self.minChild(i) if self.heapList[i] > self.heapList[mc]: tmp = self.heapList[i] self.heapList[i] = self.heapList[mc] self.heapList[mc] = tmp i = mc def minChild(self,i): if i * 2 + 1 > self.currentSize: return i * 2 else: if self.heapList[i*2] < self.heapList[i*2+1]: return i * 2 else: return i * 2 + 1
robin1885/algorithms-exercises-using-python
source-code-from-author-book/Listings-for-Second-Edition/listing_6_20.py
Python
mit
488
#!/usr/bin/env python # # A library that provides a Python interface to the Telegram Bot API # Copyright (C) 2015-2017 # Leandro Toledo de Souza <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser 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 Lesser Public License for more details. # # You should have received a copy of the GNU Lesser Public License # along with this program. If not, see [http://www.gnu.org/licenses/]. __version__ = '6.1.0'
thonkify/thonkify
src/lib/telegram/version.py
Python
mit
832
# # 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. """The volume type access extension.""" from oslo_utils import uuidutils import six import webob from jacket.api.storage import extensions from jacket.api.storage.openstack import wsgi from jacket.api.storage import xmlutil from jacket.storage import exception from jacket.storage.i18n import _ from jacket.storage.volume import volume_types soft_authorize = extensions.soft_extension_authorizer('volume', 'volume_type_access') authorize = extensions.extension_authorizer('volume', 'volume_type_access') def make_volume_type(elem): elem.set('{%s}is_public' % Volume_type_access.namespace, '%s:is_public' % Volume_type_access.alias) def make_volume_type_access(elem): elem.set('volume_type_id') elem.set('project_id') class VolumeTypeTemplate(xmlutil.TemplateBuilder): def construct(self): root = xmlutil.TemplateElement('volume_type', selector='volume_type') make_volume_type(root) alias = Volume_type_access.alias namespace = Volume_type_access.namespace return xmlutil.SlaveTemplate(root, 1, nsmap={alias: namespace}) class VolumeTypesTemplate(xmlutil.TemplateBuilder): def construct(self): root = xmlutil.TemplateElement('volume_types') elem = xmlutil.SubTemplateElement( root, 'volume_type', selector='volume_types') make_volume_type(elem) alias = Volume_type_access.alias namespace = Volume_type_access.namespace return xmlutil.SlaveTemplate(root, 1, nsmap={alias: namespace}) class VolumeTypeAccessTemplate(xmlutil.TemplateBuilder): def construct(self): root = xmlutil.TemplateElement('volume_type_access') elem = xmlutil.SubTemplateElement(root, 'access', selector='volume_type_access') make_volume_type_access(elem) return xmlutil.MasterTemplate(root, 1) def _marshall_volume_type_access(vol_type): rval = [] for project_id in vol_type['projects']: rval.append({'volume_type_id': vol_type['id'], 'project_id': project_id}) return {'volume_type_access': rval} class VolumeTypeAccessController(object): """The volume type access API controller for the OpenStack API.""" def __init__(self): super(VolumeTypeAccessController, self).__init__() @wsgi.serializers(xml=VolumeTypeAccessTemplate) def index(self, req, type_id): context = req.environ['storage.context'] authorize(context) try: vol_type = volume_types.get_volume_type( context, type_id, expected_fields=['projects']) except exception.VolumeTypeNotFound as error: raise webob.exc.HTTPNotFound(explanation=error.msg) if vol_type['is_public']: expl = _("Access list not available for public volume types.") raise webob.exc.HTTPNotFound(explanation=expl) return _marshall_volume_type_access(vol_type) class VolumeTypeActionController(wsgi.Controller): """The volume type access API controller for the OpenStack API.""" def _check_body(self, body, action_name): self.assert_valid_body(body, action_name) access = body[action_name] project = access.get('project') if not uuidutils.is_uuid_like(project): msg = _("Bad project format: " "project is not in proper format (%s)") % project raise webob.exc.HTTPBadRequest(explanation=msg) def _extend_vol_type(self, vol_type_rval, vol_type_ref): if vol_type_ref: key = "%s:is_public" % (Volume_type_access.alias) vol_type_rval[key] = vol_type_ref.get('is_public', True) @wsgi.extends def show(self, req, resp_obj, id): context = req.environ['storage.context'] if soft_authorize(context): # Attach our slave template to the response object resp_obj.attach(xml=VolumeTypeTemplate()) vol_type = req.cached_resource_by_id(id, name='types') self._extend_vol_type(resp_obj.obj['volume_type'], vol_type) @wsgi.extends def index(self, req, resp_obj): context = req.environ['storage.context'] if soft_authorize(context): # Attach our slave template to the response object resp_obj.attach(xml=VolumeTypesTemplate()) for vol_type_rval in list(resp_obj.obj['volume_types']): type_id = vol_type_rval['id'] vol_type = req.cached_resource_by_id(type_id, name='types') self._extend_vol_type(vol_type_rval, vol_type) @wsgi.extends def detail(self, req, resp_obj): context = req.environ['storage.context'] if soft_authorize(context): # Attach our slave template to the response object resp_obj.attach(xml=VolumeTypesTemplate()) for vol_type_rval in list(resp_obj.obj['volume_types']): type_id = vol_type_rval['id'] vol_type = req.cached_resource_by_id(type_id, name='types') self._extend_vol_type(vol_type_rval, vol_type) @wsgi.extends(action='create') def create(self, req, body, resp_obj): context = req.environ['storage.context'] if soft_authorize(context): # Attach our slave template to the response object resp_obj.attach(xml=VolumeTypeTemplate()) type_id = resp_obj.obj['volume_type']['id'] vol_type = req.cached_resource_by_id(type_id, name='types') self._extend_vol_type(resp_obj.obj['volume_type'], vol_type) @wsgi.action('addProjectAccess') def _addProjectAccess(self, req, id, body): context = req.environ['storage.context'] authorize(context, action="addProjectAccess") self._check_body(body, 'addProjectAccess') project = body['addProjectAccess']['project'] try: volume_types.add_volume_type_access(context, id, project) except exception.VolumeTypeAccessExists as err: raise webob.exc.HTTPConflict(explanation=six.text_type(err)) except exception.VolumeTypeNotFound as err: raise webob.exc.HTTPNotFound(explanation=six.text_type(err)) return webob.Response(status_int=202) @wsgi.action('removeProjectAccess') def _removeProjectAccess(self, req, id, body): context = req.environ['storage.context'] authorize(context, action="removeProjectAccess") self._check_body(body, 'removeProjectAccess') project = body['removeProjectAccess']['project'] try: volume_types.remove_volume_type_access(context, id, project) except (exception.VolumeTypeNotFound, exception.VolumeTypeAccessNotFound) as err: raise webob.exc.HTTPNotFound(explanation=six.text_type(err)) return webob.Response(status_int=202) class Volume_type_access(extensions.ExtensionDescriptor): """Volume type access support.""" name = "VolumeTypeAccess" alias = "os-volume-type-access" namespace = ("http://docs.openstack.org/volume/" "ext/os-volume-type-access/api/v1") updated = "2014-06-26T00:00:00Z" def get_resources(self): resources = [] res = extensions.ResourceExtension( Volume_type_access.alias, VolumeTypeAccessController(), parent=dict(member_name='type', collection_name='types')) resources.append(res) return resources def get_controller_extensions(self): controller = VolumeTypeActionController() extension = extensions.ControllerExtension(self, 'types', controller) return [extension]
HybridF5/jacket
jacket/api/storage/contrib/volume_type_access.py
Python
apache-2.0
8,349
# encoding: utf-8 # module _dbm # from /usr/lib/python3.4/lib-dynload/_dbm.cpython-34m-x86_64-linux-gnu.so # by generator 1.135 # no doc # no imports # Variables with simple values library = 'Berkeley DB' # functions def open(*args, **kwargs): # real signature unknown """ Return a database object. filename The filename to open. flags How to open the file. "r" for reading, "w" for writing, etc. mode If creating a new file, the mode bits for the new file (e.g. os.O_RDWR). """ pass # classes from .OSError import OSError class error(OSError): # no doc def __init__(self, *args, **kwargs): # real signature unknown pass __weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """list of weak references to the object (if defined)""" # variables with complex values __loader__ = None # (!) real value is '' __spec__ = None # (!) real value is ''
ProfessorX/Config
.PyCharm30/system/python_stubs/-1247971765/_dbm.py
Python
gpl-2.0
998
# Copyright 2018 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. # ============================================================================== """Classes for different algorithms of reduction and broadcasting.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import enum import six from tensorflow.python.client import device_lib from tensorflow.python.distribute import cross_device_utils from tensorflow.python.distribute import device_util from tensorflow.python.distribute import reduce_util from tensorflow.python.distribute import values as value_lib from tensorflow.python.eager import context from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import resource_variable_ops from tensorflow.python.platform import tf_logging as logging from tensorflow.python.util.tf_export import tf_export from tensorflow.tools.docs import doc_controls def check_destinations(destinations): """Checks whether `destinations` is not empty. Args: destinations: a `DistributedValues`, variable, or string object. Returns: Boolean which is True if `destinations` is not empty. """ # Calling bool() on a ResourceVariable is not allowed. if isinstance(destinations, resource_variable_ops.ResourceVariable): return bool(destinations.device) return bool(destinations) def validate_destinations(destinations): if not isinstance(destinations, (value_lib.DistributedValues, resource_variable_ops.ResourceVariable, value_lib.AggregatingVariable, six.string_types, value_lib.TPUMirroredVariable, # LogicalDeviceSpec is only used internally, e.g. as a # broadcast destination, never supplied by a user. value_lib.LogicalDeviceSpec)): raise ValueError("destinations must be one of a `DistributedValues` object," " a tf.Variable object, or a device string.") if not check_destinations(destinations): raise ValueError("destinations can not be empty") def reduce_non_distributed_value(reduce_op, device_map, value, destinations): """Reduce a non-DistributedValue `value` to `destinations`.""" if isinstance(value, value_lib.DistributedValues): raise ValueError("You are passing a `DistributedValue` to " "`reduce_non_distributed_value`, which is not allowed.") # If the same value is present on all replicas then the PerReplica value will # be a single value. We also handle the case when `value` is a single value # and equal to 0. if value == 0: return 0 # If there is only a single value and the reduce op is MEAN, # that value should be on all destinations. if reduce_op == reduce_util.ReduceOp.MEAN: return value validate_destinations(destinations) # We do not support a reduce op of SUM if the value is the same across # all replicas. We call this as part of assign functions for MirroredVariables # and summing up identical values across replicas is not clearly defined. if device_map.num_replicas_in_graph != 1: raise ValueError("A non-DistributedValues value %s cannot be reduced with " "the given reduce op %s." % (value, reduce_op)) return simple_broadcast(value, destinations) def _make_tensor_into_per_replica(input_tensor): """Converts a single tensor into a PerReplica object.""" if isinstance(input_tensor, (tuple, list)): raise ValueError("Cannot convert `input_tensor` to a `PerReplica` object, " "got %r but expected a object that is not a tuple or list." % (input_tensor,)) if isinstance(input_tensor, value_lib.PerReplica): return input_tensor try: device = input_tensor.device except AttributeError: raise ValueError("Cannot convert `input_tensor` to a `PerReplica` object " "because it doesn't have device set.") device_map = value_lib.SingleDeviceMap(device) return value_lib.PerReplica(device_map, (input_tensor,)) def _normalize_value_destination_pairs(value_destination_pairs): """Converts each tensor into a PerReplica object in the input list.""" result = [] value_destination_pairs = list(value_destination_pairs) if not isinstance(value_destination_pairs, (list, tuple)): raise ValueError("`value_destination_pairs` should be a list or tuple") for pair in value_destination_pairs: if not isinstance(pair, tuple): raise ValueError( "Each element of `value_destination_pairs` should be a tuple.") if len(pair) != 2: raise ValueError("Each element of `value_destination_pairs` should be a " "tuple of size 2.") per_replica = _make_tensor_into_per_replica(pair[0]) result.append((per_replica, pair[1])) return result def _validate_value_destination_pairs(value_destination_pairs): # TODO(yuefengz): raise exceptions instead of returning False. # pylint: disable=g-missing-docstring if not value_destination_pairs: return False if not isinstance(value_destination_pairs, (list, tuple)): return False if not all(isinstance(pair, tuple) for pair in value_destination_pairs): return False if not all(isinstance(v[0], value_lib.PerReplica) for v in value_destination_pairs): return False return True # TODO(yuefengz): consider calling this function in the caller of # CrossDeviceOps. def get_devices_from(destinations): if isinstance(destinations, value_lib.DistributedValues): return destinations.devices elif isinstance(destinations, value_lib.LogicalDeviceSpec): return destinations.device_map.logical_to_actual_devices( destinations.logical_device) elif isinstance(destinations, six.string_types): return (device_util.resolve(destinations),) return (destinations.device,) def get_device_map_from(destinations): if isinstance(destinations, (value_lib.DistributedValues, value_lib.LogicalDeviceSpec)): return destinations.device_map, destinations.logical_device if isinstance(destinations, six.string_types): device = device_util.resolve(destinations) else: device = destinations.device return value_lib.SingleDeviceMap(device), 0 def _devices_match(left, right): return set(get_devices_from(left)) == set(get_devices_from(right)) def _all_devices_match(value_destination_pairs): if not all(_devices_match(v, d) for v, d in value_destination_pairs): return False if not all(_devices_match(v, value_destination_pairs[0][0]) for v, _ in value_destination_pairs[1:]): return False return True def simple_broadcast(value, destinations, always_mirrored=False): """Broadcast `value` to `destinations` using simple copies.""" device_map, logical_device = get_device_map_from(destinations) devices = device_map.logical_to_actual_devices(logical_device) if len(devices) == 1 and not always_mirrored: return cross_device_utils.copy_tensor_or_indexed_slices_to_device( value, devices[0]) else: value_updates = [] for d in devices: value_updates.append( cross_device_utils.copy_tensor_or_indexed_slices_to_device( value, d)) return value_lib.Mirrored(device_map, value_updates, logical_device) def _simple_reduce(per_replica_value, reduce_to_device, accumulation_fn, reduce_op): # pylint: disable=g-missing-docstring all_values = per_replica_value.values if not all_values: raise ValueError("`per_replica_value` must be non-empty") count = len(all_values) with ops.device(reduce_to_device): with context.device_policy(context.DEVICE_PLACEMENT_SILENT): reduced = cross_device_utils.aggregate_tensors_or_indexed_slices( all_values, accumulation_fn) if reduce_op == reduce_util.ReduceOp.MEAN: reduced = cross_device_utils.divide_by_n_tensors_or_indexed_slices( reduced, count) elif reduce_op != reduce_util.ReduceOp.SUM: raise ValueError("`reduce_op` must be Reduce.SUM or Reduce.MEAN.") return reduced @tf_export("distribute.CrossDeviceOps") class CrossDeviceOps(object): """Base class for cross-device reduction and broadcasting algorithms.""" def __init__(self): pass def reduce(self, reduce_op, per_replica_value, destinations): """Reduce `per_replica_value` to `destinations`. It runs the reduction operation defined by `reduce_op` and put the result on `destinations`. Args: reduce_op: Indicates how per_replica_value will be reduced. Accepted values are `tf.distribute.ReduceOp.SUM`, `tf.distribute.ReduceOp.MEAN`. per_replica_value: a PerReplica object or a tensor with device set. destinations: the reduction destinations. Returns: a Mirrored object. Raises: ValueError: if per_replica_value can't be converted to a PerReplica object. """ if not isinstance(per_replica_value, value_lib.PerReplica): per_replica_value = _make_tensor_into_per_replica(per_replica_value) validate_destinations(destinations) return self.reduce_implementation(reduce_op, per_replica_value, destinations) def batch_reduce(self, reduce_op, value_destination_pairs): """Reduce PerReplica objects in a batch. Reduce each first element in `value_destination_pairs` to each second element which indicates the destinations. Args: reduce_op: Indicates how per_replica_value will be reduced. Accepted values are `tf.distribute.ReduceOp.SUM`, `tf.distribute.ReduceOp.MEAN`. value_destination_pairs: a list or a tuple of tuples of PerReplica objects (or tensors with device set if there is one device) and destinations. Returns: a list of Mirrored objects. Raises: ValueError: if `value_destination_pairs` is not a list or a tuple of tuples of PerReplica objects and destinations """ # TODO(yuefengz): if destinations are different, split into several # `_batch_reduce` invocations. if not _validate_value_destination_pairs(value_destination_pairs): # If the first element of each pair is a tensor, we try to turn it into a # PerReplica object. value_destination_pairs = _normalize_value_destination_pairs( value_destination_pairs) for _, d in value_destination_pairs: validate_destinations(d) return self.batch_reduce_implementation(reduce_op, value_destination_pairs) def broadcast(self, tensor, destinations): """Broadcast the `tensor` to destinations. Args: tensor: the tensor to broadcast. destinations: the broadcast destinations. Returns: a Mirrored object. """ validate_destinations(destinations) return self.broadcast_implementation(tensor, destinations) @doc_controls.for_subclass_implementers def reduce_implementation(self, reduce_op, per_replica_value, destinations): """The implementation of reduce of `per_replica_value` to `destinations`. It runs the reduction operation defined by `reduce_op` and put the result on `destinations`. Args: reduce_op: Indicates how per_replica_value will be reduced. Accepted values are `tf.distribute.ReduceOp.SUM`, `tf.distribute.ReduceOp.MEAN`. per_replica_value: a PerReplica object or a tensor with device set. destinations: the reduction destinations. Returns: a Mirrored object. Raises: ValueError: if per_replica_value can't be converted to a PerReplica object. """ raise NotImplementedError( "_reduce method must be implemented in descendants.") @doc_controls.for_subclass_implementers def batch_reduce_implementation(self, reduce_op, value_destination_pairs): """Implementation of reduce PerReplica objects in a batch. Reduce each first element in `value_destination_pairs` to each second element which indicates the destinations. Args: reduce_op: Indicates how per_replica_value will be reduced. Accepted values are `tf.distribute.ReduceOp.SUM`, `tf.distribute.ReduceOp.MEAN`. value_destination_pairs: a list or a tuple of tuples of PerReplica objects (or tensors with device set if there is one device) and destinations. Returns: a list of Mirrored objects. Raises: ValueError: if `value_destination_pairs` is not a list or a tuple of tuples of PerReplica objects and destinations """ raise NotImplementedError( "_batch_reduce method must be implemented in descendants.") @doc_controls.for_subclass_implementers def broadcast_implementation(self, tensor, destinations): """Implementation of broadcast the `tensor` to destinations. Args: tensor: the tensor to broadcast. destinations: the broadcast destinations. Returns: a Mirrored object. """ return simple_broadcast(tensor, destinations, always_mirrored=True) @tf_export("distribute.ReductionToOneDevice") class ReductionToOneDevice(CrossDeviceOps): """Always do reduction to one device first and then do broadcasting. Batch reduction is done by reduction on each element one by one. """ def __init__(self, reduce_to_device=None, accumulation_fn=None): """Constructor. Args: reduce_to_device: the intermediate device to reduce to. If None, reduce to the first device in `destinations` of the reduce() method. accumulation_fn: a function that does accumulation. If None, then `tf.math.add_n` is used. """ self.reduce_to_device = reduce_to_device self.accumulation_fn = accumulation_fn or math_ops.add_n super(ReductionToOneDevice, self).__init__() def reduce_implementation(self, reduce_op, per_replica_value, destinations): if check_destinations(destinations): devices = get_devices_from(destinations) else: devices = get_devices_from(per_replica_value) reduce_to_device = self.reduce_to_device or devices[0] logging.log_first_n( logging.INFO, "Reduce to %s then broadcast to %r." % (reduce_to_device, devices), 10) reduced = _simple_reduce(per_replica_value, reduce_to_device, self.accumulation_fn, reduce_op) return self.broadcast(reduced, destinations) def batch_reduce_implementation(self, reduce_op, value_destination_pairs): return [ self.reduce_implementation(reduce_op, t, destinations=v) for t, v in value_destination_pairs ] def _group_value_by_device(per_replica_values): """Group values into sublists by their devices. This grouping is needed to call the all-reduce library because it expects a list of the following form: [[(grad0_gpu0, v0_gpu0), (grad1_gpu0, v1_gpu0), (grad2_gpu0, v2_gpu0) ...], [(grad0_gpu1, v0_gpu1), (grad1_gpu1, v1_gpu1), (grad2_gpu1, v2_gpu1) ...], [(grad0_gpu2, v0_gpu2), (grad1_gpu0, v1_gpu2), (grad2_gpu0, v2_gpu2) ...], ... ] Args: per_replica_values: a list of PerReplica obejcts. Returns: a list of lists, each sublist has components for its corresponding device of PerReplica objects, paired with a None. """ destinations = per_replica_values[0].devices grouped = [[] for _ in range(len(destinations))] for per_replica_value in per_replica_values: # pylint: disable=protected-access for i, v in enumerate(per_replica_value.values): assert per_replica_value.devices == destinations grouped[i].append((v, None)) return grouped def _ungroup_and_make_mirrored(grouped_reduced, destinations, reduce_op, num_between_graph_workers=1): """Ungroup results from all-reduce and make Mirrored objects. Each all-reduce result will be divided by the number of destinations before Mirrored objects are created if reduce_op is "mean". Args: grouped_reduced: a list of lists, each sublist has components for each device, paired with a None. It is the result from cross_device_utils.aggregate_gradients_using*. destinations: a value to colocate the result with. reduce_op: Indicates how values will be aggregated. Accepted values are `tf.distribute.ReduceOp.SUM`, `tf.distribute.ReduceOp.MEAN`. num_between_graph_workers: number of workers in the between-graph replication. Returns: a list of Mirrored objects. """ device_map, logical_device = get_device_map_from(destinations) num_replicas = device_map.num_replicas_in_graph * num_between_graph_workers index = [[] for _ in range(len(grouped_reduced[0]))] for per_replica_reduced in grouped_reduced: for i, (v, _) in enumerate(per_replica_reduced): if reduce_op == reduce_util.ReduceOp.MEAN: index[i].append(v / num_replicas) else: index[i].append(v) return [value_lib.Mirrored(device_map, v, logical_device) for v in index] class _ConcatAndSplitPacker(object): """Concatenate and split tensors for reduction.""" def __init__(self, num_packs=1): """Initialize the _ConcatAndSplitPacker object. Args: num_packs: specifies the number of split packs that will be formed. Raises: ValueError: if num_packs is not greater than 0. """ if num_packs <= 0: raise ValueError("num_packs must be greater than zero.") self.num_packs = num_packs def pack(self, grouped_grads_and_vars): """Pack tensors.""" self.grouped_grads_and_vars = grouped_grads_and_vars self.all_device_shapes = [] self.all_device_sizes = [] device_grad_packs = [] for device_grads_and_vars in grouped_grads_and_vars: with ops.colocate_with(device_grads_and_vars[0][0]): # Flatten all the grads. flat_grads = [ array_ops.reshape(g, [-1]) for g, _ in device_grads_and_vars ] # Remember the original shape of all the grads. device_shapes = [array_ops.shape(g) for g, _ in device_grads_and_vars] # Remember the original sizes of all the grads. device_sizes = [array_ops.size(g) for g, _ in device_grads_and_vars] # Concat all the flat grads into a big flat tensor. concat_grads = array_ops.concat(flat_grads, 0) # Split the big tensor into num_splits packs. In cases where the # total size is not divisible num_splits, the last pack gets # more elements. # TODO(zhengxq): it is also possible to optimize away all the concat # as well. num_splits = self.num_packs # The array_ops.size function will sometimes remove static shapes. So if # all gradient shapes are defined, we use another method to get the # total size. # TODO(yuefengz): move this logic to array_ops.size. if all(g.shape.is_fully_defined() for g, _ in device_grads_and_vars): total_grad_size = sum( [g.shape.num_elements() for g, _ in device_grads_and_vars]) else: total_grad_size = array_ops.size(concat_grads) split_size = total_grad_size // num_splits split_size_last = total_grad_size - split_size * (num_splits - 1) split_sizes = [split_size] * (num_splits - 1) + [split_size_last] grad_packs = array_ops.split(concat_grads, split_sizes) # Ready to aggregate the repacked gradients, with fake variables. # TODO(zhengxq): It is hacky to have to use fake variables. # We should remove the need for variables in # aggregate_gradients_using*. device_grad_packs.append(zip(grad_packs, [None] * num_splits)) self.all_device_shapes.append(device_shapes) self.all_device_sizes.append(device_sizes) return device_grad_packs def unpack(self, summed_device_grad_packs): """Reverse the pack.""" aggregated_device_grads = [] for (summed_device_grad_packs, device_grads_and_vars, device_shapes, device_sizes) in zip( summed_device_grad_packs, self.grouped_grads_and_vars, self.all_device_shapes, self.all_device_sizes): # pylint: enable=line-too-long # Reverse the packing operations in the previous steps. Form the # summed gradients back into their original shapes. with ops.colocate_with(summed_device_grad_packs[0][0]): # Form a list of the summed grad packs. device_grad_packs = [g for g, _ in summed_device_grad_packs] # Concat them back into a big flat tensor. device_grads_concat = array_ops.concat(device_grad_packs, 0) # Split the tensors back into their original sizes. grads_with_sizes = array_ops.split(device_grads_concat, device_sizes) # Reshape the tensors back into their original shapes. grads_with_shapes = [ array_ops.reshape(grad, shape) for shape, grad in zip(device_shapes, grads_with_sizes) ] # Form the list with the original list of variables. summed_device_grads = [ (g, v) for g, (_, v) in zip(grads_with_shapes, device_grads_and_vars) ] aggregated_device_grads.append(summed_device_grads) return aggregated_device_grads class _AggregateSmallTensorPacker(object): """Concatenate small gradient tensors together for reduction.""" def __init__(self, agg_small_grads_max_bytes=1048576, agg_small_grads_max_group=16): """Initialize the _AggregateSmallTensorPacker object. Args: agg_small_grads_max_bytes: largest tensor eligible for aggregation, in number of bytes. agg_small_grads_max_group: largest permitted aggregation of small tensors. Raises: ValueError: if `agg_small_grads_max_bytes` or `agg_small_grads_max_group` is not greater than 0. """ if agg_small_grads_max_bytes <= 0 or agg_small_grads_max_group <= 0: raise ValueError("agg_small_grads_max_bytes and agg_small_grads_max_group" " should both be greater than zero.") self.agg_small_grads_max_bytes = agg_small_grads_max_bytes self.agg_small_grads_max_group = agg_small_grads_max_group def pack(self, grouped_grads_and_vars): """Aggregate small tensors.""" if (self.agg_small_grads_max_bytes > 0 and self.agg_small_grads_max_group > 0): device_grads, self.packing = cross_device_utils.pack_small_tensors( grouped_grads_and_vars, max_bytes=self.agg_small_grads_max_bytes, max_group=self.agg_small_grads_max_group) return device_grads def unpack(self, summed_device_grad_packs): """Reverse the aggregation process.""" return cross_device_utils.unpack_small_tensors(summed_device_grad_packs, self.packing) def _pack_tensors(device_grads, num_packs=0, agg_small_grads_max_bytes=0, agg_small_grads_max_group=0): """Pack tensors if specified.""" if num_packs > 0: tensor_packer = _ConcatAndSplitPacker(num_packs) device_grad_packs = tensor_packer.pack(device_grads) elif agg_small_grads_max_bytes > 0 and agg_small_grads_max_group > 0: tensor_packer = _AggregateSmallTensorPacker(agg_small_grads_max_bytes, agg_small_grads_max_group) device_grad_packs = tensor_packer.pack(device_grads) else: tensor_packer = None device_grad_packs = device_grads return device_grad_packs, tensor_packer def _unpack_tensors(reduced, tensor_packer=None): """Unpack tensors if they are packed before all-reduce.""" if tensor_packer: return tensor_packer.unpack(reduced) return reduced class AllReduceCrossDeviceOps(CrossDeviceOps): """Reduction using all-reduce.""" def __init__(self, all_reduce_alg="nccl", num_packs=1, agg_small_grads_max_bytes=0, agg_small_grads_max_group=10): """All-reduce implementation of CrossDeviceOps. Before performing all-reduce, tensors will be repacked or aggregated for more efficient cross-device transportation: 1) If `num_packs` is non-zero, pack values into `num_packs` splits. 2) Otherwise, if `agg_small_grads_max_bytes` > 0 and `agg_small_grads_max_group` > 0, aggregate values smaller than `agg_small_grads_max_bytes` into groups with at most `agg_small_grads_max_group` values. 3) Otherwise, no repacking or grouping will happen. Args: all_reduce_alg: the all-reduce algorithm to use, currently only "nccl" or "hierarchical_copy" are supported. num_packs: see above. agg_small_grads_max_bytes: see above. agg_small_grads_max_group: see above. """ self._all_reduce_alg = all_reduce_alg self._num_packs = num_packs self._agg_small_grads_max_bytes = agg_small_grads_max_bytes self._agg_small_grads_max_group = agg_small_grads_max_group self._simple_cross_replica_ops = ReductionToOneDevice() super(AllReduceCrossDeviceOps, self).__init__() def reduce_implementation(self, reduce_op, per_replica_value, destinations): if _devices_match(per_replica_value, destinations): return self._batch_all_reduce(reduce_op, [per_replica_value])[0] else: return self._simple_cross_replica_ops.reduce(reduce_op, per_replica_value, destinations) def batch_reduce_implementation(self, reduce_op, value_destination_pairs): all_devices_match = _all_devices_match(value_destination_pairs) contains_indexed_slices = cross_device_utils.contains_indexed_slices( value_destination_pairs) if (all_devices_match and not context.executing_eagerly() and not contains_indexed_slices): return self._batch_all_reduce(reduce_op, [v[0] for v in value_destination_pairs]) else: if not all_devices_match: logging.log_first_n(logging.WARN, "Efficient batch_reduce is not supported if " "destinations are different.", 10) return [ self.reduce_implementation(reduce_op, t, destinations=v) for t, v in value_destination_pairs ] def _batch_all_reduce(self, reduce_op, per_replica_values): """All-reduce algorithm in a batch.""" dense_values, dense_indices, sparse_values, sparse_indices = ( cross_device_utils.split_by_sparsity(per_replica_values)) if dense_values: dense_results = self._do_batch_all_reduce(reduce_op, dense_values) else: dense_results = [] if sparse_values: sparse_results = self._do_batch_all_reduce_sparse(reduce_op, sparse_values) else: sparse_results = [] return cross_device_utils.stitch_values(((dense_results, dense_indices), (sparse_results, sparse_indices))) def _do_batch_all_reduce(self, reduce_op, dense_values): """Run batch all-reduces.""" logging.log_first_n( logging.INFO, "batch_all_reduce invoked for batches size = %d with " "algorithm = %s, num_packs = %d, agg_small_grads_max_bytes = %d and " "agg_small_grads_max_group = %d" % (len(dense_values), self._all_reduce_alg, self._num_packs, self._agg_small_grads_max_bytes, self._agg_small_grads_max_group), 10) destinations = dense_values[0].devices grouped = _group_value_by_device(dense_values) device_grad_packs, tensor_packer = _pack_tensors( grouped, self._num_packs, self._agg_small_grads_max_bytes, self._agg_small_grads_max_group) # The actual aggregation of the repacked gradients. Note that they are # sharded among different aggregation trees. So it is important to strike # the balance on num_splits. if self._all_reduce_alg == "nccl": # TODO(yuefengz): merge this into the all-reduce library. reduced = cross_device_utils.aggregate_gradients_using_nccl( device_grad_packs) else: # TODO(yuefengz): check that gpu ids in `destinations` are in ascending # order. reduced = ( cross_device_utils.aggregate_gradients_using_hierarchical_copy( destinations, device_grad_packs)) reduced = _unpack_tensors(reduced, tensor_packer) return _ungroup_and_make_mirrored(reduced, dense_values[0], reduce_op) def _do_batch_all_reduce_sparse(self, reduce_op, sparse_values): """Run batch all-reduce for sparse values.""" logging.log_first_n( logging.WARN, "Efficient allreduce is not supported for %d IndexedSlices" % len(sparse_values), 10) # Use `sparse_values` as destinations to do all-reduces. It is effectively # an allgather under the hood but not an efficient one. return self._simple_cross_replica_ops.batch_reduce( reduce_op, zip(sparse_values, sparse_values)) # For compatibility with code using the old name of `AllReduceCrossDeviceOps`. AllReduceCrossTowerOps = AllReduceCrossDeviceOps AllReduceSpecTuple = collections.namedtuple("AllReduceSpecTuple", "alg shards limit") @tf_export("distribute.NcclAllReduce") class NcclAllReduce(AllReduceCrossDeviceOps): """Reduction using NCCL all-reduce.""" def __init__(self, num_packs=1): """NCCL all-reduce implementation of CrossDeviceOps. Before performing all-reduce, tensors will be repacked or aggregated for more efficient cross-device transportation. Args: num_packs: values will be packed in this many splits. `num_packs` should be greater than 0. """ assert num_packs > 0, ( "NCLL all-reduce requires num_packs > 0, but {} is specified".format( num_packs)) super(NcclAllReduce, self).__init__( all_reduce_alg="nccl", num_packs=num_packs) @tf_export("distribute.HierarchicalCopyAllReduce") class HierarchicalCopyAllReduce(AllReduceCrossDeviceOps): """Reduction using hierarchical copy all-reduce. This is a good reduction for configurations like Nvidia DGX-1. """ def __init__(self, num_packs=1): """Hierarchical copy all-reduce implementation of CrossDeviceOps. Before performing all-reduce, tensors will be repacked or aggregated for more efficient cross-device transportation. Args: num_packs: values will be packed in this many splits. `num_packs` should be greater than 0. """ super(HierarchicalCopyAllReduce, self).__init__( all_reduce_alg="hierarchical_copy", num_packs=num_packs) class MultiWorkerAllReduce(AllReduceCrossDeviceOps): """All-reduce algorithms for distributed TensorFlow.""" def __init__(self, worker_devices, num_gpus_per_worker, all_reduce_spec=("pscpu/pscpu", 2, -1), num_packs=0, agg_small_grads_max_bytes=0, agg_small_grads_max_group=10): """Initialize the all-reduce algorithm. Args: worker_devices: a list of device strings for workers participating in all-reduce. num_gpus_per_worker: number of GPU devices per worker. all_reduce_spec: a tuple or a named tuple or a list of tuples specifying the all-reduce algorithm. 1. The first element of a tuple is the name of the all-reduce algorithm. Valid algorithm names are: "nccl", "nccl/xring", "nccl/rechd", "nccl/pscpu", "xring", "pscpu", "psgpu", "pscpu/pscpu". Algorithms with a "/" are hierarchical, so two all-reduces are executed, the first one aggregates tensors within a worker and the second aggregates across workers. 2. The second element of a tuple is the number of shards when doing all-reduce. Let's say its values is M, each tensor after packing will be split into M shards and then M parallel all-reduces would be performed before finally they are concatenated backed into a complete tensor. 3. The third element is the maximum size of tensors that will be applicable for the algorithm specified by the first element. For example, if all_reduce_spec=[("nccl", 2, 1024), ("pscpu/pscpu", 2, -1)], tensors with size not larger than 1024 bytes will be applied a 2-shard "nccl" all-reduce and other tensors will be applied a 2-shard "pscpu/pscpu" algorithm. The third elements should be in increasing order across tuples and end with -1 which indicates infinity. num_packs: see AllReduceCrossDeviceOps. agg_small_grads_max_bytes: see AllReduceCrossDeviceOps. agg_small_grads_max_group: see AllReduceCrossDeviceOps. """ self._worker_devices = worker_devices self._num_gpus_per_worker = num_gpus_per_worker super(MultiWorkerAllReduce, self).__init__( num_packs=num_packs, agg_small_grads_max_bytes=agg_small_grads_max_bytes, agg_small_grads_max_group=agg_small_grads_max_group) def validate_and_complete_spec(spec): """Validate and complete the all-reduce spec.""" # TODO(yuefengz): support namedtuple. if not isinstance(spec, tuple): raise ValueError( "A tuple is expected for all-reduce spec: %r" % all_reduce_spec) if not spec or len(spec) > 3: raise ValueError( "Too many elements in the all-reduce spec tuple: %r" % spec) if len(spec) == 1: return AllReduceSpecTuple(spec[0], 1, -1) elif len(spec) == 2: return AllReduceSpecTuple(spec[0], spec[1], -1) else: return AllReduceSpecTuple(*spec) self._all_reduce_spec = [] if isinstance(all_reduce_spec, six.string_types): self._all_reduce_spec.append(AllReduceSpecTuple(all_reduce_spec, 1, -1)) elif isinstance(all_reduce_spec, tuple): self._all_reduce_spec.append(validate_and_complete_spec(all_reduce_spec)) elif isinstance(all_reduce_spec, list): self._all_reduce_spec = [ validate_and_complete_spec(spec) for spec in all_reduce_spec ] def _batch_all_reduce(self, reduce_op, per_replica_values): """All-reduce algorithm in a batch.""" logging.log_first_n( logging.INFO, "distributed batch_all_reduce invoked for batches size = %d with " "allreduce_spec = %r, num_packs = %d, agg_small_grads_max_bytes = %d " "and agg_small_grads_max_group = %d" % (len(per_replica_values), self._all_reduce_spec, self._num_packs, self._agg_small_grads_max_bytes, self._agg_small_grads_max_group), 10) device_grads = _group_value_by_device(per_replica_values) # The all-reduce library requires fully defined shapes. # TODO(yuefengz): when tensor sharding is not needed, static shapes are not # required as well. for device_grad in device_grads: for grad, _ in device_grad: if not grad.shape.is_fully_defined(): raise ValueError("Shape is unknown for node %r" % grad) remaining_grads = device_grads aggregated_grads = [] for spec_tuple in self._all_reduce_spec: if spec_tuple.limit < 0: this_grads = remaining_grads remaining_grads = [] else: (this_grads, remaining_grads) = cross_device_utils.split_grads_by_size( spec_tuple.limit, remaining_grads) if this_grads: device_grad_packs, tensor_packer = _pack_tensors( this_grads, self._num_packs, self._agg_small_grads_max_bytes, self._agg_small_grads_max_group) range_agg_grads = cross_device_utils.sum_gradients_all_reduce( self._worker_devices, device_grad_packs, len(self._worker_devices), spec_tuple.alg, spec_tuple.shards, range(self._num_gpus_per_worker)) range_agg_grads = _unpack_tensors(range_agg_grads, tensor_packer) if not aggregated_grads: aggregated_grads = range_agg_grads else: assert len(aggregated_grads) == len(range_agg_grads) for i in range(len(aggregated_grads)): aggregated_grads[i] += range_agg_grads[i] assert not remaining_grads return _ungroup_and_make_mirrored(aggregated_grads, per_replica_values[0], reduce_op) @tf_export("distribute.experimental.CollectiveCommunication") class CollectiveCommunication(enum.Enum): """Communication choices for CollectiveOps. * `AUTO`: Default to runtime's automatic choices. * `RING`: TensorFlow's ring algorithms for all-reduce and all-gather. * `NCCL`: Use ncclAllReduce for all-reduce, and ring algorithms for all-gather. TODO(ayushd): add ncclAllGather implementation. """ AUTO = "AUTO" RING = "RING" NCCL = "NCCL" # TODO(yuefengz): support in-graph collective all-reduce. class CollectiveAllReduce(CrossDeviceOps): """All-reduce cross device ops using collective ops. In the between-graph replicated training, it will still do all-reduces across all workers and then put results on the right destinations. """ def __init__(self, num_workers=1, num_gpus_per_worker=0, all_reduce_merge_scope=32, collective_keys=None): """Initializes the object. Args: num_workers: number of workers in the between-graph replicated training. num_gpus_per_worker: number of GPUs per worker. all_reduce_merge_scope: size of groups into which to partition consecutive gradients grouped under a common 'allreduce' name scope. This is useful for some optimization of collective ops. collective_keys: an optional CollectiveKey object. """ self._num_workers = num_workers self._num_gpus_per_worker = num_gpus_per_worker self._all_reduce_merge_scope = all_reduce_merge_scope self._collective_keys = (collective_keys or cross_device_utils.CollectiveKeys()) super(CollectiveAllReduce, self).__init__() def reduce_implementation(self, reduce_op, per_replica_value, destinations): all_reduced = self._batch_all_reduce(reduce_op, [per_replica_value])[0] device_map, logical_device = get_device_map_from(destinations) if (all_reduced.device_map is device_map and all_reduced.logical_device == logical_device): return all_reduced devices = device_map.logical_to_actual_devices(logical_device) index = [] for d in devices: if d in all_reduced.devices: index.append(all_reduced.get(d)) else: # TODO(josh11b): Once we add support for model parallelism, get the # copy from the corresponding replica instead of the primary. with ops.control_dependencies(all_reduced.values), ops.device(d): index.append(array_ops.identity(all_reduced.primary)) return value_lib.Mirrored(device_map, index, logical_device) def batch_reduce_implementation(self, reduce_op, value_destination_pairs): all_devices_match = _all_devices_match(value_destination_pairs) if all_devices_match: return self._batch_all_reduce(reduce_op, [v[0] for v in value_destination_pairs]) else: if not all_devices_match: logging.log_first_n( logging.WARN, "Efficient batch_reduce is not supported if " "destinations are different.", 10) return [ self.reduce_implementation(reduce_op, t, destinations=v) for t, v in value_destination_pairs ] def _make_gradient_chunks(self, per_replica_values, all_reduce_merge_scope): """Make `per_replica_values` into chunks.""" grouped_by_device = _group_value_by_device(per_replica_values) grouped_by_var = list(zip(*grouped_by_device)) # grouped_by_var is grouped by variables and takes the following format: # [((grad0_gpu0, v0_gpu0), (grad0_gpu1, v0_gpu1), (grad0_gpu2, v0_gpu2) ..), # ((grad1_gpu0, v1_gpu0), (grad1_gpu1, v1_gpu1), (grad1_gpu0, v1_gpu2) ..), # ((grad2_gpu0, v2_gpu0), (grad2_gpu1, v2_gpu1), (grad2_gpu0, v2_gpu2) ..), # ... # ] chunked_gv = [ grouped_by_var[x:x + all_reduce_merge_scope] for x in range(0, len(grouped_by_var), all_reduce_merge_scope) ] return chunked_gv def _batch_all_reduce(self, reduce_op, per_replica_values): """All reduce algorithm in a batch.""" logging.log_first_n( logging.INFO, "Collective All-reduce invoked with batches size = %d, " "num_workers = %d" % (len(per_replica_values), self._num_workers), 10) dense_values, dense_indices, sparse_values, sparse_indices = ( cross_device_utils.split_by_sparsity(per_replica_values)) if dense_values: dense_results = self._do_batch_all_reduce_dense(reduce_op, dense_values) else: dense_results = [] if sparse_values: sparse_results = self._do_batch_all_reduce_sparse(reduce_op, sparse_values) else: sparse_results = [] return cross_device_utils.stitch_values(((dense_results, dense_indices), (sparse_results, sparse_indices))) def _do_batch_all_reduce_dense(self, reduce_op, per_replica_values): """All-reduce across all workers in a batch.""" logging.log_first_n( logging.INFO, "Collective All-reduce invoked with batches size = %d, " "num_workers = %d" % (len(per_replica_values), self._num_workers), 10) chunked_gv = self._make_gradient_chunks(per_replica_values, self._all_reduce_merge_scope) reduced_gv_list = [] for chunk in chunked_gv: with ops.name_scope("allreduce"): for grad_and_vars in chunk: # Gradients for the same variable but from different devices. scaled_grads = [g for g, _ in grad_and_vars] collective_reduced = cross_device_utils.build_collective_reduce( scaled_grads, self._num_workers, self._collective_keys, "Add", "Id") result = [] for (_, v), g in zip(grad_and_vars, collective_reduced): result.append([g, v]) reduced_gv_list.append(result) new_device_grads = [list(x) for x in zip(*reduced_gv_list)] return _ungroup_and_make_mirrored( new_device_grads, per_replica_values[0], reduce_op, num_between_graph_workers=self._num_workers) def _do_batch_all_reduce_sparse(self, reduce_op, per_replica_values): """All-reduce IndexedSlices across all workers in a batch.""" logging.log_first_n( logging.INFO, "Collective All-reduce for IndexedSlices invoked with " "batches size = %d, num_workers = %d" % (len(per_replica_values), self._num_workers), 10) chunked_gv = self._make_gradient_chunks(per_replica_values, self._all_reduce_merge_scope) reduced_gv_list = [] for chunk in chunked_gv: with ops.name_scope("allreduce"): for grad_and_vars in chunk: # Gradients for the same variable but from different devices. scaled_grads = [g for g, _ in grad_and_vars] values = [g.values for g in scaled_grads] indices = [g.indices for g in scaled_grads] assert len(values) == len(indices) # Build two separate allgathers, one for values, the other one for # indices. gathered_values = cross_device_utils.build_collective_gather( values, self._num_workers, self._collective_keys) gathered_indices = cross_device_utils.build_collective_gather( indices, self._num_workers, self._collective_keys) assert len(gathered_values) == len(gathered_indices) collective_reduced = [] for i in range(len(values)): reduced = ops.IndexedSlices( gathered_values[i], gathered_indices[i], dense_shape=scaled_grads[i].dense_shape) collective_reduced.append(reduced) result = [] for (_, v), g in zip(grad_and_vars, collective_reduced): result.append([g, v]) reduced_gv_list.append(result) new_device_grads = [list(x) for x in zip(*reduced_gv_list)] return _ungroup_and_make_mirrored( new_device_grads, per_replica_values[0], reduce_op, num_between_graph_workers=self._num_workers) _dgx1_links = [[1, 2, 3, 4], [0, 2, 3, 5], [0, 1, 3, 6], [0, 1, 2, 7], [0, 5, 6, 7], [1, 4, 6, 7], [2, 4, 5, 7], [3, 4, 5, 6]] def _has_dgx1_like_links(gpu_links): if not gpu_links: return False # TODO(yuefengz): figure out the right topology for hierarchical copy if # number of gpus are less than 8. if len(gpu_links) < 8: return False for i, (gpu_link, dgx1_link) in enumerate(zip(gpu_links, _dgx1_links)): if (set(gpu_link) != set(dgx1_link) and set(gpu_link) != set(dgx1_link + [i])): return False return True def _choose_all_reduce_algorithm(device_links): if _has_dgx1_like_links(device_links): return HierarchicalCopyAllReduce(num_packs=len(device_links)) else: return NcclAllReduce(num_packs=1) def choose_the_best(devices, session_config=None): """Find the best subclass of CrossDeviceOps given a session config. Args: devices: a list of devices passed to `tf.distribute.Strategy`. session_config: a `tf.ConfigProto` or `None`. If `None`, it will make decision based on all local devices. Returns: A subclass of `CrossDeviceOps`. """ requested_devices = set([device_util.canonicalize(d) for d in devices]) machine_devices = device_lib.list_local_devices(session_config=session_config) using_devices = [] for d in machine_devices: if device_util.canonicalize(d.name) in requested_devices: using_devices.append(d) else: logging.info( "Device is available but not used by distribute strategy: %s", d.name) if len(using_devices) != len(requested_devices): logging.warning("Not all devices in `tf.distribute.Strategy` are visible " "to TensorFlow.") return ReductionToOneDevice() if any(d.device_type.lower() != "gpu" for d in using_devices): logging.warning("Not all devices in `tf.distribute.Strategy` are visible " "to TensorFlow.") return ReductionToOneDevice() device_links = [[] for _ in range(len(using_devices))] for i, device in enumerate(using_devices): for link in device.locality.links.link: device_links[i].append(link.device_id) return _choose_all_reduce_algorithm(device_links)
kevin-coder/tensorflow-fork
tensorflow/python/distribute/cross_device_ops.py
Python
apache-2.0
47,651
"""! @package psmap_dialogs.py @brief Map feature objects and dialogs for ps.map Classes: - UnitConversion - TCValidator - PenStyleComboBox - CheckListCtrl - Instruction - InstructionObject - InitMap - MapFrame - PageSetup - Mapinfo - Text - Scalebar - RasterLegend - VectorLegend - Raster - Vector - VProperties - PsmapDialog - PageSetupDialog - MapDialog - MapFramePanel - RasterPanel - VectorPanel - RasterDialog - MainVectorDialog - VPropertiesDialog - LegendDialog - MapinfoDialog - ScalebarDialog - TextDialog (C) 2011 by Anna Kratochvilova, and the GRASS Development Team This program is free software under the GNU General Public License (>=v2). Read the file COPYING that comes with GRASS for details. @author Anna Kratochvilova <kratochanna gmail.com> (bachelor's project) @author Martin Landa <landa.martin gmail.com> (mentor) """ import os import sys import string from math import ceil, floor from copy import deepcopy from time import strftime, localtime import grass.script as grass if int(grass.version()['version'].split('.')[0]) > 6: sys.path.append(os.path.join(os.getenv('GISBASE'), 'etc', 'gui', 'wxpython', 'gui_modules')) else: sys.path.append(os.path.join(os.getenv('GISBASE'), 'etc', 'wxpython', 'gui_modules')) import globalvar import dbm_base from utils import CmdToTuple, GetCmdString from gselect import Select from gcmd import RunCommand, GError, GMessage, GWarning import wx import wx.lib.scrolledpanel as scrolled import wx.lib.filebrowsebutton as filebrowse from wx.lib.mixins.listctrl import CheckListCtrlMixin, ListCtrlAutoWidthMixin from wx.lib.expando import ExpandoTextCtrl, EVT_ETC_LAYOUT_NEEDED try: import wx.lib.agw.floatspin as fs except ImportError: fs = None grass.set_raise_on_error(True) PSMAP_COLORS = ['aqua', 'black', 'blue', 'brown', 'cyan', 'gray', 'grey', 'green', 'indigo', 'magenta','orange', 'purple', 'red', 'violet', 'white', 'yellow'] class UnitConversion: """! Class for converting units""" def __init__(self, parent = None): self.parent = parent if self.parent: ppi = wx.PaintDC(self.parent).GetPPI() else: ppi = (72, 72) self._unitsPage = { 'inch' : {'val': 1.0, 'tr' : _("inch")}, 'point' : {'val': 72.0, 'tr' : _("point")}, 'centimeter' : {'val': 2.54, 'tr' : _("centimeter")}, 'millimeter' : {'val': 25.4, 'tr' : _("millimeter")}} self._unitsMap = { 'meters' : {'val': 0.0254, 'tr' : _("meters")}, 'kilometers' : {'val': 2.54e-5, 'tr' : _("kilometers")}, 'feet' : {'val': 1./12, 'tr' : _("feet")}, 'miles' : {'val': 1./63360, 'tr' : _("miles")}, 'nautical miles': {'val': 1/72913.386, 'tr' : _("nautical miles")}} self._units = { 'pixel' : {'val': ppi[0], 'tr' : _("pixel")}, 'meter' : {'val': 0.0254, 'tr' : _("meter")}, 'nautmiles' : {'val': 1/72913.386, 'tr' :_("nautical miles")}, 'degrees' : {'val': 0.0254 , 'tr' : _("degree")} #like 1 meter, incorrect } self._units.update(self._unitsPage) self._units.update(self._unitsMap) def getPageUnitsNames(self): return sorted(self._unitsPage[unit]['tr'] for unit in self._unitsPage.keys()) def getMapUnitsNames(self): return sorted(self._unitsMap[unit]['tr'] for unit in self._unitsMap.keys()) def getAllUnits(self): return sorted(self._units.keys()) def findUnit(self, name): """!Returns unit by its tr. string""" for unit in self._units.keys(): if self._units[unit]['tr'] == name: return unit return None def findName(self, unit): """!Returns tr. string of a unit""" try: return self._units[unit]['tr'] except KeyError: return None def convert(self, value, fromUnit = None, toUnit = None): return float(value)/self._units[fromUnit]['val']*self._units[toUnit]['val'] class TCValidator(wx.PyValidator): """!validates input in textctrls, combobox, taken from wxpython demo""" def __init__(self, flag = None): wx.PyValidator.__init__(self) self.flag = flag self.Bind(wx.EVT_CHAR, self.OnChar) def Clone(self): return TCValidator(self.flag) def Validate(self, win): tc = self.GetWindow() val = tc.GetValue() if self.flag == 'DIGIT_ONLY': for x in val: if x not in string.digits: return False return True def OnChar(self, event): key = event.GetKeyCode() if key < wx.WXK_SPACE or key == wx.WXK_DELETE or key > 255: event.Skip() return if self.flag == 'DIGIT_ONLY' and chr(key) in string.digits + '.': event.Skip() return ## if self.flag == 'SCALE' and chr(key) in string.digits + ':': ## event.Skip() ## return if self.flag == 'ZERO_AND_ONE_ONLY' and chr(key) in '01': event.Skip() return if not wx.Validator_IsSilent(): wx.Bell() # Returning without calling even.Skip eats the event before it # gets to the text control return class PenStyleComboBox(wx.combo.OwnerDrawnComboBox): """!Combo for selecting line style, taken from wxpython demo""" # Overridden from OwnerDrawnComboBox, called to draw each # item in the list def OnDrawItem(self, dc, rect, item, flags): if item == wx.NOT_FOUND: # painting the control, but there is no valid item selected yet return r = wx.Rect(*rect) # make a copy r.Deflate(3, 5) penStyle = wx.SOLID if item == 1: penStyle = wx.LONG_DASH elif item == 2: penStyle = wx.DOT elif item == 3: penStyle = wx.DOT_DASH pen = wx.Pen(dc.GetTextForeground(), 3, penStyle) dc.SetPen(pen) # for painting the items in the popup dc.DrawText(self.GetString(item ), r.x + 3, (r.y + 0) + ((r.height/2) - dc.GetCharHeight() )/2 ) dc.DrawLine(r.x+5, r.y+((r.height/4)*3)+1, r.x+r.width - 5, r.y+((r.height/4)*3)+1 ) def OnDrawBackground(self, dc, rect, item, flags): """!Overridden from OwnerDrawnComboBox, called for drawing the background area of each item.""" # If the item is selected, or its item # iseven, or we are painting the # combo control itself, then use the default rendering. if (item & 1 == 0 or flags & (wx.combo.ODCB_PAINTING_CONTROL | wx.combo.ODCB_PAINTING_SELECTED)): wx.combo.OwnerDrawnComboBox.OnDrawBackground(self, dc, rect, item, flags) return # Otherwise, draw every other background with different colour. bgCol = wx.Colour(240,240,250) dc.SetBrush(wx.Brush(bgCol)) dc.SetPen(wx.Pen(bgCol)) dc.DrawRectangleRect(rect); def OnMeasureItem(self, item): """!Overridden from OwnerDrawnComboBox, should return the height needed to display an item in the popup, or -1 for default""" return 30 def OnMeasureItemWidth(self, item): """!Overridden from OwnerDrawnComboBox. Callback for item width, or -1 for default/undetermined""" return -1; # default - will be measured from text width class CheckListCtrl(wx.ListCtrl, CheckListCtrlMixin, ListCtrlAutoWidthMixin): """!List control for managing order and labels of vector maps in legend""" def __init__(self, parent): wx.ListCtrl.__init__(self, parent, id = wx.ID_ANY, style = wx.LC_REPORT|wx.LC_SINGLE_SEL|wx.BORDER_SUNKEN|wx.LC_VRULES|wx.LC_HRULES) CheckListCtrlMixin.__init__(self) ListCtrlAutoWidthMixin.__init__(self) class Instruction: """!Class which represents instruction file""" def __init__(self, parent, objectsToDraw): self.parent = parent self.objectsToDraw = objectsToDraw #here are kept objects like mapinfo, rasterlegend, etc. self.instruction = list() def __str__(self): """!Returns text for instruction file""" comment = "# timestamp: " + strftime("%Y-%m-%d %H:%M", localtime()) + '\n' env = grass.gisenv() comment += "# location: %s\n" % env['LOCATION_NAME'] comment += "# mapset: %s\n" % env['MAPSET'] comment += "# page orientation: %s\n" % self.FindInstructionByType('page')['Orientation'] border = '' if not self.FindInstructionByType('map'): border = 'border n\n' text = [str(each) for each in self.instruction] return comment + border + '\n'.join(text) + '\nend' def __getitem__(self, id): for each in self.instruction: if each.id == id: return each return None def __contains__(self, id): """!Test if instruction is included""" for each in self.instruction: if each.id == id: return True return False def __delitem__(self, id): """!Delete instruction""" for each in self.instruction: if each.id == id: if each.type == 'map': #must remove raster, vector layers too vektor = self.FindInstructionByType('vector', list = True) vProperties = self.FindInstructionByType('vProperties', list = True) raster = self.FindInstructionByType('raster', list = True) for item in vektor + vProperties + raster: if item in self.instruction: self.instruction.remove(item) self.instruction.remove(each) if id in self.objectsToDraw: self.objectsToDraw.remove(id) return def AddInstruction(self, instruction): """!Add instruction""" # add to instructions if instruction.type == 'map': self.instruction.insert(0, instruction) else: self.instruction.append(instruction) # add to drawable objects if instruction.type not in ('page', 'raster', 'vector', 'vProperties', 'initMap'): if instruction.type == 'map': self.objectsToDraw.insert(0, instruction.id) else: self.objectsToDraw.append(instruction.id) def FindInstructionByType(self, type, list = False): """!Find instruction(s) with the given type""" inst = [] for each in self.instruction: if each.type == type: inst.append(each) if len(inst) == 1 and not list: return inst[0] return inst def Read(self, filename): """!Reads instruction file and creates instruction objects""" self.filename = filename # open file try: file = open(filename, 'r') except IOError: GError(message = _("Unable to open file\n%s") % filename) return # first read file to get information about region and scaletype isRegionComment = False orientation = 'Portrait' for line in file: if '# g.region' in line: self.SetRegion(regionInstruction = line) isRegionComment = True break if '# page orientation' in line: orientation = line.split(':')[-1].strip() if not isRegionComment: self.SetRegion(regionInstruction = None) # then run ps.map -b to get information for maploc # compute scale and center map = self.FindInstructionByType('map') region = grass.region() map['center'] = (region['n'] + region['s']) / 2, (region['w'] + region['e']) / 2 mapRect = GetMapBounds(self.filename, portrait = (orientation == 'Portrait')) map['rect'] = mapRect proj = projInfo() toM = 1.0 if proj['units']: toM = float(proj['meters']) units = UnitConversion(self.parent) w = units.convert(value = mapRect.Get()[2], fromUnit = 'inch', toUnit = 'meter') / toM map['scale'] = w / abs((region['w'] - region['e'])) SetResolution(dpi = 300, width = map['rect'].width, height = map['rect'].height) # read file again, now with information about map bounds isBuffer = False buffer = [] instruction = None vectorMapNumber = 1 file.seek(0) for line in file: if not line.strip(): continue line = line.strip() if isBuffer: buffer.append(line) if 'end' in line: isBuffer = False kwargs = {} if instruction == 'scalebar': kwargs['scale'] = map['scale'] elif instruction == 'text': kwargs['mapInstruction'] = map elif instruction in ('vpoints', 'vlines', 'vareas'): kwargs['id'] = wx.NewId() kwargs['vectorMapNumber'] = vectorMapNumber vectorMapNumber += 1 elif instruction == 'paper': kwargs['Orientation'] = orientation ok = self.SendToRead(instruction, buffer, **kwargs) if not ok: return False buffer = [] continue elif line.startswith('paper'): instruction = 'paper' isBuffer = True buffer.append(line) elif line.startswith('border'): if line.split()[1].lower() in ('n', 'no', 'none'): ok = self.SendToRead('border', [line]) if not ok: return False elif line.split()[1].lower() in ('y', 'yes'): instruction = 'border' isBuffer = True buffer.append(line) elif line.startswith('scale '): ok = self.SendToRead('scale', line, isRegionComment = isRegionComment) if not ok: return False elif line.startswith('maploc'): ok = self.SendToRead(instruction = 'maploc', text = line) if not ok: return False elif line.startswith('raster'): ok = self.SendToRead(instruction = 'raster', text = line) if not ok: return False elif line.startswith('mapinfo'): instruction = 'mapinfo' isBuffer = True buffer.append(line) elif line.startswith('scalebar'): instruction = 'scalebar' isBuffer = True buffer.append(line) elif line.startswith('text'): instruction = 'text' isBuffer = True buffer.append(line) elif line.startswith('colortable'): if len(line.split()) == 2 and line.split()[1].lower() in ('n', 'no', 'none'): break instruction = 'colortable' isBuffer = True buffer.append(line) elif line.startswith('vlegend'): instruction = 'vlegend' isBuffer = True buffer.append(line) elif line.startswith('vpoints'): instruction = 'vpoints' isBuffer = True buffer.append(line) elif line.startswith('vlines'): instruction = 'vlines' isBuffer = True buffer.append(line) elif line.startswith('vareas'): instruction = 'vareas' isBuffer = True buffer.append(line) rasterLegend = self.FindInstructionByType('rasterLegend') raster = self.FindInstructionByType('raster') page = self.FindInstructionByType('page') vector = self.FindInstructionByType('vector') vectorLegend = self.FindInstructionByType('vectorLegend') vectorMaps = self.FindInstructionByType('vProperties', list = True) # check (in case of scaletype 0) if map is drawn also map['drawMap'] = False if map['scaleType'] == 0: mapForRegion = map['map'] if map['mapType'] == 'raster' and raster: if mapForRegion == raster['raster']: map['drawMap'] = True elif map['mapType'] == 'vector' and vector: for vmap in vector['list']: if mapForRegion == vmap[0]: map['drawMap'] = True # rasterLegend if rasterLegend: if rasterLegend['rasterDefault'] and raster: rasterLegend['raster'] = raster['raster'] if not rasterLegend['discrete']: rasterType = getRasterType(map = rasterLegend['raster']) if rasterType == 'CELL': rasterLegend['discrete'] = 'y' else: rasterLegend['discrete'] = 'n' #estimate size height = rasterLegend.EstimateHeight(raster = rasterLegend['raster'], discrete = rasterLegend['discrete'], fontsize = rasterLegend['fontsize'], cols = rasterLegend['cols'], height = rasterLegend['height']) width = rasterLegend.EstimateWidth(raster = rasterLegend['raster'], discrete = rasterLegend['discrete'], fontsize = rasterLegend['fontsize'], cols = rasterLegend['cols'] , width = rasterLegend['width'], paperInstr = page) rasterLegend['rect'] = wx.Rect2D(x = float(rasterLegend['where'][0]), y = float(rasterLegend['where'][1]), w = width, h = height) # vectors, vlegend if vector: for vmap in vectorMaps: for i, each in enumerate(vector['list']): if each[2] == vmap.id: vector['list'][i][4] = vmap['label'] vector['list'][i][3] = vmap['lpos'] if vectorLegend: size = vectorLegend.EstimateSize(vectorInstr = vector, fontsize = vectorLegend['fontsize'], width = vectorLegend['width'], cols = vectorLegend['cols']) vectorLegend['rect'] = wx.Rect2D(x = float(vectorLegend['where'][0]), y = float(vectorLegend['where'][1]), w = size[0], h = size[1]) page = self.FindInstructionByType('page') if not page: page = PageSetup(wx.NewId()) self.AddInstruction(page) else: page['Orientation'] = orientation # return True def SendToRead(self, instruction, text, **kwargs): psmapInstrDict = dict(paper = ['page'], maploc = ['map'], scale = ['map'], border = ['map'], raster = ['raster'], mapinfo = ['mapinfo'], scalebar = ['scalebar'], text = ['text'], vpoints = ['vector', 'vProperties'], vlines = ['vector', 'vProperties'], vareas = ['vector', 'vProperties'], colortable = ['rasterLegend'], vlegend = ['vectorLegend'] ) myInstrDict = dict(page = PageSetup, map = MapFrame, raster = Raster, mapinfo = Mapinfo, scalebar = Scalebar, text = Text, rasterLegend = RasterLegend, vectorLegend = VectorLegend, vector = Vector, vProperties = VProperties ) myInstruction = psmapInstrDict[instruction] for i in myInstruction: instr = self.FindInstructionByType(i) if i in ('text', 'vProperties') or not instr: id = wx.NewId() #!vProperties expect subtype if i == 'vProperties': id = kwargs['id'] newInstr = myInstrDict[i](id, subType = instruction[1:]) else: newInstr = myInstrDict[i](id) ok = newInstr.Read(instruction, text, **kwargs) if ok: self.AddInstruction(newInstr) else: return False else: ok = instr.Read(instruction, text, **kwargs) if not ok: return False return True def SetRegion(self, regionInstruction): """!Sets region from file comment or sets current region in case of no comment""" map = MapFrame(wx.NewId()) self.AddInstruction(map) if regionInstruction: cmd = CmdToTuple(regionInstruction.strip('# ').split()) # define scaleType if len(cmd[1]) <= 3: if 'rast' in cmd[1]: map['scaleType'] = 0 map['mapType'] = 'raster' map['map'] = cmd[1]['rast'] elif 'vect' in cmd[1]: map['scaleType'] = 0 map['mapType'] = 'vector' map['map'] = cmd[1]['vect'] elif 'region' in cmd[1]: map['scaleType'] = 1 map['region'] = cmd[1]['region'] else: map['scaleType'] = 2 else: map['scaleType'] = 2 grass.del_temp_region() region = grass.region() grass.use_temp_region() cmd = ['g.region', region] cmdString = GetCmdString(cmd).replace('g.region', '') GMessage(_("Instruction file will be loaded with following region: %s\n") % cmdString) try: RunCommand(cmd[0], **cmd[1]) except grass.ScriptError, e: GError(_("Region cannot be set\n%s") % e) return False class InstructionObject: """!Abtract class representing single instruction""" def __init__(self, id): self.id = id # default values self.defaultInstruction = dict() # current values self.instruction = self.defaultInstruction # converting units self.unitConv = UnitConversion() def __str__(self): """!Returns particular part of text instruction""" return '' def __getitem__(self, key): for each in self.instruction.keys(): if each == key: return self.instruction[key] return None def __setitem__(self, key, value): self.instruction[key] = value def GetInstruction(self): """!Get current values""" return self.instruction def SetInstruction(self, instruction): """!Set default values""" self.instruction = instruction def Read(self, instruction, text, **kwargs): """!Read instruction and save them""" pass class InitMap(InstructionObject): """!Class representing virtual map""" def __init__(self, id): InstructionObject.__init__(self, id = id) self.type = 'initMap' # default values self.defaultInstruction = dict(rect = None, scale = None) # current values self.instruction = dict(self.defaultInstruction) class MapFrame(InstructionObject): """!Class representing map (instructions maploc, scale, border)""" def __init__(self, id): InstructionObject.__init__(self, id = id) self.type = 'map' # default values self.defaultInstruction = dict(map = None, mapType = None, drawMap = True, region = None, rect = wx.Rect2D(), scaleType = 0, scale = None, center = None, resolution = 300, border = 'y', width = 1, color = '0:0:0') # current values self.instruction = dict(self.defaultInstruction) def __str__(self): instr = '' comment = '' #region settings region = grass.region() if self.instruction['scaleType'] == 0: #match map map = self.instruction['map'] if self.instruction['mapType'] == 'raster': comment = "# g.region rast=%s nsres=%s ewres=%s\n" % (map, region['nsres'], region['ewres']) else: comment = "# g.region vect=%s\n" % (map) elif self.instruction['scaleType'] == 1:# saved region region = self.instruction['region'] comment = "# g.region region=%s\n" % region elif self.instruction['scaleType'] in (2, 3): #current region, fixed scale comment = string.Template("# g.region n=$n s=$s e=$e w=$w rows=$rows cols=$cols \n").substitute(**region) instr += comment instr += '\n' # maploc maplocInstruction = "maploc %.3f %.3f" % (self.instruction['rect'].x, self.instruction['rect'].y) if self.instruction['scaleType'] != 3: maplocInstruction += " %.3f %.3f"% (self.instruction['rect'].width, self.instruction['rect'].height) instr += maplocInstruction instr += '\n' # scale if self.instruction['scaleType'] == 3: #fixed scale scaleInstruction = "scale 1:%.0f" % (1/self.instruction['scale']) instr += scaleInstruction instr += '\n' # border borderInstruction = '' if self.instruction['border'] == 'n': borderInstruction = "border n" else: borderInstruction = "border y\n" borderInstruction += string.Template(" width $width\n color $color\n").substitute(self.instruction) borderInstruction += " end" instr += borderInstruction instr += '\n' return instr def Read(self, instruction, text, **kwargs): """!Read instruction and save information""" if 'isRegionComment' in kwargs: isRegionComment = kwargs['isRegionComment'] instr = {} if instruction == 'border': for line in text: if line.startswith('end'): break try: if line.split()[1].lower() in ('n', 'no', 'none'): instr['border'] = 'n' break elif line.split()[1].lower() in ('y', 'yes'): instr['border'] = 'y' elif line.startswith('width'): instr['width'] = line.split()[1] elif line.startswith('color'): instr['color'] = line.split()[1] except IndexError: GError(_("Failed to read instruction %s") % instruction) return False elif instruction == 'scale': try: scaleText = text.strip('scale ').split(':')[1] # when scale instruction given and region comment also, then scaletype is fixed scale if not isRegionComment: instr['scaleType'] = 2 else: instr['scaleType'] = 3 scale = 1/float(scaleText) if abs(scale - self.instruction['scale']) > (0.01 * scale): GWarning(_("Scale has changed, old value: %(old)s\nnew value: %(new)s") % \ { 'old' : scale, 'new' : self.instruction['scale'] }) except (ValueError, IndexError): GError(_("Failed to read instruction %s.\nUse 1:25000 notation.") % instruction) return False elif instruction == 'maploc': maploc = text.strip('maploc ').split() if len(maploc) >= 2: if abs(self.instruction['rect'].Get()[0] - float(maploc[0])) > 0.5 or \ abs(self.instruction['rect'].Get()[1] - float(maploc[1])) > 0.5: GWarning(_("Map frame position changed, old value: %(old1)s %(old2)s\nnew value: %(new1)s %(new2)s") % \ { 'old1' : maploc[0], 'old2' : maploc[1], 'new1' : self.instruction['rect'].Get()[0], 'new2' : self.instruction['rect'].Get()[1] }) #instr['rect'] = wx.Rect2D(float(maploc[0]), float(maploc[1]), self.instruction['rect'][2], self.instruction['rect'][3]) if len(maploc) == 4: if abs(self.instruction['rect'].Get()[2] - float(maploc[2])) > 0.5 or \ abs(self.instruction['rect'].Get()[3] - float(maploc[3])) > 0.5: GWarning(_("Map frame size changed, old value: %(old1)s %(old2)s\nnew value: %(new1)s %(new2)s") % \ { 'old1' : maploc[2], 'old2' : maploc[3], 'new1' : self.instruction['rect'].Get()[2], 'new2' : self.instruction['rect'].Get()[3] }) #instr['rect'] = wx.Rect2D(*map(float, maploc)) self.instruction.update(instr) return True class PageSetup(InstructionObject): """!Class representing page instruction""" def __init__(self, id): InstructionObject.__init__(self, id = id) self.type = 'page' # default values self.defaultInstruction = dict(Units = 'inch', Format = 'a4', Orientation = 'Portrait', Width = 8.268, Height = 11.693, Left = 0.5, Right = 0.5, Top = 1, Bottom = 1) # current values self.instruction = dict(self.defaultInstruction) def __str__(self): if self.instruction['Format'] == 'custom': instr = string.Template("paper\n width $Width\n height $Height\n").substitute(self.instruction) else: instr = string.Template("paper $Format\n").substitute(self.instruction) instr += string.Template(" left $Left\n right $Right\n bottom $Bottom\n top $Top\n end").substitute(self.instruction) return instr def Read(self, instruction, text, **kwargs): """!Read instruction and save information""" instr = {} self.cats = ['Width', 'Height', 'Left', 'Right', 'Top', 'Bottom'] self.subInstr = dict(zip(['width', 'height', 'left', 'right', 'top', 'bottom'], self.cats)) if instruction == 'paper': # just for sure for line in text: if line.startswith('paper'): if len(line.split()) > 1: pformat = line.split()[1] availableFormats = self._toDict(grass.read_command('ps.map', flags = 'p', quiet = True)) # e.g. paper a3 try: instr['Format'] = pformat for key, value in availableFormats[pformat].iteritems(): instr[key] = float(value) break except KeyError: GError(_("Failed to read instruction %(file)s.\nUnknown format %(for)s") % \ { 'file' : instruction, 'for' : format }) return False else: # paper # width ... instr['Format'] = 'custom' # read subinstructions elif instr['Format'] == 'custom' and not line.startswith('end'): text = line.split() try: instr[self.subInstr[text[0]]] = float(text[1]) except (IndexError, KeyError): GError(_("Failed to read instruction %s.") % instruction) return False if 'Orientation' in kwargs and kwargs['Orientation'] == 'Landscape': instr['Width'], instr['Height'] = instr['Height'], instr['Width'] self.instruction.update(instr) return True def _toDict(self, paperStr): sizeDict = dict() # cats = self.subInstr[ 'Width', 'Height', 'Left', 'Right', 'Top', 'Bottom'] for line in paperStr.strip().split('\n'): d = dict(zip(self.cats, line.split()[1:])) sizeDict[line.split()[0]] = d return sizeDict class Mapinfo(InstructionObject): """!Class representing mapinfo instruction""" def __init__(self, id): InstructionObject.__init__(self, id = id) self.type = 'mapinfo' # default values self.defaultInstruction = dict(unit = 'inch', where = (0, 0), font = 'Helvetica', fontsize = 10, color = '0:0:0', background = 'none', border = 'none', rect = None) # current values self.instruction = dict(self.defaultInstruction) def __str__(self): instr = "mapinfo\n" instr += " where %.3f %.3f\n" % (self.instruction['where'][0], self.instruction['where'][1]) instr += string.Template(" font $font\n fontsize $fontsize\n color $color\n").substitute(self.instruction) instr += string.Template(" background $background\n border $border\n").substitute(self.instruction) instr += " end" return instr def Read(self, instruction, text): """!Read instruction and save information""" instr = {} try: for line in text: sub = line.split(None,1) if sub[0] == 'font': instr['font'] = sub[1] elif sub[0] == 'fontsize': instr['fontsize'] = int(sub[1]) elif sub[0] == 'color': instr['color'] = sub[1] elif sub[0] == 'background': instr['background'] = sub[1] elif sub[0] == 'border': instr['border'] = sub[1] elif sub[0] == 'where': instr['where'] = float(sub[1].split()[0]), float(sub[1].split()[1]) except (ValueError, IndexError): GError(_("Failed to read instruction %s") % instruction) return False self.instruction.update(instr) self.instruction['rect'] = self.EstimateRect(mapinfoDict = self.instruction) return True def EstimateRect(self, mapinfoDict): """!Estimate size to draw mapinfo""" w = mapinfoDict['fontsize'] * 20 # any better estimation? h = mapinfoDict['fontsize'] * 7 width = self.unitConv.convert(value = w, fromUnit = 'point', toUnit = 'inch') height = self.unitConv.convert(value = h, fromUnit = 'point', toUnit = 'inch') return wx.Rect2D(x = float(mapinfoDict['where'][0]), y = float(mapinfoDict['where'][1]), w = width, h = height) class Text(InstructionObject): """!Class representing text instruction""" def __init__(self, id): InstructionObject.__init__(self, id = id) self.type = 'text' # default values self.defaultInstruction = dict(text = "", font = "Helvetica", fontsize = 10, color = 'black', background = 'none', hcolor = 'none', hwidth = 1, border = 'none', width = '1', XY = True, where = (0,0), unit = 'inch', rotate = None, ref = "center center", xoffset = 0, yoffset = 0, east = None, north = None) # current values self.instruction = dict(self.defaultInstruction) def __str__(self): text = self.instruction['text'].replace('\n','\\n') instr = "text %s %s" % (self.instruction['east'], self.instruction['north']) try: instr += " %s\n" % text.encode('latin_1') except UnicodeEncodeError, err: try: pos = str(err).split('position')[1].split(':')[0].strip() except IndexError: pos = '' if pos: message = _("Characters on position %s are not supported " "by ISO-8859-1 (Latin 1) encoding " "which is required by module ps.map.") % pos else: message = _("Not all characters are supported " "by ISO-8859-1 (Latin 1) encoding " "which is required by module ps.map.") GMessage(message = message) return '' instr += (string.Template(" font $font\n fontsize $fontsize\n color $color\n"). substitute(self.instruction). encode('latin_1')) instr += string.Template(" hcolor $hcolor\n").substitute(self.instruction).encode('latin_1') if self.instruction['hcolor'] != 'none': instr += string.Template(" hwidth $hwidth\n").substitute(self.instruction).encode('latin_1') instr += string.Template(" border $border\n").substitute(self.instruction).encode('latin_1') if self.instruction['border'] != 'none': instr += string.Template(" width $width\n").substitute(self.instruction).encode('latin_1') instr += string.Template(" background $background\n").substitute(self.instruction).encode('latin_1') if self.instruction["ref"] != '0': instr += string.Template(" ref $ref\n").substitute(self.instruction).encode('latin_1') if self.instruction["rotate"]: instr += string.Template(" rotate $rotate\n").substitute(self.instruction).encode('latin_1') if float(self.instruction["xoffset"]) or float(self.instruction["yoffset"]): instr += (string.Template(" xoffset $xoffset\n yoffset $yoffset\n"). substitute(self.instruction).encode('latin_1')) instr += " end" return instr def Read(self, instruction, text, **kwargs): """!Read instruction and save information""" map = kwargs['mapInstruction'] instr = {} for line in text: try: sub = line.split(None, 1)[0] if sub == 'text': e, n = line.split(None, 3)[1:3] if '%' in e and '%' in n: instr['XY'] = True instr['east'], instr['north'] = self.PercentToReal(e, n) else: instr['XY'] = False instr['east'], instr['north'] = float(e), float(n) instr['text'] = line.split(None, 3)[3] elif sub == 'font': instr['font'] = line.split(None, 1)[1] elif sub == 'fontsize': instr['fontsize'] = float(line.split(None, 1)[1]) elif sub == 'color': instr['color'] = line.split(None, 1)[1] elif sub == 'width': instr['width'] = line.split(None, 1)[1] elif sub == 'hcolor': instr['hcolor'] = line.split(None, 1)[1] elif sub == 'hwidth': instr['hwidth'] = line.split(None, 1)[1] elif sub == 'background': instr['background'] = line.split(None, 1)[1] elif sub == 'border': instr['border'] = line.split(None, 1)[1] elif sub == 'ref': instr['ref'] = line.split(None, 1)[1] elif sub == 'rotate': instr['rotate'] = float(line.split(None, 1)[1]) elif sub == 'xoffset': instr['xoffset'] = int(line.split(None, 1)[1]) elif sub == 'yoffset': instr['yoffset'] = int(line.split(None, 1)[1]) elif sub == 'opaque': if line.split(None, 1)[1].lower() in ('n', 'none'): instr['background'] = 'none' except(IndexError, ValueError): GError(_("Failed to read instruction %s") % instruction) return False instr['where'] = PaperMapCoordinates(map = map, x = instr['east'], y = instr['north'], paperToMap = False) self.instruction.update(instr) return True def PercentToReal(self, e, n): """!Converts text coordinates from percent of region to map coordinates""" e, n = float(e.strip('%')), float(n.strip('%')) region = grass.region() N = region['s'] + (region['n'] - region['s']) / 100 * n E = region['w'] + (region['e'] - region['w']) / 100 * e return E, N class Scalebar(InstructionObject): """!Class representing scalebar instruction""" def __init__(self, id): InstructionObject.__init__(self, id = id) self.type = 'scalebar' # default values self.defaultInstruction = dict(unit = 'inch', where = (1,1), unitsLength = 'auto', unitsHeight = 'inch', length = None, height = 0.1, rect = None, fontsize = 10, background = 'y', scalebar = 'f', segment = 4, numbers = 1) # current values self.instruction = dict(self.defaultInstruction) def __str__(self): instr = string.Template("scalebar $scalebar\n").substitute(self.instruction) instr += " where %.3f %.3f\n" % (self.instruction['where'][0], self.instruction['where'][1]) instr += string.Template(" length $length\n units $unitsLength\n").substitute(self.instruction) instr += string.Template(" height $height\n").substitute(self.instruction) instr += string.Template(" segment $segment\n numbers $numbers\n").substitute(self.instruction) instr += string.Template(" fontsize $fontsize\n background $background\n").substitute(self.instruction) instr += " end" return instr def Read(self, instruction, text, **kwargs): """!Read instruction and save information""" scale = kwargs['scale'] instr = {} for line in text: try: if line.startswith('scalebar'): if 'scalebar s' in line: instr['scalebar'] = 's' else: instr['scalebar'] = 'f' elif line.startswith('where'): instr['where'] = map(float, line.split()[1:3]) elif line.startswith('length'): instr['length'] = float(line.split()[1]) elif line.startswith('units'): if line.split()[1] in ['auto', 'meters', 'kilometers', 'feet', 'miles', 'nautmiles']: instr['unitsLength'] = line.split()[1] elif line.startswith('height'): instr['height'] = float(line.split()[1]) elif line.startswith('fontsize'): instr['fontsize'] = float(line.split()[1]) elif line.startswith('numbers'): instr['numbers'] = int(line.split()[1]) elif line.startswith('segment'): instr['segment'] = int(line.split()[1]) elif line.startswith('background'): if line.split()[1].strip().lower() in ('y','yes'): instr['background'] = 'y' elif line.split()[1].strip().lower() in ('n','no', 'none'): instr['background'] = 'n' except(IndexError, ValueError): GError(_("Failed to read instruction %s") % instruction) return False self.instruction.update(instr) w, h = self.EstimateSize(scalebarDict = self.instruction, scale = scale) x = self.instruction['where'][0] - w / 2 y = self.instruction['where'][1] - h / 2 self.instruction['rect'] = wx.Rect2D(x, y, w, h) return True def EstimateSize(self, scalebarDict, scale): """!Estimate size to draw scalebar""" units = projInfo()['units'] if not units or units not in self.unitConv.getAllUnits(): units = 'meters' if scalebarDict['unitsLength'] != 'auto': length = self.unitConv.convert(value = scalebarDict['length'], fromUnit = scalebarDict['unitsLength'], toUnit = 'inch') else: length = self.unitConv.convert(value = scalebarDict['length'], fromUnit = units, toUnit = 'inch') length *= scale length *= 1.1 #for numbers on the edge height = scalebarDict['height'] + 2 * self.unitConv.convert(value = scalebarDict['fontsize'], fromUnit = 'point', toUnit = 'inch') return (length, height) class RasterLegend(InstructionObject): """!Class representing colortable instruction""" def __init__(self, id): InstructionObject.__init__(self, id = id) self.type = 'rasterLegend' # default values self.defaultInstruction = dict(rLegend = False, unit = 'inch', rasterDefault = True, raster = None, discrete = None, type = None, where = (0, 0), width = None, height = None, cols = 1, font = "Helvetica", fontsize = 10, #color = '0:0:0', tickbar = False, range = False, min = 0, max = 0, color = 'black', tickbar = 'n', range = False, min = 0, max = 0, nodata = 'n') # current values self.instruction = dict(self.defaultInstruction) def __str__(self): instr = "colortable y\n" instr += string.Template(" raster $raster\n").substitute(self.instruction) instr += " where %.3f %.3f\n" % (self.instruction['where'][0], self.instruction['where'][1]) if self.instruction['width']: instr += string.Template(" width $width\n").substitute(self.instruction) instr += string.Template(" discrete $discrete\n").substitute(self.instruction) if self.instruction['discrete'] == 'n': if self.instruction['height']: instr += string.Template(" height $height\n").substitute(self.instruction) instr += string.Template(" tickbar $tickbar\n").substitute(self.instruction) if self.instruction['range']: instr += string.Template(" range $min $max\n").substitute(self.instruction) else: instr += string.Template(" cols $cols\n").substitute(self.instruction) instr += string.Template(" nodata $nodata\n").substitute(self.instruction) instr += string.Template(" font $font\n fontsize $fontsize\n color $color\n")\ .substitute(self.instruction) instr += " end" return instr def Read(self, instruction, text, **kwargs): """!Read instruction and save information""" instr = {} instr['rLegend'] = True for line in text: try: if line.startswith('where'): instr['where'] = map(float, line.split()[1:3]) elif line.startswith('font '): instr['font'] = line.split()[1] elif line.startswith('fontsize'): instr['fontsize'] = float(line.split()[1]) elif line.startswith('color '): instr['color'] = line.split()[1] elif line.startswith('raster'): instr['raster'] = line.split()[1] elif line.startswith('width'): instr['width'] = float(line.split()[1]) elif line.startswith('height'): instr['height'] = float(line.split()[1]) elif line.startswith('cols'): instr['cols'] = int(line.split()[1]) elif line.startswith('range'): instr['range'] = True instr['min'] = float(line.split()[1]) instr['max'] = float(line.split()[2]) elif line.startswith('nodata'): if line.split()[1].strip().lower() in ('y','yes'): instr['nodata'] = 'y' elif line.split()[1].strip().lower() in ('n','no', 'none'): instr['nodata'] = 'n' elif line.startswith('tickbar'): if line.split()[1].strip().lower() in ('y','yes'): instr['tickbar'] = 'y' elif line.split()[1].strip().lower() in ('n','no', 'none'): instr['tickbar'] = 'n' elif line.startswith('discrete'): if line.split()[1].strip().lower() in ('y','yes'): instr['discrete'] = 'y' elif line.split()[1].strip().lower() in ('n','no', 'none'): instr['discrete'] = 'n' except(IndexError, ValueError): GError(_("Failed to read instruction %s") % instruction) return False if 'raster' in instr: instr['rasterDefault'] = False if 'discrete' not in instr: rasterType = getRasterType(map = instr['raster']) instr['type'] = rasterType if rasterType == 'CELL': instr['discrete'] = 'y' else: instr['discrete'] = 'n' else: instr['rasterDefault'] = True self.instruction.update(instr) # add 'rect' in the end return True def EstimateHeight(self, raster, discrete, fontsize, cols = None, height = None): """!Estimate height to draw raster legend""" if discrete == 'n': if height: height = height else: height = self.unitConv.convert(value = fontsize * 10, fromUnit = 'point', toUnit = 'inch') if discrete == 'y': if cols: cols = cols else: cols = 1 rinfo = grass.raster_info(raster) if rinfo['datatype'] in ('DCELL', 'FCELL'): minim, maxim = rinfo['min'], rinfo['max'] rows = ceil(maxim / cols ) else: cat = grass.read_command('r.category', map = raster, fs = ':').strip().split('\n') rows = ceil(float(len(cat)) / cols ) height = self.unitConv.convert(value = 1.5 * rows * fontsize, fromUnit = 'point', toUnit = 'inch') return height def EstimateWidth(self, raster, discrete, fontsize, cols = None, width = None, paperInstr = None): """!Estimate size to draw raster legend""" if discrete == 'n': rinfo = grass.raster_info(raster) minim, maxim = rinfo['min'], rinfo['max'] if width: width = width else: width = self.unitConv.convert(value = fontsize * 2, fromUnit = 'point', toUnit = 'inch') text = len(max(str(minim), str(maxim), key = len)) textPart = self.unitConv.convert(value = text * fontsize / 2, fromUnit = 'point', toUnit = 'inch') width += textPart elif discrete == 'y': if cols: cols = cols else: cols = 1 if width: width = width else: paperWidth = paperInstr['Width'] - paperInstr['Right'] - paperInstr['Left'] width = (paperWidth / cols) * (cols - 1) + 1 return width class VectorLegend(InstructionObject): """!Class representing colortable instruction""" def __init__(self, id): InstructionObject.__init__(self, id = id) self.type = 'vectorLegend' # default values self.defaultInstruction = dict(vLegend = False, unit = 'inch', where = (0, 0), defaultSize = True, width = 0.4, cols = 1, span = None, font = "Helvetica", fontsize = 10, border = 'none') # current values self.instruction = dict(self.defaultInstruction) def __str__(self): instr = "vlegend\n" instr += " where %.3f %.3f\n" % (self.instruction['where'][0], self.instruction['where'][1]) instr += string.Template(" font $font\n fontsize $fontsize\n").substitute(self.instruction) instr += string.Template(" width $width\n cols $cols\n").substitute(self.instruction) if self.instruction['span']: instr += string.Template(" span $span\n").substitute(self.instruction) instr += string.Template(" border $border\n").substitute(self.instruction) instr += " end" return instr def Read(self, instruction, text, **kwargs): """!Read instruction and save information""" instr = {} instr['vLegend'] = True for line in text: try: if line.startswith('where'): instr['where'] = map(float, line.split()[1:3]) elif line.startswith('font '): instr['font'] = line.split()[1] elif line.startswith('fontsize'): instr['fontsize'] = float(line.split()[1]) elif line.startswith('width'): instr['width'] = float(line.split()[1]) elif line.startswith('cols'): instr['cols'] = int(line.split()[1]) elif line.startswith('span'): instr['span'] = float(line.split()[1]) elif line.startswith('border'): instr['border'] = line.split()[1] except(IndexError, ValueError): GError(_("Failed to read instruction %s") % instruction) return False self.instruction.update(instr) return True def EstimateSize(self, vectorInstr, fontsize, width = None, cols = None): """!Estimate size to draw vector legend""" if width: width = width else: width = fontsize/24.0 if cols: cols = cols else: cols = 1 vectors = vectorInstr['list'] labels = [vector[4] for vector in vectors if vector[3] != 0] extent = (len(max(labels, key = len)) * fontsize / 2, fontsize) wExtent = self.unitConv.convert(value = extent[0], fromUnit = 'point', toUnit = 'inch') hExtent = self.unitConv.convert(value = extent[1], fromUnit = 'point', toUnit = 'inch') w = (width + wExtent) * cols h = len(labels) * hExtent / cols h *= 1.1 return (w, h) class Raster(InstructionObject): """!Class representing raster instruction""" def __init__(self, id): InstructionObject.__init__(self, id = id) self.type = 'raster' # default values self.defaultInstruction = dict(isRaster = False, raster = None) # current values self.instruction = dict(self.defaultInstruction) def __str__(self): instr = string.Template("raster $raster").substitute(self.instruction) return instr def Read(self, instruction, text): """!Read instruction and save information""" instr = {} instr['isRaster'] = True try: map = text.split()[1] except IndexError: GError(_("Failed to read instruction %s") % instruction) return False try: info = grass.find_file(map, element = 'cell') except grass.ScriptError, e: GError(message = e.value) return False instr['raster'] = info['fullname'] self.instruction.update(instr) return True class Vector(InstructionObject): """!Class keeps vector layers""" def __init__(self, id): InstructionObject.__init__(self, id = id) self.type = 'vector' # default values self.defaultInstruction = dict(list = None)# [vmap, type, id, lpos, label] # current values self.instruction = dict(self.defaultInstruction) def __str__(self): return '' def Read(self, instruction, text, **kwargs): """!Read instruction and save information""" instr = {} for line in text: if line.startswith('vpoints') or line.startswith('vlines') or line.startswith('vareas'): # subtype if line.startswith('vpoints'): subType = 'points' elif line.startswith('vlines'): subType = 'lines' elif line.startswith('vareas'): subType = 'areas' # name of vector map vmap = line.split()[1] try: info = grass.find_file(vmap, element = 'vector') except grass.ScriptError, e: GError(message = e.value) return False vmap = info['fullname'] # id id = kwargs['id'] # lpos lpos = kwargs['vectorMapNumber'] #label label = '('.join(vmap.split('@')) + ')' break instr = [vmap, subType, id, lpos, label] if not self.instruction['list']: self.instruction['list'] = [] self.instruction['list'].append(instr) return True class VProperties(InstructionObject): """!Class represents instructions vareas, vlines, vpoints""" def __init__(self, id, subType): InstructionObject.__init__(self, id = id) self.type = 'vProperties' self.subType = subType # default values if self.subType == 'points': dd = dict(subType = 'points', name = None, type = 'point or centroid', connection = False, layer = '1', masked = 'n', color = '0:0:0', width = 1, fcolor = '255:0:0', rgbcolumn = None, symbol = os.path.join('basic', 'x'), eps = None, size = 5, sizecolumn = None, scale = None, rotation = False, rotate = 0, rotatecolumn = None, label = None, lpos = None) elif self.subType == 'lines': dd = dict(subType = 'lines', name = None, type = 'line or boundary', connection = False, layer = '1', masked = 'n', color = '0:0:0', hwidth = 1, hcolor = 'none', rgbcolumn = None, width = 1, cwidth = None, style = 'solid', linecap = 'butt', label = None, lpos = None) else: # areas dd = dict(subType = 'areas', name = None, connection = False, layer = '1', masked = 'n', color = '0:0:0', width = 1, fcolor = 'none', rgbcolumn = None, pat = None, pwidth = 1, scale = 1, label = None, lpos = None) self.defaultInstruction = dd # current values self.instruction = dict(self.defaultInstruction) def __str__(self): dic = self.instruction vInstruction = string.Template("v$subType $name\n").substitute(dic) #data selection if self.subType in ('points', 'lines'): vInstruction += string.Template(" type $type\n").substitute(dic) if dic['connection']: vInstruction += string.Template(" layer $layer\n").substitute(dic) if dic.has_key('cats'): vInstruction += string.Template(" cats $cats\n").substitute(dic) elif dic.has_key('where'): vInstruction += string.Template(" where $where\n").substitute(dic) vInstruction += string.Template(" masked $masked\n").substitute(dic) #colors vInstruction += string.Template(" color $color\n").substitute(dic) if self.subType in ('points', 'areas'): if dic['color'] != 'none': vInstruction += string.Template(" width $width\n").substitute(dic) if dic['rgbcolumn']: vInstruction += string.Template(" rgbcolumn $rgbcolumn\n").substitute(dic) vInstruction += string.Template(" fcolor $fcolor\n").substitute(dic) else: if dic['rgbcolumn']: vInstruction += string.Template(" rgbcolumn $rgbcolumn\n").substitute(dic) elif dic['hcolor'] != 'none': vInstruction += string.Template(" hwidth $hwidth\n").substitute(dic) vInstruction += string.Template(" hcolor $hcolor\n").substitute(dic) # size and style if self.subType == 'points': if dic['symbol']: vInstruction += string.Template(" symbol $symbol\n").substitute(dic) else: #eps vInstruction += string.Template(" eps $eps\n").substitute(dic) if dic['size']: vInstruction += string.Template(" size $size\n").substitute(dic) else: # sizecolumn vInstruction += string.Template(" sizecolumn $sizecolumn\n").substitute(dic) vInstruction += string.Template(" scale $scale\n").substitute(dic) if dic['rotation']: if dic['rotate'] is not None: vInstruction += string.Template(" rotate $rotate\n").substitute(dic) else: vInstruction += string.Template(" rotatecolumn $rotatecolumn\n").substitute(dic) if self.subType == 'areas': if dic['pat'] is not None: vInstruction += string.Template(" pat $pat\n").substitute(dic) vInstruction += string.Template(" pwidth $pwidth\n").substitute(dic) vInstruction += string.Template(" scale $scale\n").substitute(dic) if self.subType == 'lines': if dic['width'] is not None: vInstruction += string.Template(" width $width\n").substitute(dic) else: vInstruction += string.Template(" cwidth $cwidth\n").substitute(dic) vInstruction += string.Template(" style $style\n").substitute(dic) vInstruction += string.Template(" linecap $linecap\n").substitute(dic) #position and label in vlegend vInstruction += string.Template(" label $label\n lpos $lpos\n").substitute(dic) vInstruction += " end" return vInstruction def Read(self, instruction, text, **kwargs): """!Read instruction and save information""" instr = {} try: info = grass.find_file(name = text[0].split()[1], element = 'vector') except grass.ScriptError, e: GError(message = e.value) return False instr['name'] = info['fullname'] #connection instr['connection'] = True self.mapDBInfo = dbm_base.VectorDBInfo(instr['name']) self.layers = self.mapDBInfo.layers.keys() if not self.layers: instr['connection'] = False # points if text[0].startswith('vpoints'): for line in text[1:]: if line.startswith('type'): tp = [] if line.find('point') != -1: tp.append('point') if line.find('centroid') != -1: tp.append('centroid') instr['type'] = ' or '.join(tp) elif line.startswith('fcolor'): instr['fcolor'] = line.split()[1] elif line.startswith('rgbcolumn'): instr['rgbcolumn'] = line.split()[1] elif line.startswith('symbol'): instr['symbol'] = line.split()[1] elif line.startswith('eps'): instr['eps'] = line.split()[1] elif line.startswith('size '): instr['size'] = line.split()[1] elif line.startswith('sizecolumn'): instr['size'] = None instr['sizecolumn'] = line.split()[1] elif line.startswith('scale '): instr['scale'] = float(line.split()[1]) elif line.startswith('rotate '): instr['rotation'] = True instr['rotate'] = line.split()[1] elif line.startswith('rotatecolumn'): instr['rotatecolumn'] = line.split()[1] instr['rotation'] = True instr['rotate'] = None # lines elif text[0].startswith('vlines'): for line in text[1:]: if line.startswith('type'): tp = [] if line.find('line') != -1: tp.append('line') if line.find('boundary') != -1: tp.append('boundary') instr['type'] = ' or '.join(tp) elif line.startswith('hwidth'): instr['hwidth'] = float(line.split()[1]) elif line.startswith('hcolor'): instr['hcolor'] = line.split()[1] elif line.startswith('rgbcolumn'): instr['rgbcolumn'] = line.split()[1] elif line.startswith('cwidth'): instr['cwidth'] = float(line.split()[1]) instr['width'] = None elif line.startswith('style'): instr['style'] = line.split()[1] elif line.startswith('linecap'): instr['linecap'] = line.split()[1] elif text[0].startswith('vareas'): for line in text[1:]: if line.startswith('fcolor'): instr['fcolor'] = line.split()[1] elif line.startswith('pat'): instr['pat'] = line.split()[1] elif line.startswith('pwidth'): instr['pwidth'] = float(line.split()[1]) elif line.startswith('scale'): instr['scale'] = float(line.split()[1]) # same properties for all for line in text[1:]: if line.startswith('lpos'): instr['lpos'] = int(line.split()[1]) elif line.startswith('label'): instr['label'] = line.split(None, 1)[1] elif line.startswith('layer'): instr['layer'] = line.split()[1] elif line.startswith('masked'): if line.split()[1].lower() in ('y', 'yes'): instr['masked'] = 'y' else: instr['masked'] = 'n' elif line.startswith('color'): instr['color'] = line.split()[1] elif line.startswith('rgbcolumn'): instr['rgbcolumn'] = line.split()[1] elif line.startswith('width'): instr['width'] = float(line.split()[1]) if 'label' not in instr: instr['label'] = '('.join(instr['name'].split('@')) + ')' if 'lpos' not in instr: instr['lpos'] = kwargs['vectorMapNumber'] self.instruction.update(instr) return True class PsmapDialog(wx.Dialog): def __init__(self, parent, id, title, settings, apply = True): wx.Dialog.__init__(self, parent = parent, id = wx.ID_ANY, title = title, size = wx.DefaultSize, style = wx.CAPTION|wx.MINIMIZE_BOX|wx.CLOSE_BOX) self.apply = apply self.id = id self.parent = parent self.instruction = settings self.objectType = None self.unitConv = UnitConversion(self) self.spinCtrlSize = (50, -1) self.Bind(wx.EVT_CLOSE, self.OnClose) def AddUnits(self, parent, dialogDict): parent.units = dict() parent.units['unitsLabel'] = wx.StaticText(parent, id = wx.ID_ANY, label = _("Units:")) choices = self.unitConv.getPageUnitsNames() parent.units['unitsCtrl'] = wx.Choice(parent, id = wx.ID_ANY, choices = choices) parent.units['unitsCtrl'].SetStringSelection(self.unitConv.findName(dialogDict['unit'])) def AddPosition(self, parent, dialogDict): parent.position = dict() parent.position['comment'] = wx.StaticText(parent, id = wx.ID_ANY,\ label = _("Position of the top left corner\nfrom the top left edge of the paper")) parent.position['xLabel'] = wx.StaticText(parent, id = wx.ID_ANY, label = _("X:")) parent.position['yLabel'] = wx.StaticText(parent, id = wx.ID_ANY, label = _("Y:")) parent.position['xCtrl'] = wx.TextCtrl(parent, id = wx.ID_ANY, value = str(dialogDict['where'][0]), validator = TCValidator(flag = 'DIGIT_ONLY')) parent.position['yCtrl'] = wx.TextCtrl(parent, id = wx.ID_ANY, value = str(dialogDict['where'][1]), validator = TCValidator(flag = 'DIGIT_ONLY')) if dialogDict.has_key('unit'): x = self.unitConv.convert(value = dialogDict['where'][0], fromUnit = 'inch', toUnit = dialogDict['unit']) y = self.unitConv.convert(value = dialogDict['where'][1], fromUnit = 'inch', toUnit = dialogDict['unit']) parent.position['xCtrl'].SetValue("%5.3f" % x) parent.position['yCtrl'].SetValue("%5.3f" % y) def AddFont(self, parent, dialogDict, color = True): parent.font = dict() ## parent.font['fontLabel'] = wx.StaticText(parent, id = wx.ID_ANY, label = _("Choose font:")) ## parent.font['fontCtrl'] = wx.FontPickerCtrl(parent, id = wx.ID_ANY) ## ## parent.font['fontCtrl'].SetSelectedFont( ## wx.FontFromNativeInfoString(dialogDict['font'] + " " + str(dialogDict['fontsize']))) ## parent.font['fontCtrl'].SetMaxPointSize(50) ## ## if color: ## parent.font['colorLabel'] = wx.StaticText(parent, id = wx.ID_ANY, label = _("Choose color:")) ## parent.font['colorCtrl'] = wx.ColourPickerCtrl(parent, id = wx.ID_ANY, style=wx.FNTP_FONTDESC_AS_LABEL) ## parent.font['colorCtrl'].SetColour(dialogDict['color']) ## parent.font['colorCtrl'].SetColour(convertRGB(dialogDict['color'])) parent.font['fontLabel'] = wx.StaticText(parent, id = wx.ID_ANY, label = _("Font:")) parent.font['fontSizeLabel'] = wx.StaticText(parent, id = wx.ID_ANY, label = _("Font size:")) fontChoices = [ 'Times-Roman', 'Times-Italic', 'Times-Bold', 'Times-BoldItalic', 'Helvetica',\ 'Helvetica-Oblique', 'Helvetica-Bold', 'Helvetica-BoldOblique', 'Courier',\ 'Courier-Oblique', 'Courier-Bold', 'Courier-BoldOblique'] parent.font['fontCtrl'] = wx.Choice(parent, id = wx.ID_ANY, choices = fontChoices) if dialogDict['font'] in fontChoices: parent.font['fontCtrl'].SetStringSelection(dialogDict['font']) else: parent.font['fontCtrl'].SetStringSelection('Helvetica') parent.font['fontSizeCtrl'] = wx.SpinCtrl(parent, id = wx.ID_ANY, min = 4, max = 50, initial = 10) parent.font['fontSizeCtrl'].SetValue(dialogDict['fontsize']) if color: parent.font['colorLabel'] = wx.StaticText(parent, id = wx.ID_ANY, label = _("Choose color:")) parent.font['colorCtrl'] = wx.ColourPickerCtrl(parent, id = wx.ID_ANY) parent.font['colorCtrl'].SetColour(convertRGB(dialogDict['color'])) ## parent.font['colorLabel'] = wx.StaticText(parent, id = wx.ID_ANY, label = _("Color:")) ## colorChoices = [ 'aqua', 'black', 'blue', 'brown', 'cyan', 'gray', 'green', 'indigo', 'magenta',\ ## 'orange', 'purple', 'red', 'violet', 'white', 'yellow'] ## parent.colorCtrl = wx.Choice(parent, id = wx.ID_ANY, choices = colorChoices) ## parent.colorCtrl.SetStringSelection(parent.rLegendDict['color']) ## parent.font['colorCtrl'] = wx.ColourPickerCtrl(parent, id = wx.ID_ANY) ## parent.font['colorCtrl'].SetColour(dialogDict['color']) def OnApply(self, event): ok = self.update() if ok: self.parent.DialogDataChanged(id = self.id) return True else: return False def OnOK(self, event): """!Apply changes, close dialog""" ok = self.OnApply(event) if ok: self.Close() def OnCancel(self, event): """!Close dialog""" self.Close() def OnClose(self, event): """!Destroy dialog and delete it from open dialogs""" if self.objectType: for each in self.objectType: if each in self.parent.openDialogs: del self.parent.openDialogs[each] event.Skip() self.Destroy() def _layout(self, panel): #buttons btnCancel = wx.Button(self, wx.ID_CANCEL) btnOK = wx.Button(self, wx.ID_OK) btnOK.SetDefault() if self.apply: btnApply = wx.Button(self, wx.ID_APPLY) # bindigs btnOK.Bind(wx.EVT_BUTTON, self.OnOK) btnOK.SetToolTipString(_("Close dialog and apply changes")) #btnCancel.Bind(wx.EVT_BUTTON, self.OnCancel) btnCancel.SetToolTipString(_("Close dialog and ignore changes")) btnCancel.Bind(wx.EVT_BUTTON, self.OnCancel) if self.apply: btnApply.Bind(wx.EVT_BUTTON, self.OnApply) btnApply.SetToolTipString(_("Apply changes")) # sizers btnSizer = wx.StdDialogButtonSizer() btnSizer.AddButton(btnCancel) if self.apply: btnSizer.AddButton(btnApply) btnSizer.AddButton(btnOK) btnSizer.Realize() mainSizer = wx.BoxSizer(wx.VERTICAL) mainSizer.Add(item = panel, proportion = 1, flag = wx.EXPAND | wx.ALL, border = 5) mainSizer.Add(item = btnSizer, proportion = 0, flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5) self.SetSizer(mainSizer) mainSizer.Layout() mainSizer.Fit(self) class PageSetupDialog(PsmapDialog): def __init__(self, parent, id, settings): PsmapDialog.__init__(self, parent = parent, id = id, title = "Page setup", settings = settings) self.cat = ['Units', 'Format', 'Orientation', 'Width', 'Height', 'Left', 'Right', 'Top', 'Bottom'] labels = [_('Units'), _('Format'), _('Orientation'), _('Width'), _('Height'), _('Left'), _('Right'), _('Top'), _('Bottom')] self.catsLabels = dict(zip(self.cat, labels)) paperString = RunCommand('ps.map', flags = 'p', read = True, quiet = True) self.paperTable = self._toList(paperString) self.unitsList = self.unitConv.getPageUnitsNames() self.pageSetupDict = settings[id].GetInstruction() self._layout() if self.pageSetupDict: self.getCtrl('Units').SetStringSelection(self.unitConv.findName(self.pageSetupDict['Units'])) if self.pageSetupDict['Format'] == 'custom': self.getCtrl('Format').SetSelection(self.getCtrl('Format').GetCount() - 1) else: self.getCtrl('Format').SetStringSelection(self.pageSetupDict['Format']) if self.pageSetupDict['Orientation'] == 'Portrait': self.getCtrl('Orientation').SetSelection(0) else: self.getCtrl('Orientation').SetSelection(1) for item in self.cat[3:]: val = self.unitConv.convert(value = self.pageSetupDict[item], fromUnit = 'inch', toUnit = self.pageSetupDict['Units']) self.getCtrl(item).SetValue("%4.3f" % val) if self.getCtrl('Format').GetSelection() != self.getCtrl('Format').GetCount() - 1: # custom self.getCtrl('Width').Disable() self.getCtrl('Height').Disable() else: self.getCtrl('Orientation').Disable() # events self.getCtrl('Units').Bind(wx.EVT_CHOICE, self.OnChoice) self.getCtrl('Format').Bind(wx.EVT_CHOICE, self.OnChoice) self.getCtrl('Orientation').Bind(wx.EVT_CHOICE, self.OnChoice) self.btnOk.Bind(wx.EVT_BUTTON, self.OnOK) def update(self): self.pageSetupDict['Units'] = self.unitConv.findUnit(self.getCtrl('Units').GetStringSelection()) self.pageSetupDict['Format'] = self.paperTable[self.getCtrl('Format').GetSelection()]['Format'] if self.getCtrl('Orientation').GetSelection() == 0: self.pageSetupDict['Orientation'] = 'Portrait' else: self.pageSetupDict['Orientation'] = 'Landscape' for item in self.cat[3:]: self.pageSetupDict[item] = self.unitConv.convert(value = float(self.getCtrl(item).GetValue()), fromUnit = self.pageSetupDict['Units'], toUnit = 'inch') def OnOK(self, event): try: self.update() except ValueError: wx.MessageBox(message = _("Literal is not allowed!"), caption = _('Invalid input'), style = wx.OK|wx.ICON_ERROR) else: event.Skip() def _layout(self): size = (110,-1) #sizers mainSizer = wx.BoxSizer(wx.VERTICAL) pageBox = wx.StaticBox(self, id = wx.ID_ANY, label = " %s " % _("Page size")) pageSizer = wx.StaticBoxSizer(pageBox, wx.VERTICAL) marginBox = wx.StaticBox(self, id = wx.ID_ANY, label = " %s " % _("Margins")) marginSizer = wx.StaticBoxSizer(marginBox, wx.VERTICAL) horSizer = wx.BoxSizer(wx.HORIZONTAL) #staticText + choice choices = [self.unitsList, [item['Format'] for item in self.paperTable], [_('Portrait'), _('Landscape')]] propor = [0,1,1] border = [5,3,3] self.hBoxDict={} for i, item in enumerate(self.cat[:3]): hBox = wx.BoxSizer(wx.HORIZONTAL) stText = wx.StaticText(self, id = wx.ID_ANY, label = self.catsLabels[item] + ':') choice = wx.Choice(self, id = wx.ID_ANY, choices = choices[i], size = size) hBox.Add(stText, proportion = propor[i], flag = wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = border[i]) hBox.Add(choice, proportion = 0, flag = wx.ALL, border = border[i]) if item == 'Units': hBox.Add(size,1) self.hBoxDict[item] = hBox #staticText + TextCtrl for item in self.cat[3:]: hBox = wx.BoxSizer(wx.HORIZONTAL) label = wx.StaticText(self, id = wx.ID_ANY, label = self.catsLabels[item] + ':') textctrl = wx.TextCtrl(self, id = wx.ID_ANY, size = size, value = '') hBox.Add(label, proportion = 1, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 3) hBox.Add(textctrl, proportion = 0, flag = wx.ALIGN_CENTRE|wx.ALL, border = 3) self.hBoxDict[item] = hBox sizer = list([mainSizer] + [pageSizer]*4 + [marginSizer]*4) for i, item in enumerate(self.cat): sizer[i].Add(self.hBoxDict[item], 0, wx.GROW|wx.RIGHT|wx.LEFT,5) # OK button btnSizer = wx.StdDialogButtonSizer() self.btnOk = wx.Button(self, wx.ID_OK) self.btnOk.SetDefault() btnSizer.AddButton(self.btnOk) btn = wx.Button(self, wx.ID_CANCEL) btnSizer.AddButton(btn) btnSizer.Realize() horSizer.Add(pageSizer, proportion = 0, flag = wx.LEFT|wx.RIGHT|wx.BOTTOM, border = 10) horSizer.Add(marginSizer, proportion = 0, flag = wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, border = 10) mainSizer.Add(horSizer, proportion = 0, border = 10) mainSizer.Add(btnSizer, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT|wx.ALL, border = 10) self.SetSizer(mainSizer) mainSizer.Fit(self) def OnChoice(self, event): currPaper = self.paperTable[self.getCtrl('Format').GetSelection()] currUnit = self.unitConv.findUnit(self.getCtrl('Units').GetStringSelection()) currOrientIdx = self.getCtrl('Orientation').GetSelection() newSize = dict() for item in self.cat[3:]: newSize[item] = self.unitConv.convert(float(currPaper[item]), fromUnit = 'inch', toUnit = currUnit) enable = True if currPaper['Format'] != _('custom'): if currOrientIdx == 1: # portrait newSize['Width'], newSize['Height'] = newSize['Height'], newSize['Width'] for item in self.cat[3:]: self.getCtrl(item).ChangeValue("%4.3f" % newSize[item]) enable = False self.getCtrl('Width').Enable(enable) self.getCtrl('Height').Enable(enable) self.getCtrl('Orientation').Enable(not enable) def getCtrl(self, item): return self.hBoxDict[item].GetItem(1).GetWindow() def _toList(self, paperStr): sizeList = list() for line in paperStr.strip().split('\n'): d = dict(zip([self.cat[1]]+ self.cat[3:],line.split())) sizeList.append(d) d = {}.fromkeys([self.cat[1]]+ self.cat[3:], 100) d.update(Format = _('custom')) sizeList.append(d) return sizeList class MapDialog(PsmapDialog): """!Dialog for map frame settings and optionally raster and vector map selection""" def __init__(self, parent, id, settings, rect = None, notebook = False): PsmapDialog.__init__(self, parent = parent, id = id, title = "", settings = settings) self.isNotebook = notebook if self.isNotebook: self.objectType = ('mapNotebook',) else: self.objectType = ('map',) #notebook if self.isNotebook: self.notebook = wx.Notebook(parent = self, id = wx.ID_ANY, style = wx.BK_DEFAULT) self.mPanel = MapFramePanel(parent = self.notebook, id = self.id[0], settings = self.instruction, rect = rect, notebook = True) self.id[0] = self.mPanel.getId() self.rPanel = RasterPanel(parent = self.notebook, id = self.id[1], settings = self.instruction, notebook = True) self.id[1] = self.rPanel.getId() self.vPanel = VectorPanel(parent = self.notebook, id = self.id[2], settings = self.instruction, notebook = True) self.id[2] = self.vPanel.getId() self._layout(self.notebook) self.SetTitle(_("Map settings")) else: self.mPanel = MapFramePanel(parent = self, id = self.id[0], settings = self.instruction, rect = rect, notebook = False) self.id[0] = self.mPanel.getId() self._layout(self.mPanel) self.SetTitle(_("Map frame settings")) def OnApply(self, event): """!Apply changes""" if self.isNotebook: okV = self.vPanel.update() okR = self.rPanel.update() if okV and self.id[2] in self.instruction: self.parent.DialogDataChanged(id = self.id[2]) if okR and self.id[1] in self.instruction: self.parent.DialogDataChanged(id = self.id[1]) if not okR or not okV: return False ok = self.mPanel.update() if ok: self.parent.DialogDataChanged(id = self.id[0]) return True return False def OnCancel(self, event): """!Close dialog and remove tmp red box""" self.parent.canvas.pdcTmp.RemoveId(self.parent.canvas.idZoomBoxTmp) self.parent.canvas.Refresh() self.Close() def updateDialog(self): """!Update raster and vector information""" if self.mPanel.scaleChoice.GetSelection() == 0: if self.mPanel.rasterTypeRadio.GetValue(): if 'raster' in self.parent.openDialogs: if self.parent.openDialogs['raster'].rPanel.rasterYesRadio.GetValue() and \ self.parent.openDialogs['raster'].rPanel.rasterSelect.GetValue() == self.mPanel.select.GetValue(): self.mPanel.drawMap.SetValue(True) else: self.mPanel.drawMap.SetValue(False) else: if 'vector' in self.parent.openDialogs: found = False for each in self.parent.openDialogs['vector'].vPanel.vectorList: if each[0] == self.mPanel.select.GetValue(): found = True self.mPanel.drawMap.SetValue(found) class MapFramePanel(wx.Panel): """!wx.Panel with map (scale, region, border) settings""" def __init__(self, parent, id, settings, rect, notebook = True): wx.Panel.__init__(self, parent, id = wx.ID_ANY, style = wx.TAB_TRAVERSAL) self.id = id self.instruction = settings if notebook: self.book = parent self.book.AddPage(page = self, text = _("Map frame")) self.mapDialog = self.book.GetParent() else: self.mapDialog = parent if self.id is not None: self.mapFrameDict = self.instruction[self.id].GetInstruction() else: self.id = wx.NewId() mapFrame = MapFrame(self.id) self.mapFrameDict = mapFrame.GetInstruction() self.mapFrameDict['rect'] = rect self._layout() self.scale = [None]*4 self.center = [None]*4 self.selectedMap = self.mapFrameDict['map'] self.selectedRegion = self.mapFrameDict['region'] self.scaleType = self.mapFrameDict['scaleType'] self.mapType = self.mapFrameDict['mapType'] self.scaleChoice.SetSelection(self.mapFrameDict['scaleType']) if self.instruction[self.id]: self.drawMap.SetValue(self.mapFrameDict['drawMap']) else: self.drawMap.SetValue(True) if self.mapFrameDict['scaleType'] == 0 and self.mapFrameDict['map']: self.select.SetValue(self.mapFrameDict['map']) if self.mapFrameDict['mapType'] == 'raster': self.rasterTypeRadio.SetValue(True) self.vectorTypeRadio.SetValue(False) else: self.rasterTypeRadio.SetValue(False) self.vectorTypeRadio.SetValue(True) elif self.mapFrameDict['scaleType'] == 1 and self.mapFrameDict['region']: self.select.SetValue(self.mapFrameDict['region']) self.OnMap(None) self.scale[self.mapFrameDict['scaleType']] = self.mapFrameDict['scale'] self.center[self.mapFrameDict['scaleType']] = self.mapFrameDict['center'] self.OnScaleChoice(None) self.OnElementType(None) self.OnBorder(None) def _layout(self): """!Do layout""" border = wx.BoxSizer(wx.VERTICAL) box = wx.StaticBox (parent = self, id = wx.ID_ANY, label = " %s " % _("Map frame")) sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL) gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5) #scale options frameText = wx.StaticText(self, id = wx.ID_ANY, label = _("Map frame options:")) scaleChoices = [_("fit frame to match selected map"), _("fit frame to match saved region"), _("fit frame to match current computational region"), _("fixed scale and map center")] self.scaleChoice = wx.Choice(self, id = wx.ID_ANY, choices = scaleChoices) gridBagSizer.Add(frameText, pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.scaleChoice, pos = (1, 0), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0) #map and region selection self.staticBox = wx.StaticBox (parent = self, id = wx.ID_ANY, label = " %s " % _("Map selection")) sizerM = wx.StaticBoxSizer(self.staticBox, wx.HORIZONTAL) self.mapSizer = wx.GridBagSizer(hgap = 5, vgap = 5) self.rasterTypeRadio = wx.RadioButton(self, id = wx.ID_ANY, label = " %s " % _("raster"), style = wx.RB_GROUP) self.vectorTypeRadio = wx.RadioButton(self, id = wx.ID_ANY, label = " %s " % _("vector")) self.drawMap = wx.CheckBox(self, id = wx.ID_ANY, label = "add selected map") self.mapOrRegionText = [_("Map:"), _("Region:")] dc = wx.PaintDC(self)# determine size of labels width = max(dc.GetTextExtent(self.mapOrRegionText[0])[0], dc.GetTextExtent(self.mapOrRegionText[1])[0]) self.mapText = wx.StaticText(self, id = wx.ID_ANY, label = self.mapOrRegionText[0], size = (width, -1)) self.select = Select(self, id = wx.ID_ANY, size = globalvar.DIALOG_GSELECT_SIZE, type = 'raster', multiple = False, updateOnPopup = True, onPopup = None) self.mapSizer.Add(self.rasterTypeRadio, pos = (0, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.mapSizer.Add(self.vectorTypeRadio, pos = (0, 2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.mapSizer.Add(self.drawMap, pos = (0, 3), flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, border = 0) self.mapSizer.Add(self.mapText, pos = (1, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.mapSizer.Add(self.select, pos = (1, 1), span = (1, 3), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) sizerM.Add(self.mapSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5) gridBagSizer.Add(sizerM, pos = (2, 0), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0) #map scale and center boxC = wx.StaticBox (parent = self, id = wx.ID_ANY, label = " %s " % _("Map scale and center")) sizerC = wx.StaticBoxSizer(boxC, wx.HORIZONTAL) self.centerSizer = wx.FlexGridSizer(rows = 2, cols = 5, hgap = 5, vgap = 5) centerText = wx.StaticText(self, id = wx.ID_ANY, label = _("Center:")) self.eastingText = wx.StaticText(self, id = wx.ID_ANY, label = _("E:")) self.northingText = wx.StaticText(self, id = wx.ID_ANY, label = _("N:")) self.eastingTextCtrl = wx.TextCtrl(self, id = wx.ID_ANY, style = wx.TE_RIGHT, validator = TCValidator(flag = 'DIGIT_ONLY')) self.northingTextCtrl = wx.TextCtrl(self, id = wx.ID_ANY, style = wx.TE_RIGHT, validator = TCValidator(flag = 'DIGIT_ONLY')) scaleText = wx.StaticText(self, id = wx.ID_ANY, label = _("Scale:")) scalePrefixText = wx.StaticText(self, id = wx.ID_ANY, label = _("1 :")) self.scaleTextCtrl = wx.TextCtrl(self, id = wx.ID_ANY, value = "", style = wx.TE_RIGHT, validator = TCValidator('DIGIT_ONLY')) self.centerSizer.Add(centerText, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.RIGHT, border = 10) self.centerSizer.Add(self.eastingText, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, border = 0) self.centerSizer.Add(self.eastingTextCtrl, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.centerSizer.Add(self.northingText, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, border = 0) self.centerSizer.Add(self.northingTextCtrl, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.centerSizer.Add(scaleText, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.RIGHT, border = 10) self.centerSizer.Add(scalePrefixText, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, border = 0) self.centerSizer.Add(self.scaleTextCtrl, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0) sizerC.Add(self.centerSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5) gridBagSizer.Add(sizerC, pos = (3, 0), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0) #resolution flexSizer = wx.FlexGridSizer(rows = 1, cols = 2, hgap = 5, vgap = 5) resolutionText = wx.StaticText(self, id = wx.ID_ANY, label = _("Map max resolution (dpi):")) self.resolutionSpin = wx.SpinCtrl(self, id = wx.ID_ANY, min = 1, max = 1000, initial = 300) flexSizer.Add(resolutionText, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0) flexSizer.Add(self.resolutionSpin, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.resolutionSpin.SetValue(self.mapFrameDict['resolution']) gridBagSizer.Add(flexSizer, pos = (4, 0), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0) sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5) border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5) # border box = wx.StaticBox (parent = self, id = wx.ID_ANY, label = " %s " % _("Border")) sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL) gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5) self.borderCheck = wx.CheckBox(self, id = wx.ID_ANY, label = (_("draw border around map frame"))) if self.mapFrameDict['border'] == 'y': self.borderCheck.SetValue(True) else: self.borderCheck.SetValue(False) self.borderColorText = wx.StaticText(self, id = wx.ID_ANY, label = _("border color:")) self.borderWidthText = wx.StaticText(self, id = wx.ID_ANY, label = _("border width (pts):")) self.borderColourPicker = wx.ColourPickerCtrl(self, id = wx.ID_ANY) self.borderWidthCtrl = wx.SpinCtrl(self, id = wx.ID_ANY, min = 1, max = 100, initial = 1) if self.mapFrameDict['border'] == 'y': self.borderWidthCtrl.SetValue(int(self.mapFrameDict['width'])) self.borderColourPicker.SetColour(convertRGB(self.mapFrameDict['color'])) gridBagSizer.Add(self.borderCheck, pos = (0, 0), span = (1,2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0) gridBagSizer.Add(self.borderColorText, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.borderWidthText, pos = (2, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.borderColourPicker, pos = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0) gridBagSizer.Add(self.borderWidthCtrl, pos = (2, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0) sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5) border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5) self.SetSizer(border) self.Fit() if projInfo()['proj'] == 'll': self.scaleChoice.SetItems(self.scaleChoice.GetItems()[0:3]) boxC.Hide() for each in self.centerSizer.GetChildren(): each.GetWindow().Hide() # bindings self.scaleChoice.Bind(wx.EVT_CHOICE, self.OnScaleChoice) self.select.GetTextCtrl().Bind(wx.EVT_TEXT, self.OnMap) self.Bind(wx.EVT_RADIOBUTTON, self.OnElementType, self.vectorTypeRadio) self.Bind(wx.EVT_RADIOBUTTON, self.OnElementType, self.rasterTypeRadio) self.Bind(wx.EVT_CHECKBOX, self.OnBorder, self.borderCheck) def OnMap(self, event): """!Selected map or region changing""" if self.select.GetValue(): self.selected = self.select.GetValue() else: self.selected = None if self.scaleChoice.GetSelection() == 0: self.selectedMap = self.selected if self.rasterTypeRadio.GetValue(): mapType = 'raster' else: mapType = 'vector' self.scale[0], self.center[0], foo = AutoAdjust(self, scaleType = 0, map = self.selected, mapType = mapType, rect = self.mapFrameDict['rect']) #self.center[0] = self.RegionCenter(self.RegionDict(scaleType = 0)) elif self.scaleChoice.GetSelection() == 1: self.selectedRegion = self.selected self.scale[1], self.center[1], foo = AutoAdjust(self, scaleType = 1, region = self.selected, rect = self.mapFrameDict['rect']) #self.center[1] = self.RegionCenter(self.RegionDict(scaleType = 1)) elif self.scaleChoice.GetSelection() == 2: self.scale[2], self.center[2], foo = AutoAdjust(self, scaleType = 2, rect = self.mapFrameDict['rect']) #self.center[2] = self.RegionCenter(self.RegionDict(scaleType = 2)) else: self.scale[3] = None self.center[3] = None self.OnScaleChoice(None) def OnScaleChoice(self, event): """!Selected scale type changing""" scaleType = self.scaleChoice.GetSelection() if self.scaleType != scaleType: self.scaleType = scaleType self.select.SetValue("") if scaleType in (0, 1): # automatic - region from raster map, saved region if scaleType == 0: # set map selection self.rasterTypeRadio.Show() self.vectorTypeRadio.Show() self.drawMap.Show() self.staticBox.SetLabel(" %s " % _("Map selection")) if self.rasterTypeRadio.GetValue(): stype = 'raster' else: stype = 'vector' self.select.SetElementList(type = stype) self.mapText.SetLabel(self.mapOrRegionText[0]) self.select.SetToolTipString(_("Region is set to match this map,\nraster or vector map must be added later")) if scaleType == 1: # set region selection self.rasterTypeRadio.Hide() self.vectorTypeRadio.Hide() self.drawMap.Hide() self.staticBox.SetLabel(" %s " % _("Region selection")) stype = 'region' self.select.SetElementList(type = stype) self.mapText.SetLabel(self.mapOrRegionText[1]) self.select.SetToolTipString("") for each in self.mapSizer.GetChildren(): each.GetWindow().Enable() for each in self.centerSizer.GetChildren(): each.GetWindow().Disable() if self.scale[scaleType]: self.scaleTextCtrl.SetValue("%.0f" % (1/self.scale[scaleType])) if self.center[scaleType]: self.eastingTextCtrl.SetValue(str(self.center[scaleType][0])) self.northingTextCtrl.SetValue(str(self.center[scaleType][1])) elif scaleType == 2: for each in self.mapSizer.GetChildren(): each.GetWindow().Disable() for each in self.centerSizer.GetChildren(): each.GetWindow().Disable() if self.scale[scaleType]: self.scaleTextCtrl.SetValue("%.0f" % (1/self.scale[scaleType])) if self.center[scaleType]: self.eastingTextCtrl.SetValue(str(self.center[scaleType][0])) self.northingTextCtrl.SetValue(str(self.center[scaleType][1])) else: # fixed for each in self.mapSizer.GetChildren(): each.GetWindow().Disable() for each in self.centerSizer.GetChildren(): each.GetWindow().Enable() if self.scale[scaleType]: self.scaleTextCtrl.SetValue("%.0f" % (1/self.scale[scaleType])) if self.center[scaleType]: self.eastingTextCtrl.SetValue(str(self.center[scaleType][0])) self.northingTextCtrl.SetValue(str(self.center[scaleType][1])) def OnElementType(self, event): """!Changes data in map selection tree ctrl popup""" if self.rasterTypeRadio.GetValue(): mapType = 'raster' else: mapType = 'vector' self.select.SetElementList(type = mapType) if self.mapType != mapType and event is not None: self.mapType = mapType self.select.SetValue('') self.mapType = mapType def OnBorder(self, event): """!Enables/disable the part relating to border of map frame""" for each in (self.borderColorText, self.borderWidthText, self.borderColourPicker, self.borderWidthCtrl): each.Enable(self.borderCheck.GetValue()) def getId(self): """!Returns id of raster map""" return self.id def update(self): """!Save changes""" mapFrameDict = dict(self.mapFrameDict) # resolution mapFrameDict['resolution'] = self.resolutionSpin.GetValue() #scale scaleType = self.scaleType mapFrameDict['scaleType'] = scaleType if mapFrameDict['scaleType'] == 0: if self.select.GetValue(): mapFrameDict['drawMap'] = self.drawMap.GetValue() mapFrameDict['map'] = self.select.GetValue() mapFrameDict['mapType'] = self.mapType mapFrameDict['region'] = None if mapFrameDict['drawMap']: if mapFrameDict['mapType'] == 'raster': mapFile = grass.find_file(mapFrameDict['map'], element = 'cell') if mapFile['file'] == '': GMessage("Raster %s not found" % mapFrameDict['map']) return False raster = self.instruction.FindInstructionByType('raster') if raster: raster['raster'] = mapFrameDict['map'] else: raster = Raster(wx.NewId()) raster['raster'] = mapFrameDict['map'] raster['isRaster'] = True self.instruction.AddInstruction(raster) elif mapFrameDict['mapType'] == 'vector': mapFile = grass.find_file(mapFrameDict['map'], element = 'vector') if mapFile['file'] == '': GMessage("Vector %s not found" % mapFrameDict['map']) return False vector = self.instruction.FindInstructionByType('vector') isAdded = False if vector: for each in vector['list']: if each[0] == mapFrameDict['map']: isAdded = True if not isAdded: topoInfo = grass.vector_info_topo(map = mapFrameDict['map']) if topoInfo: if bool(topoInfo['areas']): topoType = 'areas' elif bool(topoInfo['lines']): topoType = 'lines' else: topoType = 'points' label = '('.join(mapFrameDict['map'].split('@')) + ')' if not vector: vector = Vector(wx.NewId()) vector['list'] = [] self.instruction.AddInstruction(vector) id = wx.NewId() vector['list'].insert(0, [mapFrameDict['map'], topoType, id, 1, label]) vProp = VProperties(id, topoType) vProp['name'], vProp['label'], vProp['lpos'] = mapFrameDict['map'], label, 1 self.instruction.AddInstruction(vProp) else: return False self.scale[0], self.center[0], self.rectAdjusted = AutoAdjust(self, scaleType = 0, map = mapFrameDict['map'], mapType = self.mapType, rect = self.mapFrameDict['rect']) if self.rectAdjusted: mapFrameDict['rect'] = self.rectAdjusted else: mapFrameDict['rect'] = self.mapFrameDict['rect'] mapFrameDict['scale'] = self.scale[0] mapFrameDict['center'] = self.center[0] # set region if self.mapType == 'raster': RunCommand('g.region', rast = mapFrameDict['map']) if self.mapType == 'vector': raster = self.instruction.FindInstructionByType('raster') if raster: rasterId = raster.id else: rasterId = None if rasterId: RunCommand('g.region', vect = mapFrameDict['map'], rast = self.instruction[rasterId]['raster']) else: RunCommand('g.region', vect = mapFrameDict['map']) else: wx.MessageBox(message = _("No map selected!"), caption = _('Invalid input'), style = wx.OK|wx.ICON_ERROR) return False elif mapFrameDict['scaleType'] == 1: if self.select.GetValue(): mapFrameDict['drawMap'] = False mapFrameDict['map'] = None mapFrameDict['mapType'] = None mapFrameDict['region'] = self.select.GetValue() self.scale[1], self.center[1], self.rectAdjusted = AutoAdjust(self, scaleType = 1, region = mapFrameDict['region'], rect = self.mapFrameDict['rect']) if self.rectAdjusted: mapFrameDict['rect'] = self.rectAdjusted else: mapFrameDict['rect'] = self.mapFrameDict['rect'] mapFrameDict['scale'] = self.scale[1] mapFrameDict['center'] = self.center[1] # set region RunCommand('g.region', region = mapFrameDict['region']) else: wx.MessageBox(message = _("No region selected!"), caption = _('Invalid input'), style = wx.OK|wx.ICON_ERROR) return False elif scaleType == 2: mapFrameDict['drawMap'] = False mapFrameDict['map'] = None mapFrameDict['mapType'] = None mapFrameDict['region'] = None self.scale[2], self.center[2], self.rectAdjusted = AutoAdjust(self, scaleType = 2, rect = self.mapFrameDict['rect']) if self.rectAdjusted: mapFrameDict['rect'] = self.rectAdjusted else: mapFrameDict['rect'] = self.mapFrameDict['rect'] mapFrameDict['scale'] = self.scale[2] mapFrameDict['center'] = self.center[2] env = grass.gisenv() windFilePath = os.path.join(env['GISDBASE'], env['LOCATION_NAME'], env['MAPSET'], 'WIND') try: windFile = open(windFilePath, 'r').read() region = grass.parse_key_val(windFile, sep = ':', val_type = float) except IOError: region = grass.region() raster = self.instruction.FindInstructionByType('raster') if raster: rasterId = raster.id else: rasterId = None if rasterId: # because of resolution RunCommand('g.region', n = region['north'], s = region['south'], e = region['east'], w = region['west'], rast = self.instruction[rasterId]['raster']) else: RunCommand('g.region', n = region['north'], s = region['south'], e = region['east'], w = region['west']) elif scaleType == 3: mapFrameDict['drawMap'] = False mapFrameDict['map'] = None mapFrameDict['mapType'] = None mapFrameDict['region'] = None mapFrameDict['rect'] = self.mapFrameDict['rect'] try: scaleNumber = float(self.scaleTextCtrl.GetValue()) centerE = float(self.eastingTextCtrl.GetValue()) centerN = float(self.northingTextCtrl.GetValue()) except (ValueError, SyntaxError): wx.MessageBox(message = _("Invalid scale or map center!"), caption = _('Invalid input'), style = wx.OK|wx.ICON_ERROR) return False mapFrameDict['scale'] = 1/scaleNumber mapFrameDict['center'] = centerE, centerN ComputeSetRegion(self, mapDict = mapFrameDict) # check resolution SetResolution(dpi = mapFrameDict['resolution'], width = mapFrameDict['rect'].width, height = mapFrameDict['rect'].height) # border if self.borderCheck.GetValue(): mapFrameDict['border'] = 'y' else: mapFrameDict['border'] = 'n' if mapFrameDict['border'] == 'y': mapFrameDict['width'] = self.borderWidthCtrl.GetValue() mapFrameDict['color'] = convertRGB(self.borderColourPicker.GetColour()) if self.id not in self.instruction: mapFrame = MapFrame(self.id) self.instruction.AddInstruction(mapFrame) self.instruction[self.id].SetInstruction(mapFrameDict) if self.id not in self.mapDialog.parent.objectId: self.mapDialog.parent.objectId.insert(0, self.id)# map frame is drawn first return True class RasterPanel(wx.Panel): """!Panel for raster map settings""" def __init__(self, parent, id, settings, notebook = True): wx.Panel.__init__(self, parent, id = wx.ID_ANY, style = wx.TAB_TRAVERSAL) self.instruction = settings if notebook: self.book = parent self.book.AddPage(page = self, text = _("Raster map")) self.mainDialog = self.book.GetParent() else: self.mainDialog = parent if id: self.id = id self.rasterDict = self.instruction[self.id].GetInstruction() else: self.id = wx.NewId() raster = Raster(self.id) self.rasterDict = raster.GetInstruction() self._layout() self.OnRaster(None) def _layout(self): """!Do layout""" border = wx.BoxSizer(wx.VERTICAL) # choose raster map box = wx.StaticBox (parent = self, id = wx.ID_ANY, label = " %s " % _("Choose raster map")) sizer = wx.StaticBoxSizer(box, wx.VERTICAL) gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5) self.rasterNoRadio = wx.RadioButton(self, id = wx.ID_ANY, label = _("no raster map"), style = wx.RB_GROUP) self.rasterYesRadio = wx.RadioButton(self, id = wx.ID_ANY, label = _("raster:")) self.rasterSelect = Select(self, id = wx.ID_ANY, size = globalvar.DIALOG_GSELECT_SIZE, type = 'raster', multiple = False, updateOnPopup = True, onPopup = None) if self.rasterDict['isRaster']: self.rasterYesRadio.SetValue(True) self.rasterNoRadio.SetValue(False) self.rasterSelect.SetValue(self.rasterDict['raster']) else: self.rasterYesRadio.SetValue(False) self.rasterNoRadio.SetValue(True) mapId = self.instruction.FindInstructionByType('map').id if self.instruction[mapId]['map'] and self.instruction[mapId]['mapType'] == 'raster': self.rasterSelect.SetValue(self.instruction[mapId]['map'])# raster map from map frame dialog if possible else: self.rasterSelect.SetValue('') gridBagSizer.Add(self.rasterNoRadio, pos = (0, 0), span = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.rasterYesRadio, pos = (1, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.rasterSelect, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0) sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5) border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5) #self.rasterSelect.GetTextCtrl().Bind(wx.EVT_TEXT, self.OnRaster) self.Bind(wx.EVT_RADIOBUTTON, self.OnRaster, self.rasterNoRadio) self.Bind(wx.EVT_RADIOBUTTON, self.OnRaster, self.rasterYesRadio) self.SetSizer(border) self.Fit() def OnRaster(self, event): """!Enable/disable raster selection""" self.rasterSelect.Enable(self.rasterYesRadio.GetValue()) def update(self): #draw raster map = self.instruction.FindInstructionByType('map') if self.rasterNoRadio.GetValue() or not self.rasterSelect.GetValue(): self.rasterDict['isRaster'] = False self.rasterDict['raster'] = None map['drawMap'] = False if self.id in self.instruction: del self.instruction[self.id] else: self.rasterDict['isRaster'] = True self.rasterDict['raster'] = self.rasterSelect.GetValue() if self.rasterDict['raster'] != map['drawMap']: map['drawMap'] = False if self.id not in self.instruction: raster = Raster(self.id) self.instruction.AddInstruction(raster) self.instruction[self.id].SetInstruction(self.rasterDict) if 'map' in self.mainDialog.parent.openDialogs: self.mainDialog.parent.openDialogs['map'].updateDialog() return True def getId(self): return self.id class VectorPanel(wx.Panel): """!Panel for vector maps settings""" def __init__(self, parent, id, settings, notebook = True): wx.Panel.__init__(self, parent, id = wx.ID_ANY, style = wx.TAB_TRAVERSAL) self.parent = parent self.instruction = settings self.tmpDialogDict = {} vectors = self.instruction.FindInstructionByType('vProperties', list = True) for vector in vectors: self.tmpDialogDict[vector.id] = dict(self.instruction[vector.id].GetInstruction()) if id: self.id = id self.vectorList = deepcopy(self.instruction[id]['list']) else: self.id = wx.NewId() self.vectorList = [] vLegend = self.instruction.FindInstructionByType('vectorLegend') if vLegend: self.vLegendId = vLegend.id else: self.vLegendId = None self._layout() if notebook: self.parent.AddPage(page = self, text = _("Vector maps")) self.parent = self.parent.GetParent() def _layout(self): """!Do layout""" border = wx.BoxSizer(wx.VERTICAL) # choose vector map box = wx.StaticBox (parent = self, id = wx.ID_ANY, label = " %s " % _("Add map")) sizer = wx.StaticBoxSizer(box, wx.VERTICAL) gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5) text = wx.StaticText(self, id = wx.ID_ANY, label = _("Map:")) self.select = Select(self, id = wx.ID_ANY,# size = globalvar.DIALOG_GSELECT_SIZE, type = 'vector', multiple = False, updateOnPopup = True, onPopup = None) topologyType = [_("points"), _("lines"), _("areas")] self.vectorType = wx.RadioBox(self, id = wx.ID_ANY, label = " %s " % _("Data Type"), choices = topologyType, majorDimension = 3, style = wx.RA_SPECIFY_COLS) self.AddVector = wx.Button(self, id = wx.ID_ANY, label = _("Add")) gridBagSizer.Add(text, pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.select, pos = (0,1), span = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.vectorType, pos = (1,1), flag = wx.ALIGN_CENTER, border = 0) gridBagSizer.Add(self.AddVector, pos = (1,2), flag = wx.ALIGN_BOTTOM|wx.ALIGN_RIGHT, border = 0) sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5) border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5) # manage vector layers box = wx.StaticBox (parent = self, id = wx.ID_ANY, label = " %s " % _("Manage vector maps")) sizer = wx.StaticBoxSizer(box, wx.VERTICAL) gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5) gridBagSizer.AddGrowableCol(0,2) gridBagSizer.AddGrowableCol(1,1) text = wx.StaticText(self, id = wx.ID_ANY, label = _("The topmost vector map overlaps the others")) self.listbox = wx.ListBox(self, id = wx.ID_ANY, choices = [], style = wx.LB_SINGLE|wx.LB_NEEDED_SB) self.btnUp = wx.Button(self, id = wx.ID_ANY, label = _("Up")) self.btnDown = wx.Button(self, id = wx.ID_ANY, label = _("Down")) self.btnDel = wx.Button(self, id = wx.ID_ANY, label = _("Delete")) self.btnProp = wx.Button(self, id = wx.ID_ANY, label = _("Properties...")) self.updateListBox(selected=0) gridBagSizer.Add(text, pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.listbox, pos = (1,0), span = (4, 1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0) gridBagSizer.Add(self.btnUp, pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0) gridBagSizer.Add(self.btnDown, pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0) gridBagSizer.Add(self.btnDel, pos = (3,1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0) gridBagSizer.Add(self.btnProp, pos = (4,1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0) sizer.Add(gridBagSizer, proportion = 0, flag = wx.ALL, border = 5) border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5) self.Bind(wx.EVT_BUTTON, self.OnAddVector, self.AddVector) self.Bind(wx.EVT_BUTTON, self.OnDelete, self.btnDel) self.Bind(wx.EVT_BUTTON, self.OnUp, self.btnUp) self.Bind(wx.EVT_BUTTON, self.OnDown, self.btnDown) self.Bind(wx.EVT_BUTTON, self.OnProperties, self.btnProp) self.select.GetTextCtrl().Bind(wx.EVT_TEXT, self.OnVector) self.SetSizer(border) self.Fit() self.Bind(wx.EVT_LISTBOX_DCLICK, self.OnProperties, self.listbox) def OnVector(self, event): """!Gets info about toplogy and enables/disables choices point/line/area""" vmap = self.select.GetValue() try: topoInfo = grass.vector_info_topo(map = vmap) except grass.ScriptError: return if topoInfo: self.vectorType.EnableItem(2, bool(topoInfo['areas'])) self.vectorType.EnableItem(1, bool(topoInfo['boundaries']) or bool(topoInfo['lines'])) self.vectorType.EnableItem(0, bool(topoInfo['centroids'] or bool(topoInfo['points']) )) for item in range(2,-1,-1): if self.vectorType.IsItemEnabled(item): self.vectorType.SetSelection(item) break self.AddVector.SetFocus() def OnAddVector(self, event): """!Adds vector map to list""" vmap = self.select.GetValue() if vmap: mapname = vmap.split('@')[0] try: mapset = '(' + vmap.split('@')[1] + ')' except IndexError: mapset = '' type = self.vectorType.GetStringSelection() record = "%s - %s" % (vmap,type) id = wx.NewId() lpos = 1 label = mapname + mapset self.vectorList.insert(0, [vmap, type, id, lpos, label]) self.reposition() self.listbox.InsertItems([record], 0) vector = VProperties(id, type) self.tmpDialogDict[id] = vector.GetInstruction() self.tmpDialogDict[id]['name'] = vmap self.listbox.SetSelection(0) self.listbox.EnsureVisible(0) self.btnProp.SetFocus() self.enableButtons() def OnDelete(self, event): """!Deletes vector map from the list""" if self.listbox.GetSelections(): pos = self.listbox.GetSelection() id = self.vectorList[pos][2] del self.vectorList[pos] del self.tmpDialogDict[id] for i in range(pos, len(self.vectorList)): if self.vectorList[i][3]:# can be 0 self.vectorList[i][3] -= 1 if pos < len(self.vectorList) -1: selected = pos else: selected = len(self.vectorList) -1 self.updateListBox(selected = selected) if self.listbox.IsEmpty(): self.enableButtons(False) def OnUp(self, event): """!Moves selected map to top""" if self.listbox.GetSelections(): pos = self.listbox.GetSelection() if pos: self.vectorList.insert(pos - 1, self.vectorList.pop(pos)) if not self.vLegendId: self.reposition() if pos > 0: self.updateListBox(selected = (pos - 1)) else: self.updateListBox(selected = 0) def OnDown(self, event): """!Moves selected map to bottom""" if self.listbox.GetSelections(): pos = self.listbox.GetSelection() if pos != len(self.vectorList) - 1: self.vectorList.insert(pos + 1, self.vectorList.pop(pos)) if not self.vLegendId: self.reposition() if pos < len(self.vectorList) -1: self.updateListBox(selected = (pos + 1)) else: self.updateListBox(selected = len(self.vectorList) -1) def OnProperties(self, event): """!Opens vector map properties dialog""" if self.listbox.GetSelections(): pos = self.listbox.GetSelection() id = self.vectorList[pos][2] dlg = VPropertiesDialog(self, id = id, settings = self.instruction, vectors = self.vectorList, tmpSettings = self.tmpDialogDict[id]) dlg.ShowModal() self.parent.FindWindowById(wx.ID_OK).SetFocus() def enableButtons(self, enable = True): """!Enable/disable up, down, properties, delete buttons""" self.btnUp.Enable(enable) self.btnDown.Enable(enable) self.btnProp.Enable(enable) self.btnDel.Enable(enable) def updateListBox(self, selected = None): mapList = ["%s - %s" % (item[0], item[1]) for item in self.vectorList] self.listbox.Set(mapList) if self.listbox.IsEmpty(): self.enableButtons(False) else: self.enableButtons(True) if selected is not None: self.listbox.SetSelection(selected) self.listbox.EnsureVisible(selected) def reposition(self): """!Update position in legend, used only if there is no vlegend yet""" for i in range(len(self.vectorList)): if self.vectorList[i][3]: self.vectorList[i][3] = i + 1 def getId(self): return self.id def update(self): vectors = self.instruction.FindInstructionByType('vProperties', list = True) for vector in vectors: del self.instruction[vector.id] if self.id in self.instruction: del self.instruction[self.id] if len(self.vectorList) > 0: vector = Vector(self.id) self.instruction.AddInstruction(vector) vector.SetInstruction({'list': deepcopy(self.vectorList)}) # save new vectors for item in self.vectorList: id = item[2] vLayer = VProperties(id, item[1]) self.instruction.AddInstruction(vLayer) vLayer.SetInstruction(self.tmpDialogDict[id]) vLayer['name'] = item[0] vLayer['label'] = item[4] vLayer['lpos'] = item[3] else: if self.id in self.instruction: del self.instruction[self.id] if 'map' in self.parent.parent.openDialogs: self.parent.parent.openDialogs['map'].updateDialog() return True class RasterDialog(PsmapDialog): def __init__(self, parent, id, settings): PsmapDialog.__init__(self, parent = parent, id = id, title = _("Raster map settings"), settings = settings) self.objectType = ('raster',) self.rPanel = RasterPanel(parent = self, id = self.id, settings = self.instruction, notebook = False) self.id = self.rPanel.getId() self._layout(self.rPanel) def update(self): ok = self.rPanel.update() if ok: return True return False def OnApply(self, event): ok = self.update() if not ok: return False if self.id in self.instruction: self.parent.DialogDataChanged(id = self.id) else: mapId = self.instruction.FindInstructionByType('map').id self.parent.DialogDataChanged(id = mapId) return True def updateDialog(self): """!Update information (not used)""" pass ## if 'map' in self.parent.openDialogs: ## if self.parent.openDialogs['map'].mPanel.rasterTypeRadio.GetValue()\ ## and self.parent.openDialogs['map'].mPanel.select.GetValue(): ## if self.parent.openDialogs['map'].mPanel.drawMap.IsChecked(): ## self.rPanel.rasterSelect.SetValue(self.parent.openDialogs['map'].mPanel.select.GetValue()) class MainVectorDialog(PsmapDialog): def __init__(self, parent, id, settings): PsmapDialog.__init__(self, parent = parent, id = id, title = _("Vector maps settings"), settings = settings) self.objectType = ('vector',) self.vPanel = VectorPanel(parent = self, id = self.id, settings = self.instruction, notebook = False) self.id = self.vPanel.getId() self._layout(self.vPanel) def update(self): self.vPanel.update() def OnApply(self, event): self.update() if self.id in self.instruction: self.parent.DialogDataChanged(id = self.id) else: mapId = self.instruction.FindInstructionByType('map').id self.parent.DialogDataChanged(id = mapId) return True def updateDialog(self): """!Update information (not used)""" pass class VPropertiesDialog(PsmapDialog): def __init__(self, parent, id, settings, vectors, tmpSettings): PsmapDialog.__init__(self, parent = parent, id = id, title = "", settings = settings, apply = False) vectorList = vectors self.vPropertiesDict = tmpSettings # determine map and its type for item in vectorList: if id == item[2]: self.vectorName = item[0] self.type = item[1] self.SetTitle(self.vectorName + " "+ _("properties")) #vector map info self.connection = True try: self.mapDBInfo = dbm_base.VectorDBInfo(self.vectorName) self.layers = self.mapDBInfo.layers.keys() except grass.ScriptError: self.connection = False self.layers = [] if not self.layers: self.connection = False self.layers = [] self.currLayer = self.vPropertiesDict['layer'] #path to symbols, patterns gisbase = os.getenv("GISBASE") self.symbolPath = os.path.join(gisbase, 'etc', 'symbol') self.symbols = [] for dir in os.listdir(self.symbolPath): for symbol in os.listdir(os.path.join(self.symbolPath, dir)): self.symbols.append(os.path.join(dir, symbol)) self.patternPath = os.path.join(gisbase, 'etc', 'paint', 'patterns') #notebook notebook = wx.Notebook(parent = self, id = wx.ID_ANY, style = wx.BK_DEFAULT) self.DSpanel = self._DataSelectionPanel(notebook) self.EnableLayerSelection(enable = self.connection) selectPanel = { 'points': [self._ColorsPointAreaPanel, self._StylePointPanel], 'lines': [self._ColorsLinePanel, self._StyleLinePanel], 'areas': [self._ColorsPointAreaPanel, self._StyleAreaPanel]} self.ColorsPanel = selectPanel[self.type][0](notebook) self.OnOutline(None) if self.type in ('points', 'areas'): self.OnFill(None) self.OnColor(None) self.StylePanel = selectPanel[self.type][1](notebook) if self.type == 'points': self.OnSize(None) self.OnRotation(None) if self.type == 'areas': self.OnPattern(None) self._layout(notebook) def _DataSelectionPanel(self, notebook): panel = wx.Panel(parent = notebook, id = wx.ID_ANY, size = (-1, -1), style = wx.TAB_TRAVERSAL) notebook.AddPage(page = panel, text = _("Data selection")) border = wx.BoxSizer(wx.VERTICAL) # data type self.checkType1 = self.checkType2 = None if self.type in ('lines', 'points'): box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Feature type")) sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL) gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5) if self.type == 'points': label = (_("points"), _("centroids")) else: label = (_("lines"), _("boundaries")) if self.type == 'points': name = ("point", "centroid") else: name = ("line", "boundary") self.checkType1 = wx.CheckBox(panel, id = wx.ID_ANY, label = label[0], name = name[0]) self.checkType2 = wx.CheckBox(panel, id = wx.ID_ANY, label = label[1], name = name[1]) self.checkType1.SetValue(self.vPropertiesDict['type'].find(name[0]) >= 0) self.checkType2.SetValue(self.vPropertiesDict['type'].find(name[1]) >= 0) gridBagSizer.Add(self.checkType1, pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.checkType2, pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5) border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5) # layer selection box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Layer selection")) sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL) self.gridBagSizerL = wx.GridBagSizer(hgap = 5, vgap = 5) self.warning = wx.StaticText(panel, id = wx.ID_ANY, label = "") if not self.connection: self.warning = wx.StaticText(panel, id = wx.ID_ANY, label = _("Database connection is not defined in DB file.")) text = wx.StaticText(panel, id = wx.ID_ANY, label = _("Select layer:")) self.layerChoice = wx.Choice(panel, id = wx.ID_ANY, choices = map(str, self.layers), size = self.spinCtrlSize) self.layerChoice.SetStringSelection(self.currLayer) if self.connection: table = self.mapDBInfo.layers[int(self.currLayer)]['table'] else: table = "" self.radioWhere = wx.RadioButton(panel, id = wx.ID_ANY, label = "SELECT * FROM %s WHERE" % table, style = wx.RB_GROUP) self.textCtrlWhere = wx.TextCtrl(panel, id = wx.ID_ANY, value = "") if self.connection: cols = self.mapDBInfo.GetColumns(self.mapDBInfo.layers[int(self.currLayer)]['table']) else: cols = [] self.choiceColumns = wx.Choice(panel, id = wx.ID_ANY, choices = cols) self.radioCats = wx.RadioButton(panel, id = wx.ID_ANY, label = "Choose categories ") self.textCtrlCats = wx.TextCtrl(panel, id = wx.ID_ANY, value = "") self.textCtrlCats.SetToolTipString(_("list of categories (e.g. 1,3,5-7)")) if self.vPropertiesDict.has_key('cats'): self.radioCats.SetValue(True) self.textCtrlCats.SetValue(self.vPropertiesDict['cats']) if self.vPropertiesDict.has_key('where'): self.radioWhere.SetValue(True) where = self.vPropertiesDict['where'].strip().split(" ",1) self.choiceColumns.SetStringSelection(where[0]) self.textCtrlWhere.SetValue(where[1]) row = 0 if not self.connection: self.gridBagSizerL.Add(self.warning, pos = (0,0), span = (1,3), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) row = 1 self.gridBagSizerL.Add(text, pos = (0 + row,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.gridBagSizerL.Add(self.layerChoice, pos = (0 + row,1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0) self.gridBagSizerL.Add(self.radioWhere, pos = (1 + row,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.gridBagSizerL.Add(self.choiceColumns, pos = (1 + row,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.gridBagSizerL.Add(self.textCtrlWhere, pos = (1 + row,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.gridBagSizerL.Add(self.radioCats, pos = (2 + row,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.gridBagSizerL.Add(self.textCtrlCats, pos = (2 + row,1), span = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0) sizer.Add(self.gridBagSizerL, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5) border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5) #mask box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Mask")) sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL) self.mask = wx.CheckBox(panel, id = wx.ID_ANY, label = _("Use current mask")) if self.vPropertiesDict['masked'] == 'y': self.mask.SetValue(True) else: self.mask.SetValue(False) sizer.Add(self.mask, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5) border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5) self.Bind(wx.EVT_CHOICE, self.OnLayer, self.layerChoice) panel.SetSizer(border) panel.Fit() return panel def _ColorsPointAreaPanel(self, notebook): panel = wx.Panel(parent = notebook, id = wx.ID_ANY, size = (-1, -1), style = wx.TAB_TRAVERSAL) notebook.AddPage(page = panel, text = _("Colors")) border = wx.BoxSizer(wx.VERTICAL) #colors - outline box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Outline")) sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL) self.gridBagSizerO = wx.GridBagSizer(hgap = 5, vgap = 2) self.outlineCheck = wx.CheckBox(panel, id = wx.ID_ANY, label = _("draw outline")) self.outlineCheck.SetValue(self.vPropertiesDict['color'] != 'none') widthText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Width (pts):")) if fs: self.widthSpin = fs.FloatSpin(panel, id = wx.ID_ANY, min_val = 0, max_val = 30, increment = 0.5, value = 1, style = fs.FS_RIGHT) self.widthSpin.SetFormat("%f") self.widthSpin.SetDigits(2) else: self.widthSpin = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 1, max = 25, initial = 1, size = self.spinCtrlSize) if self.vPropertiesDict['color'] == None: self.vPropertiesDict['color'] = 'none' if self.vPropertiesDict['color'] != 'none': self.widthSpin.SetValue(self.vPropertiesDict['width'] ) else: self.widthSpin.SetValue(1) colorText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Color:")) self.colorPicker = wx.ColourPickerCtrl(panel, id = wx.ID_ANY) if self.vPropertiesDict['color'] != 'none': self.colorPicker.SetColour(convertRGB(self.vPropertiesDict['color'])) else: self.colorPicker.SetColour(convertRGB('black')) self.gridBagSizerO.Add(self.outlineCheck, pos = (0, 0), span = (1,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.gridBagSizerO.Add(widthText, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.gridBagSizerO.Add(self.widthSpin, pos = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0) self.gridBagSizerO.Add(colorText, pos = (2, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.gridBagSizerO.Add(self.colorPicker, pos = (2, 2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) sizer.Add(self.gridBagSizerO, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5) border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5) self.Bind(wx.EVT_CHECKBOX, self.OnOutline, self.outlineCheck) #colors - fill box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Fill")) sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL) self.gridBagSizerF = wx.GridBagSizer(hgap = 5, vgap = 2) self.fillCheck = wx.CheckBox(panel, id = wx.ID_ANY, label = _("fill color")) self.fillCheck.SetValue(self.vPropertiesDict['fcolor'] != 'none' or self.vPropertiesDict['rgbcolumn'] is not None) self.colorPickerRadio = wx.RadioButton(panel, id = wx.ID_ANY, label = _("choose color:"), style = wx.RB_GROUP) #set choose color option if there is no db connection if self.connection: self.colorPickerRadio.SetValue(not self.vPropertiesDict['rgbcolumn']) else: self.colorPickerRadio.SetValue(False) self.fillColorPicker = wx.ColourPickerCtrl(panel, id = wx.ID_ANY) if self.vPropertiesDict['fcolor'] != 'none': self.fillColorPicker.SetColour(convertRGB(self.vPropertiesDict['fcolor'])) else: self.fillColorPicker.SetColour(convertRGB('red')) self.colorColRadio = wx.RadioButton(panel, id = wx.ID_ANY, label = _("color from map table column:")) self.colorColChoice = self.getColsChoice(parent = panel) if self.connection: if self.vPropertiesDict['rgbcolumn']: self.colorColRadio.SetValue(True) self.colorColChoice.SetStringSelection(self.vPropertiesDict['rgbcolumn']) else: self.colorColRadio.SetValue(False) self.colorColChoice.SetSelection(0) self.colorColChoice.Enable(self.connection) self.colorColRadio.Enable(self.connection) self.gridBagSizerF.Add(self.fillCheck, pos = (0, 0), span = (1,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.gridBagSizerF.Add(self.colorPickerRadio, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.gridBagSizerF.Add(self.fillColorPicker, pos = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.gridBagSizerF.Add(self.colorColRadio, pos = (2, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.gridBagSizerF.Add(self.colorColChoice, pos = (2, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0) sizer.Add(self.gridBagSizerF, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5) border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5) self.Bind(wx.EVT_CHECKBOX, self.OnFill, self.fillCheck) self.Bind(wx.EVT_RADIOBUTTON, self.OnColor, self.colorColRadio) self.Bind(wx.EVT_RADIOBUTTON, self.OnColor, self.colorPickerRadio) panel.SetSizer(border) panel.Fit() return panel def _ColorsLinePanel(self, notebook): panel = wx.Panel(parent = notebook, id = wx.ID_ANY, size = (-1, -1), style = wx.TAB_TRAVERSAL) notebook.AddPage(page = panel, text = _("Colors")) border = wx.BoxSizer(wx.VERTICAL) #colors - outline box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Outline")) sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL) self.gridBagSizerO = wx.GridBagSizer(hgap = 5, vgap = 2) if self.vPropertiesDict['hcolor'] == None: self.vPropertiesDict['hcolor'] = 'none' if self.vPropertiesDict['color'] == None: self.vPropertiesDict['color'] = 'none' self.outlineCheck = wx.CheckBox(panel, id = wx.ID_ANY, label = _("draw outline")) self.outlineCheck.SetValue(self.vPropertiesDict['hcolor'] != 'none') self.outlineCheck.SetToolTipString(_("No effect for fill color from table column")) widthText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Width (pts):")) if fs: self.outWidthSpin = fs.FloatSpin(panel, id = wx.ID_ANY, min_val = 0, max_val = 30, increment = 0.5, value = 1, style = fs.FS_RIGHT) self.outWidthSpin.SetFormat("%f") self.outWidthSpin.SetDigits(1) else: self.outWidthSpin = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 1, max = 30, initial = 1, size = self.spinCtrlSize) if self.vPropertiesDict['hcolor'] != 'none': self.outWidthSpin.SetValue(self.vPropertiesDict['hwidth'] ) else: self.outWidthSpin.SetValue(1) colorText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Color:")) self.colorPicker = wx.ColourPickerCtrl(panel, id = wx.ID_ANY) if self.vPropertiesDict['hcolor'] != 'none': self.colorPicker.SetColour(convertRGB(self.vPropertiesDict['hcolor']) ) else: self.colorPicker.SetColour(convertRGB('black')) self.gridBagSizerO.Add(self.outlineCheck, pos = (0, 0), span = (1,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.gridBagSizerO.Add(widthText, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.gridBagSizerO.Add(self.outWidthSpin, pos = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0) self.gridBagSizerO.Add(colorText, pos = (2, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.gridBagSizerO.Add(self.colorPicker, pos = (2, 2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) sizer.Add(self.gridBagSizerO, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5) border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5) self.Bind(wx.EVT_CHECKBOX, self.OnOutline, self.outlineCheck) #colors - fill box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Fill")) sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL) self.gridBagSizerF = wx.GridBagSizer(hgap = 5, vgap = 2) fillText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Color of lines:")) self.colorPickerRadio = wx.RadioButton(panel, id = wx.ID_ANY, label = _("choose color:"), style = wx.RB_GROUP) #set choose color option if there is no db connection if self.connection: self.colorPickerRadio.SetValue(not self.vPropertiesDict['rgbcolumn']) else: self.colorPickerRadio.SetValue(False) self.fillColorPicker = wx.ColourPickerCtrl(panel, id = wx.ID_ANY) if self.vPropertiesDict['color'] != 'none': self.fillColorPicker.SetColour(convertRGB(self.vPropertiesDict['color']) ) else: self.fillColorPicker.SetColour(convertRGB('black')) self.colorColRadio = wx.RadioButton(panel, id = wx.ID_ANY, label = _("color from map table column:")) self.colorColChoice = self.getColsChoice(parent = panel) if self.connection: if self.vPropertiesDict['rgbcolumn']: self.colorColRadio.SetValue(True) self.colorColChoice.SetStringSelection(self.vPropertiesDict['rgbcolumn']) else: self.colorColRadio.SetValue(False) self.colorColChoice.SetSelection(0) self.colorColChoice.Enable(self.connection) self.colorColRadio.Enable(self.connection) self.gridBagSizerF.Add(fillText, pos = (0, 0), span = (1,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.gridBagSizerF.Add(self.colorPickerRadio, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.gridBagSizerF.Add(self.fillColorPicker, pos = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.gridBagSizerF.Add(self.colorColRadio, pos = (2, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.gridBagSizerF.Add(self.colorColChoice, pos = (2, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0) sizer.Add(self.gridBagSizerF, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5) border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5) self.Bind(wx.EVT_RADIOBUTTON, self.OnColor, self.colorColRadio) self.Bind(wx.EVT_RADIOBUTTON, self.OnColor, self.colorPickerRadio) panel.SetSizer(border) panel.Fit() return panel def _StylePointPanel(self, notebook): panel = wx.Panel(parent = notebook, id = wx.ID_ANY, size = (-1, -1), style = wx.TAB_TRAVERSAL) notebook.AddPage(page = panel, text = _("Size and style")) border = wx.BoxSizer(wx.VERTICAL) #symbology box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Symbology")) sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL) gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5) gridBagSizer.AddGrowableCol(1) self.symbolRadio = wx.RadioButton(panel, id = wx.ID_ANY, label = _("symbol:"), style = wx.RB_GROUP) self.symbolRadio.SetValue(bool(self.vPropertiesDict['symbol'])) self.symbolChoice = wx.Choice(panel, id = wx.ID_ANY, choices = self.symbols) self.epsRadio = wx.RadioButton(panel, id = wx.ID_ANY, label = _("eps file:")) self.epsRadio.SetValue(bool(self.vPropertiesDict['eps'])) self.epsFileCtrl = filebrowse.FileBrowseButton(panel, id = wx.ID_ANY, labelText = '', buttonText = _("Browse"), toolTip = _("Type filename or click browse to choose file"), dialogTitle = _("Choose a file"), startDirectory = '', initialValue = '', fileMask = "Encapsulated PostScript (*.eps)|*.eps|All files (*.*)|*.*", fileMode = wx.OPEN) if self.vPropertiesDict['symbol']: self.symbolChoice.SetStringSelection(self.vPropertiesDict['symbol']) self.epsFileCtrl.SetValue('') else: #eps chosen self.epsFileCtrl.SetValue(self.vPropertiesDict['eps']) self.symbolChoice.SetSelection(0) gridBagSizer.Add(self.symbolRadio, pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.symbolChoice, pos = (0, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.epsRadio, pos = (1, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.epsFileCtrl, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0) sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5) border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5) #size box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Size")) sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL) gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5) gridBagSizer.AddGrowableCol(0) self.sizeRadio = wx.RadioButton(panel, id = wx.ID_ANY, label = _("size:"), style = wx.RB_GROUP) self.sizeSpin = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 1, max = 50, initial = 1) self.sizecolumnRadio = wx.RadioButton(panel, id = wx.ID_ANY, label = _("size from map table column:")) self.sizeColChoice = self.getColsChoice(panel) self.scaleText = wx.StaticText(panel, id = wx.ID_ANY, label = _("scale:")) self.scaleSpin = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 1, max = 25, initial = 1) self.sizeRadio.SetValue(self.vPropertiesDict['size'] is not None) self.sizecolumnRadio.SetValue(bool(self.vPropertiesDict['sizecolumn'])) if self.vPropertiesDict['size']: self.sizeSpin.SetValue(self.vPropertiesDict['size']) else: self.sizeSpin.SetValue(5) if self.vPropertiesDict['sizecolumn']: self.scaleSpin.SetValue(self.vPropertiesDict['scale']) self.sizeColChoice.SetStringSelection(self.vPropertiesDict['sizecolumn']) else: self.scaleSpin.SetValue(1) self.sizeColChoice.SetSelection(0) if not self.connection: for each in (self.sizecolumnRadio, self.sizeColChoice, self.scaleSpin, self.scaleText): each.Disable() gridBagSizer.Add(self.sizeRadio, pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.sizeSpin, pos = (0, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.sizecolumnRadio, pos = (1, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.sizeColChoice, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0) gridBagSizer.Add(self.scaleText, pos = (2, 0), flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, border = 0) gridBagSizer.Add(self.scaleSpin, pos = (2, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5) border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5) self.Bind(wx.EVT_RADIOBUTTON, self.OnSize, self.sizeRadio) self.Bind(wx.EVT_RADIOBUTTON, self.OnSize, self.sizecolumnRadio) #rotation box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Rotation")) sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL) gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5) gridBagSizer.AddGrowableCol(1) self.rotateCheck = wx.CheckBox(panel, id = wx.ID_ANY, label = _("rotate symbols:")) self.rotateRadio = wx.RadioButton(panel, id = wx.ID_ANY, label = _("counterclockwise in degrees:"), style = wx.RB_GROUP) self.rotateSpin = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 0, max = 360, initial = 0) self.rotatecolumnRadio = wx.RadioButton(panel, id = wx.ID_ANY, label = _("from map table column:")) self.rotateColChoice = self.getColsChoice(panel) self.rotateCheck.SetValue(self.vPropertiesDict['rotation']) self.rotateRadio.SetValue(self.vPropertiesDict['rotate'] is not None) self.rotatecolumnRadio.SetValue(bool(self.vPropertiesDict['rotatecolumn'])) if self.vPropertiesDict['rotate']: self.rotateSpin.SetValue(self.vPropertiesDict['rotate']) else: self.rotateSpin.SetValue(0) if self.vPropertiesDict['rotatecolumn']: self.rotateColChoice.SetStringSelection(self.vPropertiesDict['rotatecolumn']) else: self.rotateColChoice.SetSelection(0) gridBagSizer.Add(self.rotateCheck, pos = (0, 0), span = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.rotateRadio, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.rotateSpin, pos = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.rotatecolumnRadio, pos = (2, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.rotateColChoice, pos = (2, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0) sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5) border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5) self.Bind(wx.EVT_CHECKBOX, self.OnRotation, self.rotateCheck) self.Bind(wx.EVT_RADIOBUTTON, self.OnRotationType, self.rotateRadio) self.Bind(wx.EVT_RADIOBUTTON, self.OnRotationType, self.rotatecolumnRadio) panel.SetSizer(border) panel.Fit() return panel def _StyleLinePanel(self, notebook): panel = wx.Panel(parent = notebook, id = wx.ID_ANY, size = (-1, -1), style = wx.TAB_TRAVERSAL) notebook.AddPage(page = panel, text = _("Size and style")) border = wx.BoxSizer(wx.VERTICAL) #width box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Width")) sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL) gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5) widthText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Set width (pts):")) if fs: self.widthSpin = fs.FloatSpin(panel, id = wx.ID_ANY, min_val = 0, max_val = 30, increment = 0.5, value = 1, style = fs.FS_RIGHT) self.widthSpin.SetFormat("%f") self.widthSpin.SetDigits(1) else: self.widthSpin = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 1, max = 30, initial = 1) self.cwidthCheck = wx.CheckBox(panel, id = wx.ID_ANY, label = _("multiply width by category value")) if self.vPropertiesDict['width']: self.widthSpin.SetValue(self.vPropertiesDict['width']) self.cwidthCheck.SetValue(False) else: self.widthSpin.SetValue(self.vPropertiesDict['cwidth']) self.cwidthCheck.SetValue(True) gridBagSizer.Add(widthText, pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.widthSpin, pos = (0, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.cwidthCheck, pos = (1, 0), span = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5) border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5) #style box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Line style")) sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL) gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5) styleText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Choose line style:")) penStyles = ["solid", "dashed", "dotted", "dashdotted"] self.styleCombo = PenStyleComboBox(panel, choices = penStyles, validator = TCValidator(flag = 'ZERO_AND_ONE_ONLY')) ## self.styleCombo = wx.ComboBox(panel, id = wx.ID_ANY, ## choices = ["solid", "dashed", "dotted", "dashdotted"], ## validator = TCValidator(flag = 'ZERO_AND_ONE_ONLY')) ## self.styleCombo.SetToolTipString(_("It's possible to enter a series of 0's and 1's too. "\ ## "The first block of repeated zeros or ones represents 'draw', "\ ## "the second block represents 'blank'. An even number of blocks "\ ## "will repeat the pattern, an odd number of blocks will alternate the pattern.")) linecapText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Choose linecap:")) self.linecapChoice = wx.Choice(panel, id = wx.ID_ANY, choices = ["butt", "round", "extended_butt"]) self.styleCombo.SetValue(self.vPropertiesDict['style']) self.linecapChoice.SetStringSelection(self.vPropertiesDict['linecap']) gridBagSizer.Add(styleText, pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.styleCombo, pos = (0, 1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0) gridBagSizer.Add(linecapText, pos = (1, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.linecapChoice, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0) sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5) border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5) panel.SetSizer(border) panel.Fit() return panel def _StyleAreaPanel(self, notebook): panel = wx.Panel(parent = notebook, id = wx.ID_ANY, size = (-1, -1), style = wx.TAB_TRAVERSAL) notebook.AddPage(page = panel, text = _("Size and style")) border = wx.BoxSizer(wx.VERTICAL) #pattern box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Pattern")) sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL) gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5) gridBagSizer.AddGrowableCol(1) self.patternCheck = wx.CheckBox(panel, id = wx.ID_ANY, label = _("use pattern:")) self.patFileCtrl = filebrowse.FileBrowseButton(panel, id = wx.ID_ANY, labelText = _("Choose pattern file:"), buttonText = _("Browse"), toolTip = _("Type filename or click browse to choose file"), dialogTitle = _("Choose a file"), startDirectory = self.patternPath, initialValue = '', fileMask = "Encapsulated PostScript (*.eps)|*.eps|All files (*.*)|*.*", fileMode = wx.OPEN) self.patWidthText = wx.StaticText(panel, id = wx.ID_ANY, label = _("pattern line width (pts):")) self.patWidthSpin = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 1, max = 25, initial = 1) self.patScaleText = wx.StaticText(panel, id = wx.ID_ANY, label = _("pattern scale factor:")) self.patScaleSpin = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 1, max = 25, initial = 1) self.patternCheck.SetValue(bool(self.vPropertiesDict['pat'])) if self.patternCheck.GetValue(): self.patFileCtrl.SetValue(self.vPropertiesDict['pat']) self.patWidthSpin.SetValue(self.vPropertiesDict['pwidth']) self.patScaleSpin.SetValue(self.vPropertiesDict['scale']) gridBagSizer.Add(self.patternCheck, pos = (0, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.patFileCtrl, pos = (1, 0), span = (1, 2),flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0) gridBagSizer.Add(self.patWidthText, pos = (2, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.patWidthSpin, pos = (2, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.patScaleText, pos = (3, 0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.patScaleSpin, pos = (3, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5) border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5) self.Bind(wx.EVT_CHECKBOX, self.OnPattern, self.patternCheck) panel.SetSizer(border) panel.Fit() return panel def OnLayer(self, event): """!Change columns on layer change """ if self.layerChoice.GetStringSelection() == self.currLayer: return self.currLayer = self.layerChoice.GetStringSelection() if self.connection: cols = self.mapDBInfo.GetColumns(self.mapDBInfo.layers[int(self.currLayer)]['table']) else: cols = [] self.choiceColumns.SetItems(cols) self.choiceColumns.SetSelection(0) if self.type in ('points', 'lines'): self.colorColChoice.SetItems(cols) self.colorColChoice.SetSelection(0) def OnOutline(self, event): for widget in self.gridBagSizerO.GetChildren(): if widget.GetWindow() != self.outlineCheck: widget.GetWindow().Enable(self.outlineCheck.GetValue()) def OnFill(self, event): enable = self.fillCheck.GetValue() self.colorColChoice.Enable(enable) self.colorColRadio.Enable(enable) self.fillColorPicker.Enable(enable) self.colorPickerRadio.Enable(enable) if enable: self.OnColor(None) if not self.connection: self.colorColChoice.Disable() self.colorColRadio.Disable() def OnColor(self, event): self.colorColChoice.Enable(self.colorColRadio.GetValue()) self.fillColorPicker.Enable(self.colorPickerRadio.GetValue()) def OnSize(self, event): self.sizeSpin.Enable(self.sizeRadio.GetValue()) self.sizeColChoice.Enable(self.sizecolumnRadio.GetValue()) self.scaleText.Enable(self.sizecolumnRadio.GetValue()) self.scaleSpin.Enable(self.sizecolumnRadio.GetValue()) def OnRotation(self, event): for each in (self.rotateRadio, self.rotatecolumnRadio, self.rotateColChoice, self.rotateSpin): if self.rotateCheck.GetValue(): each.Enable() self.OnRotationType(event = None) else: each.Disable() def OnRotationType(self, event): self.rotateSpin.Enable(self.rotateRadio.GetValue()) self.rotateColChoice.Enable(self.rotatecolumnRadio.GetValue()) def OnPattern(self, event): for each in (self.patFileCtrl, self.patWidthText, self.patWidthSpin, self.patScaleText, self.patScaleSpin): each.Enable(self.patternCheck.GetValue()) def EnableLayerSelection(self, enable = True): for widget in self.gridBagSizerL.GetChildren(): if widget.GetWindow() != self.warning: widget.GetWindow().Enable(enable) def getColsChoice(self, parent): """!Returns a wx.Choice with table columns""" if self.connection: cols = self.mapDBInfo.GetColumns(self.mapDBInfo.layers[int(self.currLayer)]['table']) else: cols = [] choice = wx.Choice(parent = parent, id = wx.ID_ANY, choices = cols) return choice def update(self): #feature type if self.type in ('lines', 'points'): featureType = None if self.checkType1.GetValue(): featureType = self.checkType1.GetName() if self.checkType2.GetValue(): featureType += " or " + self.checkType2.GetName() elif self.checkType2.GetValue(): featureType = self.checkType2.GetName() if featureType: self.vPropertiesDict['type'] = featureType # is connection self.vPropertiesDict['connection'] = self.connection if self.connection: self.vPropertiesDict['layer'] = self.layerChoice.GetStringSelection() if self.radioCats.GetValue() and not self.textCtrlCats.IsEmpty(): self.vPropertiesDict['cats'] = self.textCtrlCats.GetValue() elif self.radioWhere.GetValue() and not self.textCtrlWhere.IsEmpty(): self.vPropertiesDict['where'] = self.choiceColumns.GetStringSelection() + " " \ + self.textCtrlWhere.GetValue() #mask if self.mask.GetValue(): self.vPropertiesDict['masked'] = 'y' else: self.vPropertiesDict['masked'] = 'n' #colors if self.type in ('points', 'areas'): if self.outlineCheck.GetValue(): self.vPropertiesDict['color'] = convertRGB(self.colorPicker.GetColour()) self.vPropertiesDict['width'] = self.widthSpin.GetValue() else: self.vPropertiesDict['color'] = 'none' if self.fillCheck.GetValue(): if self.colorPickerRadio.GetValue(): self.vPropertiesDict['fcolor'] = convertRGB(self.fillColorPicker.GetColour()) self.vPropertiesDict['rgbcolumn'] = None if self.colorColRadio.GetValue(): self.vPropertiesDict['fcolor'] = 'none'# this color is taken in case of no record in rgb column self.vPropertiesDict['rgbcolumn'] = self.colorColChoice.GetStringSelection() else: self.vPropertiesDict['fcolor'] = 'none' if self.type == 'lines': #hcolor only when no rgbcolumn if self.outlineCheck.GetValue():# and self.fillCheck.GetValue() and self.colorColRadio.GetValue(): self.vPropertiesDict['hcolor'] = convertRGB(self.colorPicker.GetColour()) self.vPropertiesDict['hwidth'] = self.outWidthSpin.GetValue() else: self.vPropertiesDict['hcolor'] = 'none' if self.colorPickerRadio.GetValue(): self.vPropertiesDict['color'] = convertRGB(self.fillColorPicker.GetColour()) self.vPropertiesDict['rgbcolumn'] = None if self.colorColRadio.GetValue(): self.vPropertiesDict['color'] = 'none'# this color is taken in case of no record in rgb column self.vPropertiesDict['rgbcolumn'] = self.colorColChoice.GetStringSelection() # #size and style # if self.type == 'points': #symbols if self.symbolRadio.GetValue(): self.vPropertiesDict['symbol'] = self.symbolChoice.GetStringSelection() self.vPropertiesDict['eps'] = None else: self.vPropertiesDict['eps'] = self.epsFileCtrl.GetValue() self.vPropertiesDict['symbol'] = None #size if self.sizeRadio.GetValue(): self.vPropertiesDict['size'] = self.sizeSpin.GetValue() self.vPropertiesDict['sizecolumn'] = None self.vPropertiesDict['scale'] = None else: self.vPropertiesDict['sizecolumn'] = self.sizeColChoice.GetStringSelection() self.vPropertiesDict['scale'] = self.scaleSpin.GetValue() self.vPropertiesDict['size'] = None #rotation self.vPropertiesDict['rotate'] = None self.vPropertiesDict['rotatecolumn'] = None self.vPropertiesDict['rotation'] = False if self.rotateCheck.GetValue(): self.vPropertiesDict['rotation'] = True if self.rotateRadio.GetValue(): self.vPropertiesDict['rotate'] = self.rotateSpin.GetValue() else: self.vPropertiesDict['rotatecolumn'] = self.rotateColChoice.GetStringSelection() if self.type == 'areas': #pattern self.vPropertiesDict['pat'] = None if self.patternCheck.GetValue() and bool(self.patFileCtrl.GetValue()): self.vPropertiesDict['pat'] = self.patFileCtrl.GetValue() self.vPropertiesDict['pwidth'] = self.patWidthSpin.GetValue() self.vPropertiesDict['scale'] = self.patScaleSpin.GetValue() if self.type == 'lines': #width if self.cwidthCheck.GetValue(): self.vPropertiesDict['cwidth'] = self.widthSpin.GetValue() self.vPropertiesDict['width'] = None else: self.vPropertiesDict['width'] = self.widthSpin.GetValue() self.vPropertiesDict['cwidth'] = None #line style if self.styleCombo.GetValue(): self.vPropertiesDict['style'] = self.styleCombo.GetValue() else: self.vPropertiesDict['style'] = 'solid' self.vPropertiesDict['linecap'] = self.linecapChoice.GetStringSelection() def OnOK(self, event): self.update() event.Skip() class LegendDialog(PsmapDialog): def __init__(self, parent, id, settings, page): PsmapDialog.__init__(self, parent = parent, id = id, title = "Legend settings", settings = settings) self.objectType = ('rasterLegend', 'vectorLegend') self.instruction = settings map = self.instruction.FindInstructionByType('map') if map: self.mapId = map.id else: self.mapId = None vector = self.instruction.FindInstructionByType('vector') if vector: self.vectorId = vector.id else: self.vectorId = None raster = self.instruction.FindInstructionByType('raster') if raster: self.rasterId = raster.id else: self.rasterId = None self.pageId = self.instruction.FindInstructionByType('page').id currPage = self.instruction[self.pageId].GetInstruction() #raster legend if self.id[0] is not None: self.rasterLegend = self.instruction[self.id[0]] self.rLegendDict = self.rasterLegend.GetInstruction() else: self.id[0] = wx.NewId() self.rasterLegend = RasterLegend(self.id[0]) self.rLegendDict = self.rasterLegend.GetInstruction() self.rLegendDict['where'] = currPage['Left'], currPage['Top'] #vector legend if self.id[1] is not None: self.vLegendDict = self.instruction[self.id[1]].GetInstruction() else: self.id[1] = wx.NewId() vectorLegend = VectorLegend(self.id[1]) self.vLegendDict = vectorLegend.GetInstruction() self.vLegendDict['where'] = currPage['Left'], currPage['Top'] if self.rasterId: self.currRaster = self.instruction[self.rasterId]['raster'] else: self.currRaster = None #notebook self.notebook = wx.Notebook(parent = self, id = wx.ID_ANY, style = wx.BK_DEFAULT) self.panelRaster = self._rasterLegend(self.notebook) self.panelVector = self._vectorLegend(self.notebook) self.OnRaster(None) self.OnRange(None) self.OnIsLegend(None) self.OnSpan(None) self.OnBorder(None) self._layout(self.notebook) self.notebook.ChangeSelection(page) self.notebook.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGING, self.OnPageChanging) def OnPageChanging(self, event): """!Workaround to scroll up to see the checkbox""" wx.CallAfter(self.FindWindowByName('rasterPanel').ScrollChildIntoView, self.FindWindowByName('showRLegend')) wx.CallAfter(self.FindWindowByName('vectorPanel').ScrollChildIntoView, self.FindWindowByName('showVLegend')) def _rasterLegend(self, notebook): panel = scrolled.ScrolledPanel(parent = notebook, id = wx.ID_ANY, size = (-1, 500), style = wx.TAB_TRAVERSAL) panel.SetupScrolling(scroll_x = False, scroll_y = True) panel.SetName('rasterPanel') notebook.AddPage(page = panel, text = _("Raster legend")) border = wx.BoxSizer(wx.VERTICAL) # is legend self.isRLegend = wx.CheckBox(panel, id = wx.ID_ANY, label = _("Show raster legend")) self.isRLegend.SetValue(self.rLegendDict['rLegend']) self.isRLegend.SetName("showRLegend") border.Add(item = self.isRLegend, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5) # choose raster box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Source raster")) sizer = wx.StaticBoxSizer(box, wx.VERTICAL) flexSizer = wx.FlexGridSizer (cols = 2, hgap = 5, vgap = 5) flexSizer.AddGrowableCol(1) self.rasterDefault = wx.RadioButton(panel, id = wx.ID_ANY, label = _("current raster"), style = wx.RB_GROUP) self.rasterOther = wx.RadioButton(panel, id = wx.ID_ANY, label = _("select raster")) self.rasterDefault.SetValue(self.rLegendDict['rasterDefault'])# self.rasterOther.SetValue(not self.rLegendDict['rasterDefault'])# rasterType = getRasterType(map = self.currRaster) self.rasterCurrent = wx.StaticText(panel, id = wx.ID_ANY, label = _("%(rast)s: type %(type)s") % { 'rast' : self.currRaster, 'type' : rasterType }) self.rasterSelect = Select(panel, id = wx.ID_ANY, size = globalvar.DIALOG_GSELECT_SIZE, type = 'raster', multiple = False, updateOnPopup = True, onPopup = None) if not self.rLegendDict['rasterDefault']: self.rasterSelect.SetValue(self.rLegendDict['raster']) else: self.rasterSelect.SetValue('') flexSizer.Add(self.rasterDefault, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0) flexSizer.Add(self.rasterCurrent, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.LEFT, border = 10) flexSizer.Add(self.rasterOther, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0) flexSizer.Add(self.rasterSelect, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, border = 0) sizer.Add(item = flexSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1) border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5) # type of legend box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Type of legend")) sizer = wx.StaticBoxSizer(box, wx.VERTICAL) vbox = wx.BoxSizer(wx.VERTICAL) self.discrete = wx.RadioButton(parent = panel, id = wx.ID_ANY, label = " %s " % _("discrete legend (categorical maps)"), style = wx.RB_GROUP) self.continuous = wx.RadioButton(parent = panel, id = wx.ID_ANY, label = " %s " % _("continuous color gradient legend (floating point map)")) vbox.Add(self.discrete, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 0) vbox.Add(self.continuous, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 0) sizer.Add(item = vbox, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1) border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5) # size, position and font self.sizePositionFont(legendType = 'raster', parent = panel, mainSizer = border) # advanced settings box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Advanced legend settings")) sizer = wx.StaticBoxSizer(box, wx.VERTICAL) gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5) # no data self.nodata = wx.CheckBox(panel, id = wx.ID_ANY, label = _('draw "no data" box')) if self.rLegendDict['nodata'] == 'y': self.nodata.SetValue(True) else: self.nodata.SetValue(False) #tickbar self.ticks = wx.CheckBox(panel, id = wx.ID_ANY, label = _("draw ticks across color table")) if self.rLegendDict['tickbar'] == 'y': self.ticks.SetValue(True) else: self.ticks.SetValue(False) # range if self.rasterId and self.instruction[self.rasterId]['raster']: rinfo = grass.raster_info(self.instruction[self.rasterId]['raster']) self.minim, self.maxim = rinfo['min'], rinfo['max'] else: self.minim, self.maxim = 0,0 self.range = wx.CheckBox(panel, id = wx.ID_ANY, label = _("range")) self.range.SetValue(self.rLegendDict['range']) self.minText = wx.StaticText(panel, id = wx.ID_ANY, label = "min (%s)" % self.minim) self.maxText = wx.StaticText(panel, id = wx.ID_ANY, label = "max (%s)" % self.maxim) self.min = wx.TextCtrl(panel, id = wx.ID_ANY, value = str(self.rLegendDict['min'])) self.max = wx.TextCtrl(panel, id = wx.ID_ANY, value = str(self.rLegendDict['max'])) gridBagSizer.Add(self.nodata, pos = (0,0), span = (1,5), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.ticks, pos = (1,0), span = (1,5), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.range, pos = (2,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.minText, pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, border = 0) gridBagSizer.Add(self.min, pos = (2,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.maxText, pos = (2,3), flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT, border = 0) gridBagSizer.Add(self.max, pos = (2,4), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) sizer.Add(gridBagSizer, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0) border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5) panel.SetSizer(border) panel.Fit() # bindings self.Bind(wx.EVT_RADIOBUTTON, self.OnRaster, self.rasterDefault) self.Bind(wx.EVT_RADIOBUTTON, self.OnRaster, self.rasterOther) self.Bind(wx.EVT_CHECKBOX, self.OnIsLegend, self.isRLegend) self.Bind(wx.EVT_RADIOBUTTON, self.OnDiscrete, self.discrete) self.Bind(wx.EVT_RADIOBUTTON, self.OnDiscrete, self.continuous) ## self.Bind(wx.EVT_CHECKBOX, self.OnDefaultSize, panel.defaultSize) self.Bind(wx.EVT_CHECKBOX, self.OnRange, self.range) self.rasterSelect.GetTextCtrl().Bind(wx.EVT_TEXT, self.OnRaster) return panel def _vectorLegend(self, notebook): panel = scrolled.ScrolledPanel(parent = notebook, id = wx.ID_ANY, size = (-1, 500), style = wx.TAB_TRAVERSAL) panel.SetupScrolling(scroll_x = False, scroll_y = True) panel.SetName('vectorPanel') notebook.AddPage(page = panel, text = _("Vector legend")) border = wx.BoxSizer(wx.VERTICAL) # is legend self.isVLegend = wx.CheckBox(panel, id = wx.ID_ANY, label = _("Show vector legend")) self.isVLegend.SetValue(self.vLegendDict['vLegend']) self.isVLegend.SetName("showVLegend") border.Add(item = self.isVLegend, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5) #vector maps, their order, labels box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Source vector maps")) sizer = wx.StaticBoxSizer(box, wx.VERTICAL) gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5) gridBagSizer.AddGrowableCol(0,3) gridBagSizer.AddGrowableCol(1,1) vectorText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Choose vector maps and their order in legend")) self.vectorListCtrl = CheckListCtrl(panel) self.vectorListCtrl.InsertColumn(0, _("Vector map")) self.vectorListCtrl.InsertColumn(1, _("Label")) if self.vectorId: vectors = sorted(self.instruction[self.vectorId]['list'], key = lambda x: x[3]) for vector in vectors: index = self.vectorListCtrl.InsertStringItem(sys.maxint, vector[0].split('@')[0]) self.vectorListCtrl.SetStringItem(index, 1, vector[4]) self.vectorListCtrl.SetItemData(index, index) self.vectorListCtrl.CheckItem(index, True) if vector[3] == 0: self.vectorListCtrl.CheckItem(index, False) if not self.vectorId: self.vectorListCtrl.SetColumnWidth(0, 100) else: self.vectorListCtrl.SetColumnWidth(0, wx.LIST_AUTOSIZE) self.vectorListCtrl.SetColumnWidth(1, wx.LIST_AUTOSIZE) self.btnUp = wx.Button(panel, id = wx.ID_ANY, label = _("Up")) self.btnDown = wx.Button(panel, id = wx.ID_ANY, label = _("Down")) self.btnLabel = wx.Button(panel, id = wx.ID_ANY, label = _("Edit label")) gridBagSizer.Add(vectorText, pos = (0,0), span = (1,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.vectorListCtrl, pos = (1,0), span = (3,1), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0) gridBagSizer.Add(self.btnUp, pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.btnDown, pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.btnLabel, pos = (3,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) sizer.Add(gridBagSizer, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0) border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5) # size, position and font self.sizePositionFont(legendType = 'vector', parent = panel, mainSizer = border) # border box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Border")) sizer = wx.StaticBoxSizer(box, wx.VERTICAL) flexGridSizer = wx.FlexGridSizer(cols = 2, hgap = 5, vgap = 5) self.borderCheck = wx.CheckBox(panel, id = wx.ID_ANY, label = _("draw border around legend")) self.borderColorCtrl = wx.ColourPickerCtrl(panel, id = wx.ID_ANY, style = wx.FNTP_FONTDESC_AS_LABEL) if self.vLegendDict['border'] == 'none': self.borderColorCtrl.SetColour(wx.BLACK) self.borderCheck.SetValue(False) else: self.borderColorCtrl.SetColour(convertRGB(self.vLegendDict['border'])) self.borderCheck.SetValue(True) flexGridSizer.Add(self.borderCheck, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0) flexGridSizer.Add(self.borderColorCtrl, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0) sizer.Add(item = flexGridSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1) border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5) self.Bind(wx.EVT_BUTTON, self.OnUp, self.btnUp) self.Bind(wx.EVT_BUTTON, self.OnDown, self.btnDown) self.Bind(wx.EVT_BUTTON, self.OnEditLabel, self.btnLabel) self.Bind(wx.EVT_CHECKBOX, self.OnIsLegend, self.isVLegend) self.Bind(wx.EVT_CHECKBOX, self.OnSpan, panel.spanRadio) self.Bind(wx.EVT_CHECKBOX, self.OnBorder, self.borderCheck) self.Bind(wx.EVT_FONTPICKER_CHANGED, self.OnFont, panel.font['fontCtrl']) panel.SetSizer(border) panel.Fit() return panel def sizePositionFont(self, legendType, parent, mainSizer): """!Insert widgets for size, position and font control""" if legendType == 'raster': legendDict = self.rLegendDict else: legendDict = self.vLegendDict panel = parent border = mainSizer # size and position box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Size and position")) sizer = wx.StaticBoxSizer(box, wx.VERTICAL) #unit self.AddUnits(parent = panel, dialogDict = legendDict) unitBox = wx.BoxSizer(wx.HORIZONTAL) unitBox.Add(panel.units['unitsLabel'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.LEFT, border = 10) unitBox.Add(panel.units['unitsCtrl'], proportion = 1, flag = wx.ALL, border = 5) sizer.Add(unitBox, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0) hBox = wx.BoxSizer(wx.HORIZONTAL) posBox = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " %_("Position")) posSizer = wx.StaticBoxSizer(posBox, wx.VERTICAL) sizeBox = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Size")) sizeSizer = wx.StaticBoxSizer(sizeBox, wx.VERTICAL) posGridBagSizer = wx.GridBagSizer(hgap = 10, vgap = 5) posGridBagSizer.AddGrowableRow(2) #position self.AddPosition(parent = panel, dialogDict = legendDict) posGridBagSizer.Add(panel.position['xLabel'], pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) posGridBagSizer.Add(panel.position['xCtrl'], pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) posGridBagSizer.Add(panel.position['yLabel'], pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) posGridBagSizer.Add(panel.position['yCtrl'], pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) posGridBagSizer.Add(panel.position['comment'], pos = (2,0), span = (1,2), flag =wx.ALIGN_BOTTOM, border = 0) posSizer.Add(posGridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5) #size width = wx.StaticText(panel, id = wx.ID_ANY, label = _("Width:")) if legendDict['width']: w = self.unitConv.convert(value = float(legendDict['width']), fromUnit = 'inch', toUnit = legendDict['unit']) else: w = '' panel.widthCtrl = wx.TextCtrl(panel, id = wx.ID_ANY, value = str(w), validator = TCValidator("DIGIT_ONLY")) panel.widthCtrl.SetToolTipString(_("Leave the edit field empty, to use default values.")) if legendType == 'raster': ## panel.defaultSize = wx.CheckBox(panel, id = wx.ID_ANY, label = _("Use default size")) ## panel.defaultSize.SetValue(legendDict['defaultSize']) panel.heightOrColumnsLabel = wx.StaticText(panel, id = wx.ID_ANY, label = _("Height:")) if legendDict['height']: h = self.unitConv.convert(value = float(legendDict['height']), fromUnit = 'inch', toUnit = legendDict['unit']) else: h = '' panel.heightOrColumnsCtrl = wx.TextCtrl(panel, id = wx.ID_ANY, value = str(h), validator = TCValidator("DIGIT_ONLY")) self.rSizeGBSizer = wx.GridBagSizer(hgap = 5, vgap = 5) ## self.rSizeGBSizer.Add(panel.defaultSize, pos = (0,0), span = (1,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.rSizeGBSizer.Add(width, pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.rSizeGBSizer.Add(panel.widthCtrl, pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.rSizeGBSizer.Add(panel.heightOrColumnsLabel, pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.rSizeGBSizer.Add(panel.heightOrColumnsCtrl, pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) sizeSizer.Add(self.rSizeGBSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5) if legendType == 'vector': panel.widthCtrl.SetToolTipString(_("Width of the color symbol (for lines)\nin front of the legend text")) #columns minVect, maxVect = 0, 0 if self.vectorId: minVect = 1 maxVect = min(10, len(self.instruction[self.vectorId]['list'])) cols = wx.StaticText(panel, id = wx.ID_ANY, label = _("Columns:")) panel.colsCtrl = wx.SpinCtrl(panel, id = wx.ID_ANY, value = "", min = minVect, max = maxVect, initial = legendDict['cols']) #span panel.spanRadio = wx.CheckBox(panel, id = wx.ID_ANY, label = _("column span:")) panel.spanTextCtrl = wx.TextCtrl(panel, id = wx.ID_ANY, value = '') panel.spanTextCtrl.SetToolTipString(_("Column separation distance between the left edges\n"\ "of two columns in a multicolumn legend")) if legendDict['span']: panel.spanRadio.SetValue(True) s = self.unitConv.convert(value = float(legendDict['span']), fromUnit = 'inch', toUnit = legendDict['unit']) panel.spanTextCtrl.SetValue(str(s)) else: panel.spanRadio.SetValue(False) self.vSizeGBSizer = wx.GridBagSizer(hgap = 5, vgap = 5) self.vSizeGBSizer.AddGrowableCol(1) self.vSizeGBSizer.Add(width, pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.vSizeGBSizer.Add(panel.widthCtrl, pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.vSizeGBSizer.Add(cols, pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.vSizeGBSizer.Add(panel.colsCtrl, pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.vSizeGBSizer.Add(panel.spanRadio, pos = (2,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.vSizeGBSizer.Add(panel.spanTextCtrl, pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) sizeSizer.Add(self.vSizeGBSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5) hBox.Add(posSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 3) hBox.Add(sizeSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 3) sizer.Add(hBox, proportion = 0, flag = wx.EXPAND, border = 0) border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5) # font box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Font settings")) fontSizer = wx.StaticBoxSizer(box, wx.VERTICAL) flexSizer = wx.FlexGridSizer (cols = 2, hgap = 5, vgap = 5) flexSizer.AddGrowableCol(1) if legendType == 'raster': self.AddFont(parent = panel, dialogDict = legendDict, color = True) else: self.AddFont(parent = panel, dialogDict = legendDict, color = False) flexSizer.Add(panel.font['fontLabel'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0) flexSizer.Add(panel.font['fontCtrl'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0) flexSizer.Add(panel.font['fontSizeLabel'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0) flexSizer.Add(panel.font['fontSizeCtrl'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0) if legendType == 'raster': flexSizer.Add(panel.font['colorLabel'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0) flexSizer.Add(panel.font['colorCtrl'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0) fontSizer.Add(item = flexSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1) border.Add(item = fontSizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5) # some enable/disable methods def OnIsLegend(self, event): """!Enables and disables controls, it depends if raster or vector legend is checked""" page = self.notebook.GetSelection() if page == 0 or event is None: children = self.panelRaster.GetChildren() if self.isRLegend.GetValue(): for i,widget in enumerate(children): widget.Enable() self.OnRaster(None) self.OnRange(None) self.OnDiscrete(None) else: for widget in children: if widget.GetName() != 'showRLegend': widget.Disable() if page == 1 or event is None: children = self.panelVector.GetChildren() if self.isVLegend.GetValue(): for i, widget in enumerate(children): widget.Enable() self.OnSpan(None) self.OnBorder(None) else: for widget in children: if widget.GetName() != 'showVLegend': widget.Disable() def OnRaster(self, event): if self.rasterDefault.GetValue():#default self.rasterSelect.Disable() type = getRasterType(self.currRaster) else:#select raster self.rasterSelect.Enable() map = self.rasterSelect.GetValue() type = getRasterType(map) if type == 'CELL': self.discrete.SetValue(True) elif type in ('FCELL', 'DCELL'): self.continuous.SetValue(True) if event is None: if self.rLegendDict['discrete'] == 'y': self.discrete.SetValue(True) elif self.rLegendDict['discrete'] == 'n': self.continuous.SetValue(True) self.OnDiscrete(None) def OnDiscrete(self, event): """! Change control according to the type of legend""" enabledSize = self.panelRaster.heightOrColumnsCtrl.IsEnabled() self.panelRaster.heightOrColumnsCtrl.Destroy() if self.discrete.GetValue(): self.panelRaster.heightOrColumnsLabel.SetLabel(_("Columns:")) self.panelRaster.heightOrColumnsCtrl = wx.SpinCtrl(self.panelRaster, id = wx.ID_ANY, value = "", min = 1, max = 10, initial = self.rLegendDict['cols']) self.panelRaster.heightOrColumnsCtrl.Enable(enabledSize) self.nodata.Enable() self.range.Disable() self.min.Disable() self.max.Disable() self.minText.Disable() self.maxText.Disable() self.ticks.Disable() else: self.panelRaster.heightOrColumnsLabel.SetLabel(_("Height:")) if self.rLegendDict['height']: h = self.unitConv.convert(value = float(self.rLegendDict['height']), fromUnit = 'inch', toUnit = self.rLegendDict['unit']) else: h = '' self.panelRaster.heightOrColumnsCtrl = wx.TextCtrl(self.panelRaster, id = wx.ID_ANY, value = str(h), validator = TCValidator("DIGIT_ONLY")) self.panelRaster.heightOrColumnsCtrl.Enable(enabledSize) self.nodata.Disable() self.range.Enable() if self.range.GetValue(): self.minText.Enable() self.maxText.Enable() self.min.Enable() self.max.Enable() self.ticks.Enable() self.rSizeGBSizer.Add(self.panelRaster.heightOrColumnsCtrl, pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.panelRaster.Layout() self.panelRaster.Fit() def OnRange(self, event): if not self.range.GetValue(): self.min.Disable() self.max.Disable() self.minText.Disable() self.maxText.Disable() else: self.min.Enable() self.max.Enable() self.minText.Enable() self.maxText.Enable() def OnUp(self, event): """!Moves selected map up, changes order in vector legend""" if self.vectorListCtrl.GetFirstSelected() != -1: pos = self.vectorListCtrl.GetFirstSelected() if pos: idx1 = self.vectorListCtrl.GetItemData(pos) - 1 idx2 = self.vectorListCtrl.GetItemData(pos - 1) + 1 self.vectorListCtrl.SetItemData(pos, idx1) self.vectorListCtrl.SetItemData(pos - 1, idx2) self.vectorListCtrl.SortItems(cmp) if pos > 0: selected = (pos - 1) else: selected = 0 self.vectorListCtrl.Select(selected) def OnDown(self, event): """!Moves selected map down, changes order in vector legend""" if self.vectorListCtrl.GetFirstSelected() != -1: pos = self.vectorListCtrl.GetFirstSelected() if pos != self.vectorListCtrl.GetItemCount() - 1: idx1 = self.vectorListCtrl.GetItemData(pos) + 1 idx2 = self.vectorListCtrl.GetItemData(pos + 1) - 1 self.vectorListCtrl.SetItemData(pos, idx1) self.vectorListCtrl.SetItemData(pos + 1, idx2) self.vectorListCtrl.SortItems(cmp) if pos < self.vectorListCtrl.GetItemCount() -1: selected = (pos + 1) else: selected = self.vectorListCtrl.GetItemCount() -1 self.vectorListCtrl.Select(selected) def OnEditLabel(self, event): """!Change legend label of vector map""" if self.vectorListCtrl.GetFirstSelected() != -1: idx = self.vectorListCtrl.GetFirstSelected() default = self.vectorListCtrl.GetItem(idx, 1).GetText() dlg = wx.TextEntryDialog(self, message = _("Edit legend label:"), caption = _("Edit label"), defaultValue = default, style = wx.OK|wx.CANCEL|wx.CENTRE) if dlg.ShowModal() == wx.ID_OK: new = dlg.GetValue() self.vectorListCtrl.SetStringItem(idx, 1, new) dlg.Destroy() def OnSpan(self, event): self.panelVector.spanTextCtrl.Enable(self.panelVector.spanRadio.GetValue()) def OnFont(self, event): """!Changes default width according to fontsize, width [inch] = fontsize[pt]/24""" ## fontsize = self.panelVector.font['fontCtrl'].GetSelectedFont().GetPointSize() fontsize = self.panelVector.font['fontSizeCtrl'].GetValue() unit = self.unitConv.findUnit(self.panelVector.units['unitsCtrl'].GetStringSelection()) w = fontsize/24. width = self.unitConv.convert(value = w, fromUnit = 'inch', toUnit = unit) self.panelVector.widthCtrl.SetValue("%3.2f" % width) def OnBorder(self, event): """!Enables/disables colorPickerCtrl for border""" self.borderColorCtrl.Enable(self.borderCheck.GetValue()) def updateRasterLegend(self): """!Save information from raster legend dialog to dictionary""" #is raster legend if not self.isRLegend.GetValue(): self.rLegendDict['rLegend'] = False else: self.rLegendDict['rLegend'] = True #units currUnit = self.unitConv.findUnit(self.panelRaster.units['unitsCtrl'].GetStringSelection()) self.rLegendDict['unit'] = currUnit # raster if self.rasterDefault.GetValue(): self.rLegendDict['rasterDefault'] = True self.rLegendDict['raster'] = self.currRaster else: self.rLegendDict['rasterDefault'] = False self.rLegendDict['raster'] = self.rasterSelect.GetValue() if self.rLegendDict['rLegend'] and not self.rLegendDict['raster']: wx.MessageBox(message = _("No raster map selected!"), caption = _('No raster'), style = wx.OK|wx.ICON_ERROR) return False if self.rLegendDict['raster']: # type and range of map rasterType = getRasterType(self.rLegendDict['raster']) if rasterType is None: return False self.rLegendDict['type'] = rasterType #discrete if self.discrete.GetValue(): self.rLegendDict['discrete'] = 'y' else: self.rLegendDict['discrete'] = 'n' # font self.rLegendDict['font'] = self.panelRaster.font['fontCtrl'].GetStringSelection() self.rLegendDict['fontsize'] = self.panelRaster.font['fontSizeCtrl'].GetValue() color = self.panelRaster.font['colorCtrl'].GetColour() self.rLegendDict['color'] = convertRGB(color) # position x = self.unitConv.convert(value = float(self.panelRaster.position['xCtrl'].GetValue()), fromUnit = currUnit, toUnit = 'inch') y = self.unitConv.convert(value = float(self.panelRaster.position['yCtrl'].GetValue()), fromUnit = currUnit, toUnit = 'inch') self.rLegendDict['where'] = (x, y) # estimated size width = self.panelRaster.widthCtrl.GetValue() try: width = float(width) width = self.unitConv.convert(value = width, fromUnit = currUnit, toUnit = 'inch') except ValueError: width = None self.rLegendDict['width'] = width if self.rLegendDict['discrete'] == 'n': height = self.panelRaster.heightOrColumnsCtrl.GetValue() try: height = float(height) height = self.unitConv.convert(value = height, fromUnit = currUnit, toUnit = 'inch') except ValueError: height = None self.rLegendDict['height'] = height else: cols = self.panelRaster.heightOrColumnsCtrl.GetValue() self.rLegendDict['cols'] = cols drawHeight = self.rasterLegend.EstimateHeight(raster = self.rLegendDict['raster'], discrete = self.rLegendDict['discrete'], fontsize = self.rLegendDict['fontsize'], cols = self.rLegendDict['cols'], height = self.rLegendDict['height']) drawWidth = self.rasterLegend.EstimateWidth(raster = self.rLegendDict['raster'], discrete = self.rLegendDict['discrete'], fontsize = self.rLegendDict['fontsize'], cols = self.rLegendDict['cols'], width = self.rLegendDict['width'], paperInstr = self.instruction[self.pageId]) self.rLegendDict['rect'] = wx.Rect2D(x = x, y = y, w = drawWidth, h = drawHeight) # no data if self.rLegendDict['discrete'] == 'y': if self.nodata.GetValue(): self.rLegendDict['nodata'] = 'y' else: self.rLegendDict['nodata'] = 'n' # tickbar elif self.rLegendDict['discrete'] == 'n': if self.ticks.GetValue(): self.rLegendDict['tickbar'] = 'y' else: self.rLegendDict['tickbar'] = 'n' # range if self.range.GetValue(): self.rLegendDict['range'] = True self.rLegendDict['min'] = self.min.GetValue() self.rLegendDict['max'] = self.max.GetValue() else: self.rLegendDict['range'] = False if not self.id[0] in self.instruction: rasterLegend = RasterLegend(self.id[0]) self.instruction.AddInstruction(rasterLegend) self.instruction[self.id[0]].SetInstruction(self.rLegendDict) if self.id[0] not in self.parent.objectId: self.parent.objectId.append(self.id[0]) return True def updateVectorLegend(self): """!Save information from vector legend dialog to dictionary""" vector = self.instruction.FindInstructionByType('vector') if vector: self.vectorId = vector.id else: self.vectorId = None #is vector legend if not self.isVLegend.GetValue(): self.vLegendDict['vLegend'] = False else: self.vLegendDict['vLegend'] = True if self.vLegendDict['vLegend'] == True and self.vectorId is not None: # labels #reindex order idx = 1 for item in range(self.vectorListCtrl.GetItemCount()): if self.vectorListCtrl.IsChecked(item): self.vectorListCtrl.SetItemData(item, idx) idx += 1 else: self.vectorListCtrl.SetItemData(item, 0) if idx == 1: self.vLegendDict['vLegend'] = False else: vList = self.instruction[self.vectorId]['list'] for i, vector in enumerate(vList): item = self.vectorListCtrl.FindItem(start = -1, str = vector[0].split('@')[0]) vList[i][3] = self.vectorListCtrl.GetItemData(item) vList[i][4] = self.vectorListCtrl.GetItem(item, 1).GetText() vmaps = self.instruction.FindInstructionByType('vProperties', list = True) for vmap, vector in zip(vmaps, vList): self.instruction[vmap.id]['lpos'] = vector[3] self.instruction[vmap.id]['label'] = vector[4] #units currUnit = self.unitConv.findUnit(self.panelVector.units['unitsCtrl'].GetStringSelection()) self.vLegendDict['unit'] = currUnit # position x = self.unitConv.convert(value = float(self.panelVector.position['xCtrl'].GetValue()), fromUnit = currUnit, toUnit = 'inch') y = self.unitConv.convert(value = float(self.panelVector.position['yCtrl'].GetValue()), fromUnit = currUnit, toUnit = 'inch') self.vLegendDict['where'] = (x, y) # font self.vLegendDict['font'] = self.panelVector.font['fontCtrl'].GetStringSelection() self.vLegendDict['fontsize'] = self.panelVector.font['fontSizeCtrl'].GetValue() dc = wx.PaintDC(self) font = dc.GetFont() dc.SetFont(wx.Font(pointSize = self.vLegendDict['fontsize'], family = font.GetFamily(), style = font.GetStyle(), weight = wx.FONTWEIGHT_NORMAL)) #size width = self.unitConv.convert(value = float(self.panelVector.widthCtrl.GetValue()), fromUnit = currUnit, toUnit = 'inch') self.vLegendDict['width'] = width self.vLegendDict['cols'] = self.panelVector.colsCtrl.GetValue() if self.panelVector.spanRadio.GetValue() and self.panelVector.spanTextCtrl.GetValue(): self.vLegendDict['span'] = self.panelVector.spanTextCtrl.GetValue() else: self.vLegendDict['span'] = None # size estimation vectors = self.instruction[self.vectorId]['list'] labels = [vector[4] for vector in vectors if vector[3] != 0] extent = dc.GetTextExtent(max(labels, key = len)) wExtent = self.unitConv.convert(value = extent[0], fromUnit = 'pixel', toUnit = 'inch') hExtent = self.unitConv.convert(value = extent[1], fromUnit = 'pixel', toUnit = 'inch') w = (width + wExtent) * self.vLegendDict['cols'] h = len(labels) * hExtent / self.vLegendDict['cols'] h *= 1.1 self.vLegendDict['rect'] = wx.Rect2D(x, y, w, h) #border if self.borderCheck.GetValue(): color = self.borderColorCtrl.GetColour() self.vLegendDict['border'] = convertRGB(color) else: self.vLegendDict['border'] = 'none' if not self.id[1] in self.instruction: vectorLegend = VectorLegend(self.id[1]) self.instruction.AddInstruction(vectorLegend) self.instruction[self.id[1]].SetInstruction(self.vLegendDict) if self.id[1] not in self.parent.objectId: self.parent.objectId.append(self.id[1]) return True def update(self): okR = self.updateRasterLegend() okV = self.updateVectorLegend() if okR and okV: return True return False def updateDialog(self): """!Update legend coordinates after moving""" # raster legend if 'rect' in self.rLegendDict: x, y = self.rLegendDict['rect'][:2] currUnit = self.unitConv.findUnit(self.panelRaster.units['unitsCtrl'].GetStringSelection()) x = self.unitConv.convert(value = x, fromUnit = 'inch', toUnit = currUnit) y = self.unitConv.convert(value = y, fromUnit = 'inch', toUnit = currUnit) self.panelRaster.position['xCtrl'].SetValue("%5.3f" % x) self.panelRaster.position['yCtrl'].SetValue("%5.3f" % y) #update name and type of raster raster = self.instruction.FindInstructionByType('raster') if raster: self.rasterId = raster.id else: self.rasterId = None if raster: currRaster = raster['raster'] else: currRaster = None rasterType = getRasterType(map = currRaster) self.rasterCurrent.SetLabel(_("%(rast)s: type %(type)s") % \ { 'rast' : currRaster, 'type' : str(rasterType) }) # vector legend if 'rect' in self.vLegendDict: x, y = self.vLegendDict['rect'][:2] currUnit = self.unitConv.findUnit(self.panelVector.units['unitsCtrl'].GetStringSelection()) x = self.unitConv.convert(value = x, fromUnit = 'inch', toUnit = currUnit) y = self.unitConv.convert(value = y, fromUnit = 'inch', toUnit = currUnit) self.panelVector.position['xCtrl'].SetValue("%5.3f" % x) self.panelVector.position['yCtrl'].SetValue("%5.3f" % y) # update vector maps if self.instruction.FindInstructionByType('vector'): vectors = sorted(self.instruction.FindInstructionByType('vector')['list'], key = lambda x: x[3]) self.vectorListCtrl.DeleteAllItems() for vector in vectors: index = self.vectorListCtrl.InsertStringItem(sys.maxint, vector[0].split('@')[0]) self.vectorListCtrl.SetStringItem(index, 1, vector[4]) self.vectorListCtrl.SetItemData(index, index) self.vectorListCtrl.CheckItem(index, True) if vector[3] == 0: self.vectorListCtrl.CheckItem(index, False) self.panelVector.colsCtrl.SetRange(1, min(10, len(self.instruction.FindInstructionByType('vector')['list']))) self.panelVector.colsCtrl.SetValue(1) else: self.vectorListCtrl.DeleteAllItems() self.panelVector.colsCtrl.SetRange(0,0) self.panelVector.colsCtrl.SetValue(0) class MapinfoDialog(PsmapDialog): def __init__(self, parent, id, settings): PsmapDialog.__init__(self, parent = parent, id = id, title = "Mapinfo settings", settings = settings) self.objectType = ('mapinfo',) if self.id is not None: self.mapinfo = self.instruction[self.id] self.mapinfoDict = self.mapinfo.GetInstruction() else: self.id = wx.NewId() self.mapinfo = Mapinfo(self.id) self.mapinfoDict = self.mapinfo.GetInstruction() page = self.instruction.FindInstructionByType('page').GetInstruction() self.mapinfoDict['where'] = page['Left'], page['Top'] self.panel = self._mapinfoPanel() self._layout(self.panel) self.OnIsBackground(None) self.OnIsBorder(None) def _mapinfoPanel(self): panel = wx.Panel(parent = self, id = wx.ID_ANY, size = (-1, -1), style = wx.TAB_TRAVERSAL) #panel.SetupScrolling(scroll_x = False, scroll_y = True) border = wx.BoxSizer(wx.VERTICAL) # position box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Position")) sizer = wx.StaticBoxSizer(box, wx.VERTICAL) gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5) gridBagSizer.AddGrowableCol(1) self.AddPosition(parent = panel, dialogDict = self.mapinfoDict) self.AddUnits(parent = panel, dialogDict = self.mapinfoDict) gridBagSizer.Add(panel.units['unitsLabel'], pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(panel.units['unitsCtrl'], pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(panel.position['xLabel'], pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(panel.position['xCtrl'], pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(panel.position['yLabel'], pos = (2,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(panel.position['yCtrl'], pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(panel.position['comment'], pos = (3,0), span = (1,2), flag =wx.ALIGN_BOTTOM, border = 0) sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5) border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5) # font box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Font settings")) sizer = wx.StaticBoxSizer(box, wx.VERTICAL) gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5) gridBagSizer.AddGrowableCol(1) self.AddFont(parent = panel, dialogDict = self.mapinfoDict)#creates font color too, used below gridBagSizer.Add(panel.font['fontLabel'], pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(panel.font['fontCtrl'], pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(panel.font['fontSizeLabel'], pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(panel.font['fontSizeCtrl'], pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(panel.font['colorLabel'], pos = (2,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(panel.font['colorCtrl'], pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) sizer.Add(item = gridBagSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1) border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5) # colors box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " %_("Color settings")) sizer = wx.StaticBoxSizer(box, wx.VERTICAL) flexSizer = wx.FlexGridSizer (cols = 2, hgap = 5, vgap = 5) flexSizer.AddGrowableCol(1) self.colors = {} self.colors['borderCtrl'] = wx.CheckBox(panel, id = wx.ID_ANY, label = _("use border color:")) self.colors['backgroundCtrl'] = wx.CheckBox(panel, id = wx.ID_ANY, label = _("use background color:")) self.colors['borderColor'] = wx.ColourPickerCtrl(panel, id = wx.ID_ANY) self.colors['backgroundColor'] = wx.ColourPickerCtrl(panel, id = wx.ID_ANY) if self.mapinfoDict['border'] == None: self.mapinfoDict['border'] = 'none' if self.mapinfoDict['border'] != 'none': self.colors['borderCtrl'].SetValue(True) self.colors['borderColor'].SetColour(convertRGB(self.mapinfoDict['border'])) else: self.colors['borderCtrl'].SetValue(False) self.colors['borderColor'].SetColour(convertRGB('black')) if self.mapinfoDict['background'] == None: self.mapinfoDict['background'] == 'none' if self.mapinfoDict['background'] != 'none': self.colors['backgroundCtrl'].SetValue(True) self.colors['backgroundColor'].SetColour(convertRGB(self.mapinfoDict['background'])) else: self.colors['backgroundCtrl'].SetValue(False) self.colors['backgroundColor'].SetColour(convertRGB('white')) flexSizer.Add(self.colors['borderCtrl'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0) flexSizer.Add(self.colors['borderColor'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0) flexSizer.Add(self.colors['backgroundCtrl'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0) flexSizer.Add(self.colors['backgroundColor'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0) sizer.Add(item = flexSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1) border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5) panel.SetSizer(border) self.Bind(wx.EVT_CHECKBOX, self.OnIsBorder, self.colors['borderCtrl']) self.Bind(wx.EVT_CHECKBOX, self.OnIsBackground, self.colors['backgroundCtrl']) return panel def OnIsBackground(self, event): if self.colors['backgroundCtrl'].GetValue(): self.colors['backgroundColor'].Enable() self.update() else: self.colors['backgroundColor'].Disable() def OnIsBorder(self, event): if self.colors['borderCtrl'].GetValue(): self.colors['borderColor'].Enable() self.update() else: self.colors['borderColor'].Disable() def update(self): #units currUnit = self.unitConv.findUnit(self.panel.units['unitsCtrl'].GetStringSelection()) self.mapinfoDict['unit'] = currUnit # position if self.panel.position['xCtrl'].GetValue(): x = self.panel.position['xCtrl'].GetValue() else: x = self.mapinfoDict['where'][0] if self.panel.position['yCtrl'].GetValue(): y = self.panel.position['yCtrl'].GetValue() else: y = self.mapinfoDict['where'][1] x = self.unitConv.convert(value = float(self.panel.position['xCtrl'].GetValue()), fromUnit = currUnit, toUnit = 'inch') y = self.unitConv.convert(value = float(self.panel.position['yCtrl'].GetValue()), fromUnit = currUnit, toUnit = 'inch') self.mapinfoDict['where'] = (x, y) # font self.mapinfoDict['font'] = self.panel.font['fontCtrl'].GetStringSelection() self.mapinfoDict['fontsize'] = self.panel.font['fontSizeCtrl'].GetValue() #colors color = self.panel.font['colorCtrl'].GetColour() self.mapinfoDict['color'] = convertRGB(color) if self.colors['backgroundCtrl'].GetValue(): background = self.colors['backgroundColor'].GetColour() self.mapinfoDict['background'] = convertRGB(background) else: self.mapinfoDict['background'] = 'none' if self.colors['borderCtrl'].GetValue(): border = self.colors['borderColor'].GetColour() self.mapinfoDict['border'] = convertRGB(border) else: self.mapinfoDict['border'] = 'none' # estimation of size self.mapinfoDict['rect'] = self.mapinfo.EstimateRect(self.mapinfoDict) if self.id not in self.instruction: mapinfo = Mapinfo(self.id) self.instruction.AddInstruction(mapinfo) self.instruction[self.id].SetInstruction(self.mapinfoDict) if self.id not in self.parent.objectId: self.parent.objectId.append(self.id) self.updateDialog() return True def updateDialog(self): """!Update mapinfo coordinates, after moving""" x, y = self.mapinfoDict['where'] currUnit = self.unitConv.findUnit(self.panel.units['unitsCtrl'].GetStringSelection()) x = self.unitConv.convert(value = x, fromUnit = 'inch', toUnit = currUnit) y = self.unitConv.convert(value = y, fromUnit = 'inch', toUnit = currUnit) self.panel.position['xCtrl'].SetValue("%5.3f" % x) self.panel.position['yCtrl'].SetValue("%5.3f" % y) class ScalebarDialog(PsmapDialog): """!Dialog for scale bar""" def __init__(self, parent, id, settings): PsmapDialog.__init__(self, parent = parent, id = id, title = "Scale bar settings", settings = settings) self.objectType = ('scalebar',) if self.id is not None: self.scalebar = self.instruction[id] self.scalebarDict = self.scalebar.GetInstruction() else: self.id = wx.NewId() self.scalebar = Scalebar(self.id) self.scalebarDict = self.scalebar.GetInstruction() page = self.instruction.FindInstructionByType('page').GetInstruction() self.scalebarDict['where'] = page['Left'], page['Top'] self.panel = self._scalebarPanel() self._layout(self.panel) self.mapUnit = projInfo()['units'].lower() if projInfo()['proj'] == 'xy': self.mapUnit = 'meters' if self.mapUnit not in self.unitConv.getAllUnits(): wx.MessageBox(message = _("Units of current projection are not supported,\n meters will be used!"), caption = _('Unsupported units'), style = wx.OK|wx.ICON_ERROR) self.mapUnit = 'meters' def _scalebarPanel(self): panel = wx.Panel(parent = self, id = wx.ID_ANY, style = wx.TAB_TRAVERSAL) border = wx.BoxSizer(wx.VERTICAL) # # position # box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Position")) sizer = wx.StaticBoxSizer(box, wx.VERTICAL) gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5) gridBagSizer.AddGrowableCol(1) self.AddUnits(parent = panel, dialogDict = self.scalebarDict) self.AddPosition(parent = panel, dialogDict = self.scalebarDict) if self.scalebarDict['rect']: # set position, ref point is center and not left top corner x = self.unitConv.convert(value = self.scalebarDict['where'][0] - self.scalebarDict['rect'].Get()[2]/2, fromUnit = 'inch', toUnit = self.scalebarDict['unit']) y = self.unitConv.convert(value = self.scalebarDict['where'][1] - self.scalebarDict['rect'].Get()[3]/2, fromUnit = 'inch', toUnit = self.scalebarDict['unit']) panel.position['xCtrl'].SetValue("%5.3f" % x) panel.position['yCtrl'].SetValue("%5.3f" % y) gridBagSizer.Add(panel.units['unitsLabel'], pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(panel.units['unitsCtrl'], pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(panel.position['xLabel'], pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(panel.position['xCtrl'], pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(panel.position['yLabel'], pos = (2,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(panel.position['yCtrl'], pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(panel.position['comment'], pos = (3,0), span = (1,2), flag =wx.ALIGN_BOTTOM, border = 0) sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5) border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5) # # size # box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Size")) sizer = wx.StaticBoxSizer(box, wx.VERTICAL) gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5) gridBagSizer.AddGrowableCol(1) lengthText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Length:")) heightText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Height:")) self.lengthTextCtrl = wx.TextCtrl(panel, id = wx.ID_ANY, validator = TCValidator('DIGIT_ONLY')) self.lengthTextCtrl.SetToolTipString(_("Scalebar length is given in map units")) self.heightTextCtrl = wx.TextCtrl(panel, id = wx.ID_ANY, validator = TCValidator('DIGIT_ONLY')) self.heightTextCtrl.SetToolTipString(_("Scalebar height is real height on paper")) choices = [_('default')] + self.unitConv.getMapUnitsNames() self.unitsLength = wx.Choice(panel, id = wx.ID_ANY, choices = choices) choices = self.unitConv.getPageUnitsNames() self.unitsHeight = wx.Choice(panel, id = wx.ID_ANY, choices = choices) # set values unitName = self.unitConv.findName(self.scalebarDict['unitsLength']) if unitName: self.unitsLength.SetStringSelection(unitName) else: if self.scalebarDict['unitsLength'] == 'auto': self.unitsLength.SetSelection(0) elif self.scalebarDict['unitsLength'] == 'nautmiles': self.unitsLength.SetStringSelection(self.unitConv.findName("nautical miles")) self.unitsHeight.SetStringSelection(self.unitConv.findName(self.scalebarDict['unitsHeight'])) if self.scalebarDict['length']: self.lengthTextCtrl.SetValue(str(self.scalebarDict['length'])) else: #estimate default reg = grass.region() w = int((reg['e'] - reg['w'])/3) w = round(w, -len(str(w)) + 2) #12345 -> 12000 self.lengthTextCtrl.SetValue(str(w)) h = self.unitConv.convert(value = self.scalebarDict['height'], fromUnit = 'inch', toUnit = self.scalebarDict['unitsHeight']) self.heightTextCtrl.SetValue(str(h)) gridBagSizer.Add(lengthText, pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.lengthTextCtrl, pos = (0, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.unitsLength, pos = (0, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0) gridBagSizer.Add(heightText, pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.heightTextCtrl, pos = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.unitsHeight, pos = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0) sizer.Add(gridBagSizer, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5) border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5) # #style # box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Style")) sizer = wx.StaticBoxSizer(box, wx.VERTICAL) gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5) sbTypeText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Type:")) self.sbCombo = wx.combo.BitmapComboBox(panel, style = wx.CB_READONLY) # only temporary, images must be moved away imagePath = os.path.join(globalvar.ETCIMGDIR, "scalebar-fancy.png"), os.path.join(globalvar.ETCIMGDIR, "scalebar-simple.png") for item, path in zip(['fancy', 'simple'], imagePath): if not os.path.exists(path): bitmap = wx.EmptyBitmap(0,0) else: bitmap = wx.Bitmap(path) self.sbCombo.Append(item = '', bitmap = bitmap, clientData = item[0]) #self.sbCombo.Append(item = 'simple', bitmap = wx.Bitmap("./images/scalebar-simple.png"), clientData = 's') if self.scalebarDict['scalebar'] == 'f': self.sbCombo.SetSelection(0) elif self.scalebarDict['scalebar'] == 's': self.sbCombo.SetSelection(1) sbSegmentsText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Number of segments:")) self.sbSegmentsCtrl = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 1, max = 30, initial = 4) self.sbSegmentsCtrl.SetValue(self.scalebarDict['segment']) sbLabelsText1 = wx.StaticText(panel, id = wx.ID_ANY, label = _("Label every ")) sbLabelsText2 = wx.StaticText(panel, id = wx.ID_ANY, label = _("segments")) self.sbLabelsCtrl = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 1, max = 30, initial = 1) self.sbLabelsCtrl.SetValue(self.scalebarDict['numbers']) #font fontsizeText = wx.StaticText(panel, id = wx.ID_ANY, label = _("Font size:")) self.fontsizeCtrl = wx.SpinCtrl(panel, id = wx.ID_ANY, min = 4, max = 30, initial = 10) self.fontsizeCtrl.SetValue(self.scalebarDict['fontsize']) self.backgroundCheck = wx.CheckBox(panel, id = wx.ID_ANY, label = _("transparent text background")) if self.scalebarDict['background'] == 'y': self.backgroundCheck.SetValue(False) else: self.backgroundCheck.SetValue(True) gridBagSizer.Add(sbTypeText, pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.sbCombo, pos = (0,1), span = (1, 2), flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 0) gridBagSizer.Add(sbSegmentsText, pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.sbSegmentsCtrl, pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(sbLabelsText1, pos = (2,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.sbLabelsCtrl, pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(sbLabelsText2, pos = (2,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(fontsizeText, pos = (3,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.fontsizeCtrl, pos = (3,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.backgroundCheck, pos = (4, 0), span = (1,3), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) sizer.Add(gridBagSizer, proportion = 1, flag = wx.ALIGN_CENTER_VERTICAL, border = 5) border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5) panel.SetSizer(border) return panel def update(self): """!Save information from dialog""" #units currUnit = self.unitConv.findUnit(self.panel.units['unitsCtrl'].GetStringSelection()) self.scalebarDict['unit'] = currUnit # position if self.panel.position['xCtrl'].GetValue(): x = self.panel.position['xCtrl'].GetValue() else: x = self.scalebarDict['where'][0] if self.panel.position['yCtrl'].GetValue(): y = self.panel.position['yCtrl'].GetValue() else: y = self.scalebarDict['where'][1] x = self.unitConv.convert(value = float(self.panel.position['xCtrl'].GetValue()), fromUnit = currUnit, toUnit = 'inch') y = self.unitConv.convert(value = float(self.panel.position['yCtrl'].GetValue()), fromUnit = currUnit, toUnit = 'inch') #style self.scalebarDict['scalebar'] = self.sbCombo.GetClientData(self.sbCombo.GetSelection()) self.scalebarDict['segment'] = self.sbSegmentsCtrl.GetValue() self.scalebarDict['numbers'] = self.sbLabelsCtrl.GetValue() self.scalebarDict['fontsize'] = self.fontsizeCtrl.GetValue() if self.backgroundCheck.GetValue(): self.scalebarDict['background'] = 'n' else: self.scalebarDict['background'] = 'y' # size # height self.scalebarDict['unitsHeight'] = self.unitConv.findUnit(self.unitsHeight.GetStringSelection()) try: height = float(self.heightTextCtrl.GetValue()) height = self.unitConv.convert(value = height, fromUnit = self.scalebarDict['unitsHeight'], toUnit = 'inch') except (ValueError, SyntaxError): height = 0.1 #default in inch self.scalebarDict['height'] = height #length if self.unitsLength.GetSelection() == 0: selected = 'auto' else: selected = self.unitConv.findUnit(self.unitsLength.GetStringSelection()) if selected == 'nautical miles': selected = 'nautmiles' self.scalebarDict['unitsLength'] = selected try: length = float(self.lengthTextCtrl.GetValue()) except (ValueError, SyntaxError): wx.MessageBox(message = _("Length of scale bar is not defined"), caption = _('Invalid input'), style = wx.OK|wx.ICON_ERROR) return False self.scalebarDict['length'] = length # estimation of size map = self.instruction.FindInstructionByType('map') if not map: map = self.instruction.FindInstructionByType('initMap') mapId = map.id rectSize = self.scalebar.EstimateSize(scalebarDict = self.scalebarDict, scale = self.instruction[mapId]['scale']) self.scalebarDict['rect'] = wx.Rect2D(x = x, y = y, w = rectSize[0], h = rectSize[1]) self.scalebarDict['where'] = self.scalebarDict['rect'].GetCentre() if self.id not in self.instruction: scalebar = Scalebar(self.id) self.instruction.AddInstruction(scalebar) self.instruction[self.id].SetInstruction(self.scalebarDict) if self.id not in self.parent.objectId: self.parent.objectId.append(self.id) return True def updateDialog(self): """!Update scalebar coordinates, after moving""" x, y = self.scalebarDict['rect'][:2] currUnit = self.unitConv.findUnit(self.panel.units['unitsCtrl'].GetStringSelection()) x = self.unitConv.convert(value = x, fromUnit = 'inch', toUnit = currUnit) y = self.unitConv.convert(value = y, fromUnit = 'inch', toUnit = currUnit) self.panel.position['xCtrl'].SetValue("%5.3f" % x) self.panel.position['yCtrl'].SetValue("%5.3f" % y) class TextDialog(PsmapDialog): def __init__(self, parent, id, settings): PsmapDialog.__init__(self, parent = parent, id = id, title = "Text settings", settings = settings) self.objectType = ('text',) if self.id is not None: self.textDict = self.instruction[id].GetInstruction() else: self.id = wx.NewId() text = Text(self.id) self.textDict = text.GetInstruction() page = self.instruction.FindInstructionByType('page').GetInstruction() self.textDict['where'] = page['Left'], page['Top'] map = self.instruction.FindInstructionByType('map') if not map: map = self.instruction.FindInstructionByType('initMap') self.mapId = map.id self.textDict['east'], self.textDict['north'] = PaperMapCoordinates(map = map, x = self.textDict['where'][0], y = self.textDict['where'][1], paperToMap = True) notebook = wx.Notebook(parent = self, id = wx.ID_ANY, style = wx.BK_DEFAULT) self.textPanel = self._textPanel(notebook) self.positionPanel = self._positionPanel(notebook) self.OnBackground(None) self.OnHighlight(None) self.OnBorder(None) self.OnPositionType(None) self.OnRotation(None) self._layout(notebook) def _textPanel(self, notebook): panel = wx.Panel(parent = notebook, id = wx.ID_ANY, style = wx.TAB_TRAVERSAL) notebook.AddPage(page = panel, text = _("Text")) border = wx.BoxSizer(wx.VERTICAL) # text entry box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Text")) sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL) textLabel = wx.StaticText(panel, id = wx.ID_ANY, label = _("Enter text:")) self.textCtrl = ExpandoTextCtrl(panel, id = wx.ID_ANY, value = self.textDict['text']) sizer.Add(textLabel, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 5) sizer.Add(self.textCtrl, proportion = 1, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 5) border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5) #font box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Font settings")) sizer = wx.StaticBoxSizer(box, wx.VERTICAL) flexGridSizer = wx.FlexGridSizer (rows = 3, cols = 2, hgap = 5, vgap = 5) flexGridSizer.AddGrowableCol(1) self.AddFont(parent = panel, dialogDict = self.textDict) flexGridSizer.Add(panel.font['fontLabel'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0) flexGridSizer.Add(panel.font['fontCtrl'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0) flexGridSizer.Add(panel.font['fontSizeLabel'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0) flexGridSizer.Add(panel.font['fontSizeCtrl'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0) flexGridSizer.Add(panel.font['colorLabel'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0) flexGridSizer.Add(panel.font['colorCtrl'], proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL, border = 0) sizer.Add(item = flexGridSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1) border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5) #text effects box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Text effects")) sizer = wx.StaticBoxSizer(box, wx.VERTICAL) gridBagSizer = wx.GridBagSizer (hgap = 5, vgap = 5) self.effect = {} self.effect['backgroundCtrl'] = wx.CheckBox(panel, id = wx.ID_ANY, label = _("text background")) self.effect['backgroundColor'] = wx.ColourPickerCtrl(panel, id = wx.ID_ANY) self.effect['highlightCtrl'] = wx.CheckBox(panel, id = wx.ID_ANY, label = _("highlight")) self.effect['highlightColor'] = wx.ColourPickerCtrl(panel, id = wx.ID_ANY) self.effect['highlightWidth'] = wx.SpinCtrl(panel, id = wx.ID_ANY, size = self.spinCtrlSize, min = 0, max = 5, initial = 1) self.effect['highlightWidthLabel'] = wx.StaticText(panel, id = wx.ID_ANY, label = _("Width (pts):")) self.effect['borderCtrl'] = wx.CheckBox(panel, id = wx.ID_ANY, label = _("text border")) self.effect['borderColor'] = wx.ColourPickerCtrl(panel, id = wx.ID_ANY) self.effect['borderWidth'] = wx.SpinCtrl(panel, id = wx.ID_ANY, size = self.spinCtrlSize, min = 1, max = 25, initial = 1) self.effect['borderWidthLabel'] = wx.StaticText(panel, id = wx.ID_ANY, label = _("Width (pts):")) #set values if self.textDict['background'] == None: self.textDict['background'] = 'none' if self.textDict['background'] != 'none': self.effect['backgroundCtrl'].SetValue(True) self.effect['backgroundColor'].SetColour(convertRGB(self.textDict['background'])) else: self.effect['backgroundCtrl'].SetValue(False) self.effect['backgroundColor'].SetColour(convertRGB('white')) if self.textDict['hcolor'] == None: self.textDict['hcolor'] = 'none' if self.textDict['hcolor'] != 'none': self.effect['highlightCtrl'].SetValue(True) self.effect['highlightColor'].SetColour(convertRGB(self.textDict['hcolor'])) else: self.effect['highlightCtrl'].SetValue(False) self.effect['highlightColor'].SetColour(convertRGB('grey')) self.effect['highlightWidth'].SetValue(float(self.textDict['hwidth'])) if self.textDict['border'] == None: self.textDict['border'] = 'none' if self.textDict['border'] != 'none': self.effect['borderCtrl'].SetValue(True) self.effect['borderColor'].SetColour(convertRGB(self.textDict['border'])) else: self.effect['borderCtrl'].SetValue(False) self.effect['borderColor'].SetColour(convertRGB('black')) self.effect['borderWidth'].SetValue(float(self.textDict['width'])) gridBagSizer.Add(self.effect['backgroundCtrl'], pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.effect['backgroundColor'], pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.effect['highlightCtrl'], pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.effect['highlightColor'], pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.effect['highlightWidthLabel'], pos = (1,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.effect['highlightWidth'], pos = (1,3), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.effect['borderCtrl'], pos = (2,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.effect['borderColor'], pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.effect['borderWidthLabel'], pos = (2,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizer.Add(self.effect['borderWidth'], pos = (2,3), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) sizer.Add(item = gridBagSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 1) border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5) self.Bind(EVT_ETC_LAYOUT_NEEDED, self.OnRefit, self.textCtrl) self.Bind(wx.EVT_CHECKBOX, self.OnBackground, self.effect['backgroundCtrl']) self.Bind(wx.EVT_CHECKBOX, self.OnHighlight, self.effect['highlightCtrl']) self.Bind(wx.EVT_CHECKBOX, self.OnBorder, self.effect['borderCtrl']) panel.SetSizer(border) panel.Fit() return panel def _positionPanel(self, notebook): panel = wx.Panel(parent = notebook, id = wx.ID_ANY, style = wx.TAB_TRAVERSAL) notebook.AddPage(page = panel, text = _("Position")) border = wx.BoxSizer(wx.VERTICAL) #Position box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Position")) sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL) gridBagSizer = wx.GridBagSizer(hgap = 5, vgap = 5) gridBagSizer.AddGrowableCol(0) gridBagSizer.AddGrowableCol(1) self.positionLabel = wx.StaticText(panel, id = wx.ID_ANY, label = _("Position is given:")) self.paperPositionCtrl = wx.RadioButton(panel, id = wx.ID_ANY, label = _("relatively to paper"), style = wx.RB_GROUP) self.mapPositionCtrl = wx.RadioButton(panel, id = wx.ID_ANY, label = _("by map coordinates")) self.paperPositionCtrl.SetValue(self.textDict['XY']) self.mapPositionCtrl.SetValue(not self.textDict['XY']) gridBagSizer.Add(self.positionLabel, pos = (0,0), span = (1,3), flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT, border = 0) gridBagSizer.Add(self.paperPositionCtrl, pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT, border = 0) gridBagSizer.Add(self.mapPositionCtrl, pos = (1,1),flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT, border = 0) # first box - paper coordinates box1 = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = "") sizerP = wx.StaticBoxSizer(box1, wx.VERTICAL) self.gridBagSizerP = wx.GridBagSizer (hgap = 5, vgap = 5) self.gridBagSizerP.AddGrowableCol(1) self.gridBagSizerP.AddGrowableRow(3) self.AddPosition(parent = panel, dialogDict = self.textDict) panel.position['comment'].SetLabel(_("Position from the top left\nedge of the paper")) self.AddUnits(parent = panel, dialogDict = self.textDict) self.gridBagSizerP.Add(panel.units['unitsLabel'], pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.gridBagSizerP.Add(panel.units['unitsCtrl'], pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.gridBagSizerP.Add(panel.position['xLabel'], pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.gridBagSizerP.Add(panel.position['xCtrl'], pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.gridBagSizerP.Add(panel.position['yLabel'], pos = (2,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.gridBagSizerP.Add(panel.position['yCtrl'], pos = (2,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.gridBagSizerP.Add(panel.position['comment'], pos = (3,0), span = (1,2), flag = wx.ALIGN_BOTTOM, border = 0) sizerP.Add(self.gridBagSizerP, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5) gridBagSizer.Add(sizerP, pos = (2,0),span = (1,1), flag = wx.ALIGN_CENTER_HORIZONTAL|wx.EXPAND, border = 0) # second box - map coordinates box2 = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = "") sizerM = wx.StaticBoxSizer(box2, wx.VERTICAL) self.gridBagSizerM = wx.GridBagSizer (hgap = 5, vgap = 5) self.gridBagSizerM.AddGrowableCol(0) self.gridBagSizerM.AddGrowableCol(1) self.eastingLabel = wx.StaticText(panel, id = wx.ID_ANY, label = "E:") self.northingLabel = wx.StaticText(panel, id = wx.ID_ANY, label = "N:") self.eastingCtrl = wx.TextCtrl(panel, id = wx.ID_ANY, value = "") self.northingCtrl = wx.TextCtrl(panel, id = wx.ID_ANY, value = "") east, north = PaperMapCoordinates(map = self.instruction[self.mapId], x = self.textDict['where'][0], y = self.textDict['where'][1], paperToMap = True) self.eastingCtrl.SetValue(str(east)) self.northingCtrl.SetValue(str(north)) self.gridBagSizerM.Add(self.eastingLabel, pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.gridBagSizerM.Add(self.northingLabel, pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.gridBagSizerM.Add(self.eastingCtrl, pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) self.gridBagSizerM.Add(self.northingCtrl, pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) sizerM.Add(self.gridBagSizerM, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5) gridBagSizer.Add(sizerM, pos = (2,1), flag = wx.ALIGN_LEFT|wx.EXPAND, border = 0) #offset box3 = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " %_("Offset")) sizerO = wx.StaticBoxSizer(box3, wx.VERTICAL) gridBagSizerO = wx.GridBagSizer (hgap = 5, vgap = 5) self.xoffLabel = wx.StaticText(panel, id = wx.ID_ANY, label = _("horizontal (pts):")) self.yoffLabel = wx.StaticText(panel, id = wx.ID_ANY, label = _("vertical (pts):")) self.xoffCtrl = wx.SpinCtrl(panel, id = wx.ID_ANY, size = (50, -1), min = -50, max = 50, initial = 0) self.yoffCtrl = wx.SpinCtrl(panel, id = wx.ID_ANY, size = (50, -1), min = -50, max = 50, initial = 0) self.xoffCtrl.SetValue(self.textDict['xoffset']) self.yoffCtrl.SetValue(self.textDict['yoffset']) gridBagSizerO.Add(self.xoffLabel, pos = (0,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizerO.Add(self.yoffLabel, pos = (1,0), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizerO.Add(self.xoffCtrl, pos = (0,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) gridBagSizerO.Add(self.yoffCtrl, pos = (1,1), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) sizerO.Add(gridBagSizerO, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5) gridBagSizer.Add(sizerO, pos = (3,0), flag = wx.ALIGN_CENTER_HORIZONTAL|wx.EXPAND, border = 0) # reference point box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " %_(" Reference point")) sizerR = wx.StaticBoxSizer(box, wx.VERTICAL) flexSizer = wx.FlexGridSizer(rows = 3, cols = 3, hgap = 5, vgap = 5) flexSizer.AddGrowableCol(0) flexSizer.AddGrowableCol(1) flexSizer.AddGrowableCol(2) ref = [] for row in ["upper", "center", "lower"]: for col in ["left", "center", "right"]: ref.append(row + " " + col) self.radio = [wx.RadioButton(panel, id = wx.ID_ANY, label = '', style = wx.RB_GROUP, name = ref[0])] self.radio[0].SetValue(False) flexSizer.Add(self.radio[0], proportion = 0, flag = wx.ALIGN_CENTER, border = 0) for i in range(1,9): self.radio.append(wx.RadioButton(panel, id = wx.ID_ANY, label = '', name = ref[i])) self.radio[-1].SetValue(False) flexSizer.Add(self.radio[-1], proportion = 0, flag = wx.ALIGN_CENTER, border = 0) self.FindWindowByName(self.textDict['ref']).SetValue(True) sizerR.Add(flexSizer, proportion = 1, flag = wx.EXPAND, border = 0) gridBagSizer.Add(sizerR, pos = (3,1), flag = wx.ALIGN_LEFT|wx.EXPAND, border = 0) sizer.Add(gridBagSizer, proportion = 1, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 5) border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5) #rotation box = wx.StaticBox (parent = panel, id = wx.ID_ANY, label = " %s " % _("Text rotation")) sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL) self.rotCtrl = wx.CheckBox(panel, id = wx.ID_ANY, label = _("rotate text (counterclockwise)")) self.rotValue = wx.SpinCtrl(panel, wx.ID_ANY, size = (50, -1), min = 0, max = 360, initial = 0) if self.textDict['rotate']: self.rotValue.SetValue(int(self.textDict['rotate'])) self.rotCtrl.SetValue(True) else: self.rotValue.SetValue(0) self.rotCtrl.SetValue(False) sizer.Add(self.rotCtrl, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT|wx.ALL, border = 5) sizer.Add(self.rotValue, proportion = 0, flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT|wx.ALL, border = 5) border.Add(item = sizer, proportion = 0, flag = wx.ALL | wx.EXPAND, border = 5) panel.SetSizer(border) panel.Fit() self.Bind(wx.EVT_RADIOBUTTON, self.OnPositionType, self.paperPositionCtrl) self.Bind(wx.EVT_RADIOBUTTON, self.OnPositionType, self.mapPositionCtrl) self.Bind(wx.EVT_CHECKBOX, self.OnRotation, self.rotCtrl) return panel def OnRefit(self, event): self.Fit() def OnRotation(self, event): if self.rotCtrl.GetValue(): self.rotValue.Enable() else: self.rotValue.Disable() def OnPositionType(self, event): if self.paperPositionCtrl.GetValue(): for widget in self.gridBagSizerP.GetChildren(): widget.GetWindow().Enable() for widget in self.gridBagSizerM.GetChildren(): widget.GetWindow().Disable() else: for widget in self.gridBagSizerM.GetChildren(): widget.GetWindow().Enable() for widget in self.gridBagSizerP.GetChildren(): widget.GetWindow().Disable() def OnBackground(self, event): if self.effect['backgroundCtrl'].GetValue(): self.effect['backgroundColor'].Enable() self.update() else: self.effect['backgroundColor'].Disable() def OnHighlight(self, event): if self.effect['highlightCtrl'].GetValue(): self.effect['highlightColor'].Enable() self.effect['highlightWidth'].Enable() self.effect['highlightWidthLabel'].Enable() self.update() else: self.effect['highlightColor'].Disable() self.effect['highlightWidth'].Disable() self.effect['highlightWidthLabel'].Disable() def OnBorder(self, event): if self.effect['borderCtrl'].GetValue(): self.effect['borderColor'].Enable() self.effect['borderWidth'].Enable() self.effect['borderWidthLabel'].Enable() self.update() else: self.effect['borderColor'].Disable() self.effect['borderWidth'].Disable() self.effect['borderWidthLabel'].Disable() def update(self): #text self.textDict['text'] = self.textCtrl.GetValue() if not self.textDict['text']: wx.MessageBox(_("No text entered!"), _("Error")) return False #font self.textDict['font'] = self.textPanel.font['fontCtrl'].GetStringSelection() self.textDict['fontsize'] = self.textPanel.font['fontSizeCtrl'].GetValue() color = self.textPanel.font['colorCtrl'].GetColour() self.textDict['color'] = convertRGB(color) #effects if self.effect['backgroundCtrl'].GetValue(): background = self.effect['backgroundColor'].GetColour() self.textDict['background'] = convertRGB(background) else: self.textDict['background'] = 'none' if self.effect['borderCtrl'].GetValue(): border = self.effect['borderColor'].GetColour() self.textDict['border'] = convertRGB(border) else: self.textDict['border'] = 'none' self.textDict['width'] = self.effect['borderWidth'].GetValue() if self.effect['highlightCtrl'].GetValue(): highlight = self.effect['highlightColor'].GetColour() self.textDict['hcolor'] = convertRGB(highlight) else: self.textDict['hcolor'] = 'none' self.textDict['hwidth'] = self.effect['highlightWidth'].GetValue() #offset self.textDict['xoffset'] = self.xoffCtrl.GetValue() self.textDict['yoffset'] = self.yoffCtrl.GetValue() #position if self.paperPositionCtrl.GetValue(): self.textDict['XY'] = True currUnit = self.unitConv.findUnit(self.positionPanel.units['unitsCtrl'].GetStringSelection()) self.textDict['unit'] = currUnit if self.positionPanel.position['xCtrl'].GetValue(): x = self.positionPanel.position['xCtrl'].GetValue() else: x = self.textDict['where'][0] if self.positionPanel.position['yCtrl'].GetValue(): y = self.positionPanel.position['yCtrl'].GetValue() else: y = self.textDict['where'][1] x = self.unitConv.convert(value = float(x), fromUnit = currUnit, toUnit = 'inch') y = self.unitConv.convert(value = float(y), fromUnit = currUnit, toUnit = 'inch') self.textDict['where'] = x, y self.textDict['east'], self.textDict['north'] = PaperMapCoordinates(self.instruction[self.mapId], x, y, paperToMap = True) else: self.textDict['XY'] = False if self.eastingCtrl.GetValue(): self.textDict['east'] = self.eastingCtrl.GetValue() else: self.textDict['east'] = self.textDict['east'] if self.northingCtrl.GetValue(): self.textDict['north'] = self.northingCtrl.GetValue() else: self.textDict['north'] = self.textDict['north'] self.textDict['where'] = PaperMapCoordinates(map = self.instruction[self.mapId], x = float(self.textDict['east']), y = float(self.textDict['north']), paperToMap = False) #rotation if self.rotCtrl.GetValue(): self.textDict['rotate'] = self.rotValue.GetValue() else: self.textDict['rotate'] = None #reference point for radio in self.radio: if radio.GetValue() == True: self.textDict['ref'] = radio.GetName() if self.id not in self.instruction: text = Text(self.id) self.instruction.AddInstruction(text) self.instruction[self.id].SetInstruction(self.textDict) if self.id not in self.parent.objectId: self.parent.objectId.append(self.id) # self.updateDialog() return True def updateDialog(self): """!Update text coordinates, after moving""" # XY coordinates x, y = self.textDict['where'][:2] currUnit = self.unitConv.findUnit(self.positionPanel.units['unitsCtrl'].GetStringSelection()) x = self.unitConv.convert(value = x, fromUnit = 'inch', toUnit = currUnit) y = self.unitConv.convert(value = y, fromUnit = 'inch', toUnit = currUnit) self.positionPanel.position['xCtrl'].SetValue("%5.3f" % x) self.positionPanel.position['yCtrl'].SetValue("%5.3f" % y) # EN coordinates e, n = self.textDict['east'], self.textDict['north'] self.eastingCtrl.SetValue(str(self.textDict['east'])) self.northingCtrl.SetValue(str(self.textDict['north'])) def convertRGB(rgb): """!Converts wx.Colour(r,g,b,a) to string 'r:g:b' or named color, or named color/r:g:b string to wx.Colour, depending on input""" # transform a wx.Colour tuple into an r:g:b string if type(rgb) == wx.Colour: for name, color in grass.named_colors.items(): if rgb.Red() == int(color[0] * 255) and\ rgb.Green() == int(color[1] * 255) and\ rgb.Blue() == int(color[2] * 255): return name return str(rgb.Red()) + ':' + str(rgb.Green()) + ':' + str(rgb.Blue()) # transform a GRASS named color or an r:g:b string into a wx.Colour tuple else: color = (grass.parse_color(rgb)[0]*255, grass.parse_color(rgb)[1]*255, grass.parse_color(rgb)[2]*255) color = wx.Color(*color) if color.IsOk(): return color else: return None def PaperMapCoordinates(map, x, y, paperToMap = True): """!Converts paper (inch) coordinates -> map coordinates""" unitConv = UnitConversion() currRegionDict = grass.region() cornerEasting, cornerNorthing = currRegionDict['w'], currRegionDict['n'] xMap = map['rect'][0] yMap = map['rect'][1] widthMap = map['rect'][2] * 0.0254 # to meter heightMap = map['rect'][3] * 0.0254 xScale = widthMap / abs(currRegionDict['w'] - currRegionDict['e']) yScale = heightMap / abs(currRegionDict['n'] - currRegionDict['s']) currScale = (xScale + yScale) / 2 if not paperToMap: textEasting, textNorthing = x, y eastingDiff = textEasting - cornerEasting if currRegionDict['w'] > currRegionDict['e']: eastingDiff = - eastingDiff else: eastingDiff = eastingDiff northingDiff = textNorthing - cornerNorthing if currRegionDict['n'] > currRegionDict['s']: northingDiff = - northingDiff else: northingDiff = northingDiff xPaper = xMap + unitConv.convert(value = eastingDiff, fromUnit = 'meter', toUnit = 'inch') * currScale yPaper = yMap + unitConv.convert(value = northingDiff, fromUnit = 'meter', toUnit = 'inch') * currScale return xPaper, yPaper else: if currRegionDict['w'] < currRegionDict['e']: eastingDiff = (x - xMap) else: eastingDiff = (xMap - x) if currRegionDict['n'] < currRegionDict['s']: northingDiff = (y - yMap) else: northingDiff = (yMap - y) textEasting = cornerEasting + unitConv.convert(value = eastingDiff, fromUnit = 'inch', toUnit = 'meter') / currScale textNorthing = cornerNorthing + unitConv.convert(value = northingDiff, fromUnit = 'inch', toUnit = 'meter') / currScale return int(textEasting), int(textNorthing) def AutoAdjust(self, scaleType, rect, map = None, mapType = None, region = None): """!Computes map scale, center and map frame rectangle to fit region (scale is not fixed)""" currRegionDict = {} if scaleType == 0 and map:# automatic, region from raster or vector res = '' if mapType == 'raster': try: res = grass.read_command("g.region", flags = 'gu', rast = map) except grass.ScriptError: pass elif mapType == 'vector': res = grass.read_command("g.region", flags = 'gu', vect = map) currRegionDict = grass.parse_key_val(res, val_type = float) elif scaleType == 1 and region: # saved region res = grass.read_command("g.region", flags = 'gu', region = region) currRegionDict = grass.parse_key_val(res, val_type = float) elif scaleType == 2: # current region env = grass.gisenv() windFilePath = os.path.join(env['GISDBASE'], env['LOCATION_NAME'], env['MAPSET'], 'WIND') try: windFile = open(windFilePath, 'r').read() except IOError: currRegionDict = grass.region() regionDict = grass.parse_key_val(windFile, sep = ':', val_type = float) region = grass.read_command("g.region", flags = 'gu', n = regionDict['north'], s = regionDict['south'], e = regionDict['east'], w = regionDict['west']) currRegionDict = grass.parse_key_val(region, val_type = float) else: return None, None, None if not currRegionDict: return None, None, None rX = rect.x rY = rect.y rW = rect.width rH = rect.height if not hasattr(self, 'unitConv'): self.unitConv = UnitConversion(self) toM = 1 if projInfo()['proj'] != 'xy': toM = float(projInfo()['meters']) mW = self.unitConv.convert(value = (currRegionDict['e'] - currRegionDict['w']) * toM, fromUnit = 'meter', toUnit = 'inch') mH = self.unitConv.convert(value = (currRegionDict['n'] - currRegionDict['s']) * toM, fromUnit = 'meter', toUnit = 'inch') scale = min(rW/mW, rH/mH) if rW/rH > mW/mH: x = rX - (rH*(mW/mH) - rW)/2 y = rY rWNew = rH*(mW/mH) rHNew = rH else: x = rX y = rY - (rW*(mH/mW) - rH)/2 rHNew = rW*(mH/mW) rWNew = rW # center cE = (currRegionDict['w'] + currRegionDict['e'])/2 cN = (currRegionDict['n'] + currRegionDict['s'])/2 return scale, (cE, cN), wx.Rect2D(x, y, rWNew, rHNew) #inch def SetResolution(dpi, width, height): """!If resolution is too high, lower it @param dpi max DPI @param width map frame width @param height map frame height """ region = grass.region() if region['cols'] > width * dpi or region['rows'] > height * dpi: rows = height * dpi cols = width * dpi RunCommand('g.region', rows = rows, cols = cols) def ComputeSetRegion(self, mapDict): """!Computes and sets region from current scale, map center coordinates and map rectangle""" if mapDict['scaleType'] == 3: # fixed scale scale = mapDict['scale'] if not hasattr(self, 'unitConv'): self.unitConv = UnitConversion(self) fromM = 1 if projInfo()['proj'] != 'xy': fromM = float(projInfo()['meters']) rectHalfInch = (mapDict['rect'].width/2, mapDict['rect'].height/2) rectHalfMeter = (self.unitConv.convert(value = rectHalfInch[0], fromUnit = 'inch', toUnit = 'meter')/ fromM /scale, self.unitConv.convert(value = rectHalfInch[1], fromUnit = 'inch', toUnit = 'meter')/ fromM /scale) centerE = mapDict['center'][0] centerN = mapDict['center'][1] raster = self.instruction.FindInstructionByType('raster') if raster: rasterId = raster.id else: rasterId = None if rasterId: RunCommand('g.region', n = ceil(centerN + rectHalfMeter[1]), s = floor(centerN - rectHalfMeter[1]), e = ceil(centerE + rectHalfMeter[0]), w = floor(centerE - rectHalfMeter[0]), rast = self.instruction[rasterId]['raster']) else: RunCommand('g.region', n = ceil(centerN + rectHalfMeter[1]), s = floor(centerN - rectHalfMeter[1]), e = ceil(centerE + rectHalfMeter[0]), w = floor(centerE - rectHalfMeter[0])) def projInfo(): """!Return region projection and map units information, taken from render.py""" projinfo = dict() ret = RunCommand('g.proj', read = True, flags = 'p') if not ret: return projinfo for line in ret.splitlines(): if ':' in line: key, val = line.split(':') projinfo[key.strip()] = val.strip() elif "XY location (unprojected)" in line: projinfo['proj'] = 'xy' projinfo['units'] = '' break return projinfo def GetMapBounds(filename, portrait = True): """!Run ps.map -b to get information about map bounding box @param filename psmap input file @param portrait page orientation""" orient = '' if not portrait: orient = 'r' try: bb = map(float, grass.read_command('ps.map', flags = 'b' + orient, quiet = True, input = filename).strip().split('=')[1].split(',')) except (grass.ScriptError, IndexError): GError(message = _("Unable to run `ps.map -b`")) return None return wx.Rect2D(bb[0], bb[3], bb[2] - bb[0], bb[1] - bb[3]) def getRasterType(map): """!Returns type of raster map (CELL, FCELL, DCELL)""" if map is None: map = '' file = grass.find_file(name = map, element = 'cell') if file['file']: rasterType = grass.raster_info(map)['datatype'] return rasterType else: return None
AsherBond/MondocosmOS
grass_trunk/gui/wxpython/gui_modules/psmap_dialogs.py
Python
agpl-3.0
275,095
from jsonrpc import ServiceProxy import sys import string # ===== BEGIN USER SETTINGS ===== # if you do not set these you will be prompted for a password for every command rpcuser = "" rpcpass = "" # ====== END USER SETTINGS ====== if rpcpass == "": access = ServiceProxy("http://127.0.0.1:5888") else: access = ServiceProxy("http://"+rpcuser+":"+rpcpass+"@127.0.0.1:5888") cmd = sys.argv[1].lower() if cmd == "backupwallet": try: path = raw_input("Enter destination path/filename: ") print access.backupwallet(path) except: print "\n---An error occurred---\n" elif cmd == "getaccount": try: addr = raw_input("Enter a Aiden address: ") print access.getaccount(addr) except: print "\n---An error occurred---\n" elif cmd == "getaccountaddress": try: acct = raw_input("Enter an account name: ") print access.getaccountaddress(acct) except: print "\n---An error occurred---\n" elif cmd == "getaddressesbyaccount": try: acct = raw_input("Enter an account name: ") print access.getaddressesbyaccount(acct) except: print "\n---An error occurred---\n" elif cmd == "getbalance": try: acct = raw_input("Enter an account (optional): ") mc = raw_input("Minimum confirmations (optional): ") try: print access.getbalance(acct, mc) except: print access.getbalance() except: print "\n---An error occurred---\n" elif cmd == "getblockbycount": try: height = raw_input("Height: ") print access.getblockbycount(height) except: print "\n---An error occurred---\n" elif cmd == "getblockcount": try: print access.getblockcount() except: print "\n---An error occurred---\n" elif cmd == "getblocknumber": try: print access.getblocknumber() except: print "\n---An error occurred---\n" elif cmd == "getconnectioncount": try: print access.getconnectioncount() except: print "\n---An error occurred---\n" elif cmd == "getdifficulty": try: print access.getdifficulty() except: print "\n---An error occurred---\n" elif cmd == "getgenerate": try: print access.getgenerate() except: print "\n---An error occurred---\n" elif cmd == "gethashespersec": try: print access.gethashespersec() except: print "\n---An error occurred---\n" elif cmd == "getinfo": try: print access.getinfo() except: print "\n---An error occurred---\n" elif cmd == "getnewaddress": try: acct = raw_input("Enter an account name: ") try: print access.getnewaddress(acct) except: print access.getnewaddress() except: print "\n---An error occurred---\n" elif cmd == "getreceivedbyaccount": try: acct = raw_input("Enter an account (optional): ") mc = raw_input("Minimum confirmations (optional): ") try: print access.getreceivedbyaccount(acct, mc) except: print access.getreceivedbyaccount() except: print "\n---An error occurred---\n" elif cmd == "getreceivedbyaddress": try: addr = raw_input("Enter a Bitcoin address (optional): ") mc = raw_input("Minimum confirmations (optional): ") try: print access.getreceivedbyaddress(addr, mc) except: print access.getreceivedbyaddress() except: print "\n---An error occurred---\n" elif cmd == "gettransaction": try: txid = raw_input("Enter a transaction ID: ") print access.gettransaction(txid) except: print "\n---An error occurred---\n" elif cmd == "getwork": try: data = raw_input("Data (optional): ") try: print access.gettransaction(data) except: print access.gettransaction() except: print "\n---An error occurred---\n" elif cmd == "help": try: cmd = raw_input("Command (optional): ") try: print access.help(cmd) except: print access.help() except: print "\n---An error occurred---\n" elif cmd == "listaccounts": try: mc = raw_input("Minimum confirmations (optional): ") try: print access.listaccounts(mc) except: print access.listaccounts() except: print "\n---An error occurred---\n" elif cmd == "listreceivedbyaccount": try: mc = raw_input("Minimum confirmations (optional): ") incemp = raw_input("Include empty? (true/false, optional): ") try: print access.listreceivedbyaccount(mc, incemp) except: print access.listreceivedbyaccount() except: print "\n---An error occurred---\n" elif cmd == "listreceivedbyaddress": try: mc = raw_input("Minimum confirmations (optional): ") incemp = raw_input("Include empty? (true/false, optional): ") try: print access.listreceivedbyaddress(mc, incemp) except: print access.listreceivedbyaddress() except: print "\n---An error occurred---\n" elif cmd == "listtransactions": try: acct = raw_input("Account (optional): ") count = raw_input("Number of transactions (optional): ") frm = raw_input("Skip (optional):") try: print access.listtransactions(acct, count, frm) except: print access.listtransactions() except: print "\n---An error occurred---\n" elif cmd == "move": try: frm = raw_input("From: ") to = raw_input("To: ") amt = raw_input("Amount:") mc = raw_input("Minimum confirmations (optional): ") comment = raw_input("Comment (optional): ") try: print access.move(frm, to, amt, mc, comment) except: print access.move(frm, to, amt) except: print "\n---An error occurred---\n" elif cmd == "sendfrom": try: frm = raw_input("From: ") to = raw_input("To: ") amt = raw_input("Amount:") mc = raw_input("Minimum confirmations (optional): ") comment = raw_input("Comment (optional): ") commentto = raw_input("Comment-to (optional): ") try: print access.sendfrom(frm, to, amt, mc, comment, commentto) except: print access.sendfrom(frm, to, amt) except: print "\n---An error occurred---\n" elif cmd == "sendmany": try: frm = raw_input("From: ") to = raw_input("To (in format address1:amount1,address2:amount2,...): ") mc = raw_input("Minimum confirmations (optional): ") comment = raw_input("Comment (optional): ") try: print access.sendmany(frm,to,mc,comment) except: print access.sendmany(frm,to) except: print "\n---An error occurred---\n" elif cmd == "sendtoaddress": try: to = raw_input("To (in format address1:amount1,address2:amount2,...): ") amt = raw_input("Amount:") comment = raw_input("Comment (optional): ") commentto = raw_input("Comment-to (optional): ") try: print access.sendtoaddress(to,amt,comment,commentto) except: print access.sendtoaddress(to,amt) except: print "\n---An error occurred---\n" elif cmd == "setaccount": try: addr = raw_input("Address: ") acct = raw_input("Account:") print access.setaccount(addr,acct) except: print "\n---An error occurred---\n" elif cmd == "setgenerate": try: gen= raw_input("Generate? (true/false): ") cpus = raw_input("Max processors/cores (-1 for unlimited, optional):") try: print access.setgenerate(gen, cpus) except: print access.setgenerate(gen) except: print "\n---An error occurred---\n" elif cmd == "settxfee": try: amt = raw_input("Amount:") print access.settxfee(amt) except: print "\n---An error occurred---\n" elif cmd == "stop": try: print access.stop() except: print "\n---An error occurred---\n" elif cmd == "validateaddress": try: addr = raw_input("Address: ") print access.validateaddress(addr) except: print "\n---An error occurred---\n" elif cmd == "walletpassphrase": try: pwd = raw_input("Enter wallet passphrase: ") access.walletpassphrase(pwd, 60) print "\n---Wallet unlocked---\n" except: print "\n---An error occurred---\n" elif cmd == "walletpassphrasechange": try: pwd = raw_input("Enter old wallet passphrase: ") pwd2 = raw_input("Enter new wallet passphrase: ") access.walletpassphrasechange(pwd, pwd2) print print "\n---Passphrase changed---\n" except: print print "\n---An error occurred---\n" print else: print "Command not found or not supported"
chrisfranko/aiden
contrib/bitrpc/bitrpc.py
Python
mit
7,834
#python import k3d import testing setup = testing.setup_mesh_modifier_test("PolyCube", "RotatePoints") selection = k3d.geometry.selection.create(0) selection.points = k3d.geometry.point_selection.create(selection, 1) setup.modifier.mesh_selection = selection setup.modifier.z = 1.0 testing.require_valid_mesh(setup.document, setup.modifier.get_property("output_mesh")) testing.require_similar_mesh(setup.document, setup.modifier.get_property("output_mesh"), "mesh.modifier.RotatePoints", 1)
barche/k3d
tests/mesh/mesh.modifier.RotatePoints.py
Python
gpl-2.0
498
#!/usr/bin/env python import sys import subprocess import os import re import shutil def obj_list_gen(): if os.path.exists('obj_list.map'): os.remove('obj_list.map') file=open('obj_list.map', 'w') parse_file=open('image/ram_size.txt', 'r') all_lines = parse_file.readlines() for line in all_lines: item = filter(None, line.strip().split('\t')) num = len(item) #print item #print num line_strip = (line.strip()) item_split_component=line_strip.split('component') found=line.find('component') if found > 0: print >> file, 'component' + item_split_component[1] else: if num == 1: print >> file, item[0] parse_file.close() file.close() return def parse_text_map(str): if os.path.exists('parse_text.map'): os.remove('parse_text.map') file=open('parse_text.map', 'w') if os.path.exists('temp_text.map'): os.remove('temp_text.map') temp_file=open('temp_text.map', 'w') text_file=open('image/text_image2_ns.map', 'r') text_all_lines = text_file.readlines() count=0 temp_count=1; for text_line in text_all_lines: item = filter(None, text_line.strip().split(' ')) num = len(item) line_strip = (text_line.strip()) item_split_bank=line_strip.split(' ') found_bss=text_line.find('.bss.') found_bdram=text_line.find('.bdsram.') found_fdram=text_line.find('.bfsram.') if found_bss>0: if num==1: temp_count=count+1 else: if (count!=temp_count) and (found_bdram<0) and (found_fdram<0): temp_file.write(text_line) count=count+1 temp_file.close() parse_file=open('temp_text.map', 'r') parse_file = 'temp_text.map' if (str=='flash'): command = "grep" + " 0x0e0 " + parse_file + " | grep -e '\.o$' -e '\.o)$'"; else: command = "grep -i" + " -e 0x100 -e 0x101 " + parse_file + " | grep -e '\.o)$' -e '\.o$'"; proc = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True) for line in proc.stdout: items = filter(None, line.strip().split(' ')) num = len(items) if num == 3 : if (str=='flash'): if (items[0].find("0x0e")==0): print >> file, items[0] + " " + items[1] + " " + items[2] else: if (items[0].find("0x100")==0 or items[0].find("0x101")==0): print >> file, items[0] + " " + items[1] + " " + items[2] if num == 4 : if (str=='flash'): if (items[1].find("0x0e")==0 and items[0].find(".debug")!=0): print >> file, items[1] + " " + items[2] + " " + items[3] else: if ((items[1].find("0x100")==0 or items[1].find("0x101")==0) and items[0].find(".debug")!=0): print >> file, items[1] + " " + items[2] + " " + items[3] file.close() return def parse_text_map_2(str): if os.path.exists('parse_text_2.map'): os.remove('parse_text_2.map') file=open('parse_text_2.map', 'w') parse_file = 'parse_text.map' first = 1 size = 0 if (str=='flash'): command = "grep" + " 0x0e0 " + parse_file + " | grep -e '\.o$' -e '\.o)$'"; else: command = "grep -i" + " -e 0x100 -e 0x101 " + parse_file + " | grep -e '\.o$' -e '\.o)$'"; proc = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True) for line in proc.stdout: items = filter(None, line.strip().split(' ')) if first == 1 : line_last = line size = int(items[1], 16) first = 0 continue items_last = filter(None, line_last.strip().split(' ')) if items[2] == items_last[2] : size = size + int(items[1], 16) else : split_line=os.path.split(items_last[2]) print >> file, hex(size) + " " + split_line[1] size = int(items[1], 16) line_last = line file.close() return def merge_size_and_objs(): if os.path.exists('parse_text_obj_size_1.map'): os.remove('parse_text_obj_size_1.map') file_result=open('parse_text_obj_size_1.map', 'w') parse_file = 'obj_list.txt' command = "grep -e '\.o)$' -e '\.o$'" + parse_file; last_item='none' last_obj_path='none' obj_size=0 file_size=0 image_size=0 proc = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True) file=open('parse_text_2.map', 'r') all_lines = file.readlines() for line in proc.stdout: items = filter(None, line.strip().split(' ')) items_split=os.path.split(items[0]) file_size=0 line_strip = (line.strip()) items_split_component=line_strip.split('component') items_split_test=line_strip.split('/', line_strip.count('/')) obj_path='' for num in xrange(17): obj_path += items_split_test[num]+"/" if (last_obj_path != obj_path): if (last_obj_path != 'none'): print >> file_result, "Total size hex: " + hex(obj_size) + " dec: %d"%obj_size print >> file_result, "============================================================================================" obj_size=0 last_obj_path=obj_path for line in all_lines: item = filter(None, line.strip().split(' ')) if items_split[1] == item[1]: file_size=file_size+int(item[0],16) print >> file_result, hex(file_size) + " " + items_split_component[1] obj_size = obj_size + file_size image_size=image_size+file_size print >> file_result, "Total size hex: " + hex(obj_size) + " dec: %d"%obj_size print >> file_result, "============================================================================================" print >> file_result, "Image size hex: " + hex(image_size) + " dec: %d"%image_size file_result.close(); file.close() return def merge_same_objlist(): if os.path.exists('merge_temp.map'): os.remove('merge_temp.map') merge_temp_file=open('merge_temp.map', 'w') file=open('parse_text_2.map', 'r') all_lines = file.readlines() total_size = 0 module_size = 0 merge_lable=[] for line in all_lines: item = filter(None, line.strip().split(' ')) num = len(item) line_strip = (line.strip()) item_split_bank=line_strip.split(' ') if item_split_bank[1] not in merge_lable: merge_lable.append(item_split_bank[1]) for i in range(len(merge_lable)): module_size = 0 for line in all_lines: item = filter(None, line.strip().split(' ')) num = len(item) line_strip = (line.strip()) item_split_bank=line_strip.split(' ') found=line.find(merge_lable[i]) if found>=0 and len(merge_lable[i]) == len(item_split_bank[1]): module_size = module_size + int(item_split_bank[0],16) print >> merge_temp_file, str(hex(module_size)) + " " + merge_lable[i] merge_temp_file.close() file.close() return def merge_size_and_objs_2(strx): if (strx=='flash'): des_file='code_size_flash.map' else: des_file='code_size_ram.map' if os.path.exists(des_file): os.remove(des_file) file_result=open(des_file, 'w') merge_same_objlist() file=open('merge_temp.map', 'r') all_lines = file.readlines() # file=open('parse_text_2.map', 'r') # all_lines = file.readlines() total_size = 0 module_size = 0 lable=[] for line in all_lines: item = filter(None, line.strip().split(' ')) num = len(item) #print item #print num line_strip = (line.strip()) item_split_bank=line_strip.split(' ') found_a=item_split_bank[1].find('.a') if found_a>0: item_split_bank_a=item_split_bank[1].split('.a') if item_split_bank_a[0] not in lable: lable.append(item_split_bank_a[0]) for i in range(len(lable)): print >> file_result, "=================================================================" module_size = 0 for line in all_lines: item = filter(None, line.strip().split(' ')) num = len(item) line_strip = (line.strip()) item_split_bank=line_strip.split(' ') found=line.find(lable[i]) if (found>0): module_size = module_size + int(item_split_bank[0],16) total_size += int(item_split_bank[0],16) stest = str(int(item_split_bank[0],16)) print >> file_result, item_split_bank[0] + "\t\t\t" + stest + "\t\t\t" + item_split_bank[1] print >> file_result, "\n" + "total:" print >> file_result, str(hex(module_size)) + "\t\t\t" + str(module_size) + '\n' if os.path.exists('sort_temp_file.map'): os.remove('sort_temp_file.map') file_sort_temp=open('sort_temp_file.map', 'w') for line in all_lines: item = filter(None, line.strip().split(' ')) line_strip = (line.strip()) item_split_bank=line_strip.split(' ') found=line.find('.a') if (found<0): stest = str(int(item_split_bank[0],16)) print >> file_sort_temp, item_split_bank[0] + " " + stest + " " + item_split_bank[1] file_sort_temp.close() sort_lable_wifi=['wifi_','lwip_netconf', 'wifi_interactive_mode', 'atcmd_sys','atcmd_wifi', 'tcptest', 'wlan_', 'ping_'] sort_lable_per=['rtl8721d', 'platform', 'main', 'example_entry', '_api.'] sort_lable_shell=['shell', 'log_', 'monitor', 'low_level_io', 'rtl_trace'] sort_lable_os=['croutine', 'event_groups', 'list', 'queue', 'tasks', 'timers', 'heap_5', 'port', 'freertos_', 'osdep_', 'device_lock'] file_sort_temp_r=open('sort_temp_file.map', 'r') all_lines_sort = file_sort_temp_r.readlines() array_flag=[0 for i in range(len(all_lines_sort))] temp_flag=0 print >> file_result, "=================================================================" module_size=0 for all_lines_sort_t in all_lines_sort: item = filter(None, all_lines_sort_t.strip().split(' ')) num = len(item) line_strip = (all_lines_sort_t.strip()) item_split_bank=line_strip.split(' ') temp_flag=0 for idxn in sort_lable_wifi: found = item_split_bank[2].find(idxn) if found>=0: temp_flag=1 break if (temp_flag==1): if(array_flag[all_lines_sort.index(all_lines_sort_t)]==0): module_size = module_size + int(item_split_bank[0],16) total_size += int(item_split_bank[0],16) stest = str(int(item_split_bank[0],16)) print >> file_result, item_split_bank[0] + "\t\t\t" + stest + "\t\t\t" + item_split_bank[2] array_flag[all_lines_sort.index(all_lines_sort_t)]=1 if module_size!=0: print >> file_result, "\n" + "total:" print >> file_result, str(hex(module_size)) + "\t\t\t" + str(module_size) + '\n' print >> file_result, "=================================================================" file_sort_temp_r.close() file_sort_temp_r=open('sort_temp_file.map', 'r') all_lines_sort = file_sort_temp_r.readlines() module_size=0 for all_lines_sort_t in all_lines_sort: item = filter(None, all_lines_sort_t.strip().split(' ')) num = len(item) line_strip = (all_lines_sort_t.strip()) item_split_bank=line_strip.split(' ') temp_flag=0 for idxn in sort_lable_per: found = item_split_bank[2].find(idxn) if found>=0: temp_flag=1 break if (temp_flag==1): if(array_flag[all_lines_sort.index(all_lines_sort_t)]==0): module_size = module_size + int(item_split_bank[0],16) total_size += int(item_split_bank[0],16) stest = str(int(item_split_bank[0],16)) print >> file_result, item_split_bank[0] + "\t\t\t" + stest + "\t\t\t" + item_split_bank[2] array_flag[all_lines_sort.index(all_lines_sort_t)]=1 if module_size!=0: print >> file_result, "\n" + "total:" print >> file_result, str(hex(module_size)) + "\t\t\t" + str(module_size) + '\n' print >> file_result, "=================================================================" file_sort_temp_r.close() file_sort_temp_r=open('sort_temp_file.map', 'r') all_lines_sort = file_sort_temp_r.readlines() module_size=0 for all_lines_sort_t in all_lines_sort: item = filter(None, all_lines_sort_t.strip().split(' ')) num = len(item) line_strip = (all_lines_sort_t.strip()) item_split_bank=line_strip.split(' ') temp_flag=0 for idxn in sort_lable_shell: found = item_split_bank[2].find(idxn) if found>=0: temp_flag=1 break if (temp_flag==1): if(array_flag[all_lines_sort.index(all_lines_sort_t)]==0): module_size = module_size + int(item_split_bank[0],16) total_size += int(item_split_bank[0],16) stest = str(int(item_split_bank[0],16)) print >> file_result, item_split_bank[0] + "\t\t\t" + stest + "\t\t\t" + item_split_bank[2] array_flag[all_lines_sort.index(all_lines_sort_t)]=1 if module_size!=0: print >> file_result, "\n" + "total:" print >> file_result, str(hex(module_size)) + "\t\t\t" + str(module_size) + '\n' print >> file_result, "=================================================================" file_sort_temp_r.close() file_sort_temp_r=open('sort_temp_file.map', 'r') all_lines_sort = file_sort_temp_r.readlines() module_size=0 for all_lines_sort_t in all_lines_sort: item = filter(None, all_lines_sort_t.strip().split(' ')) num = len(item) line_strip = (all_lines_sort_t.strip()) item_split_bank=line_strip.split(' ') temp_flag=0 for idxn in sort_lable_os: found = item_split_bank[2].find(idxn) if found>=0: if idxn=='timers': if found==0: temp_flag=1 break else: temp_flag=1 break if (temp_flag==1): if(array_flag[all_lines_sort.index(all_lines_sort_t)]==0): module_size = module_size + int(item_split_bank[0],16) total_size += int(item_split_bank[0],16) stest = str(int(item_split_bank[0],16)) print >> file_result, item_split_bank[0] + "\t\t\t" + stest + "\t\t\t" + item_split_bank[2] array_flag[all_lines_sort.index(all_lines_sort_t)]=1 if module_size!=0: print >> file_result, "\n" + "total:" print >> file_result, str(hex(module_size)) + "\t\t\t" + str(module_size) + '\n' print >> file_result, "=================================================================" file_sort_temp_r.close() file_sort_temp_r=open('sort_temp_file.map', 'r') all_lines_sort = file_sort_temp_r.readlines() module_size=0 for all_lines_sort_t in all_lines_sort: item = filter(None, all_lines_sort_t.strip().split(' ')) num = len(item) line_strip = (all_lines_sort_t.strip()) item_split_bank=line_strip.split(' ') temp_flag=0 for idxn in sort_lable_per: found = item_split_bank[2].find(idxn) if found>=0: temp_flag=1 break for idxn in sort_lable_wifi: found = item_split_bank[2].find(idxn) if found>=0: temp_flag=1 break for idxn in sort_lable_shell: found = item_split_bank[2].find(idxn) if found>=0: temp_flag=1 break for idxn in sort_lable_os: found = item_split_bank[2].find(idxn) if found>=0: if idxn=='timers': if found==0: temp_flag=1 break else: temp_flag=1 break if (temp_flag==0): if(array_flag[all_lines_sort.index(all_lines_sort_t)]==0): module_size = module_size + int(item_split_bank[0],16) total_size += int(item_split_bank[0],16) stest = str(int(item_split_bank[0],16)) print >> file_result, item_split_bank[0] + "\t\t\t" + stest + "\t\t\t" + item_split_bank[2] array_flag[all_lines_sort.index(all_lines_sort_t)]=1 if module_size!=0: print >> file_result, "\n" + "total:" print >> file_result, str(hex(module_size)) + "\t\t\t" + str(module_size) + '\n' print >> file_result, "=================================================================" file_sort_temp_r.close() module_size=0 if module_size!=0: print >> file_result, "=================================================================" print >> file_result, "\n" + "Image size:" print >> file_result, str(hex(total_size)) + "\t\t\t" + str(total_size) + '\n' file_result.close() file.close() return if os.path.exists('image/text_image2_ns.map'): obj_list_gen() # flash code and data parse_text_map('flash') parse_text_map_2('flash') merge_size_and_objs_2('flash') #ram code and data parse_text_map('ram') parse_text_map_2('ram') merge_size_and_objs_2('ram') #remove temp files os.remove('obj_list.map') os.remove('parse_text.map') os.remove('parse_text_2.map') os.remove('merge_temp.map') os.remove('temp_text.map') os.remove('sort_temp_file.map') if os.path.exists('image/code_size_ram.map'): os.remove('image/code_size_ram.map') if os.path.exists('image/code_size_flash.map'): os.remove('image/code_size_flash.map') shutil.move('code_size_ram.map', 'image') shutil.move('code_size_flash.map', 'image')
sunghan-chang/TizenRT
build/tools/amebad/gnu_utility/code_analyze.py
Python
apache-2.0
15,949
from django.apps import AppConfig from django.contrib.admin.checks import check_admin_app from django.core import checks from django.utils.translation import ugettext_lazy as _ class SimpleAdminConfig(AppConfig): """Simple AppConfig which does not do automatic discovery.""" name = 'fact_book' verbose_name = _("World Fact Book") def ready(self): checks.register(check_admin_app, checks.Tags.admin) class AdminConfig(SimpleAdminConfig): """The default AppConfig for admin which does autodiscovery.""" def ready(self): super(AdminConfig, self).ready() self.module.autodiscover()
obitec/django-factbook
fact_book/apps.py
Python
apache-2.0
633
from moto.core.responses import BaseResponse class ReservedInstances(BaseResponse): def cancel_reserved_instances_listing(self): if self.is_not_dryrun("CancelReservedInstances"): raise NotImplementedError( "ReservedInstances.cancel_reserved_instances_listing is not yet implemented" ) def create_reserved_instances_listing(self): if self.is_not_dryrun("CreateReservedInstances"): raise NotImplementedError( "ReservedInstances.create_reserved_instances_listing is not yet implemented" ) def describe_reserved_instances(self): raise NotImplementedError( "ReservedInstances.describe_reserved_instances is not yet implemented" ) def describe_reserved_instances_listings(self): raise NotImplementedError( "ReservedInstances.describe_reserved_instances_listings is not yet implemented" ) def describe_reserved_instances_offerings(self): raise NotImplementedError( "ReservedInstances.describe_reserved_instances_offerings is not yet implemented" ) def purchase_reserved_instances_offering(self): if self.is_not_dryrun("PurchaseReservedInstances"): raise NotImplementedError( "ReservedInstances.purchase_reserved_instances_offering is not yet implemented" )
spulec/moto
moto/ec2/responses/reserved_instances.py
Python
apache-2.0
1,409
import sys from django.db.backends.base.creation import BaseDatabaseCreation class DatabaseCreation(BaseDatabaseCreation): def sql_table_creation_suffix(self): test_settings = self.connection.settings_dict['TEST'] assert test_settings['COLLATION'] is None, ( "PostgreSQL does not support collation setting at database creation time." ) if test_settings['CHARSET']: return "WITH ENCODING '%s'" % test_settings['CHARSET'] return '' def _clone_test_db(self, number, verbosity, keepdb=False): # CREATE DATABASE ... WITH TEMPLATE ... requires closing connections # to the template database. self.connection.close() qn = self.connection.ops.quote_name source_database_name = self.connection.settings_dict['NAME'] target_database_name = self.get_test_db_clone_settings(number)['NAME'] with self._nodb_connection.cursor() as cursor: try: cursor.execute("CREATE DATABASE %s WITH TEMPLATE %s" % ( qn(target_database_name), qn(source_database_name))) except Exception as e: if keepdb: return try: if verbosity >= 1: print("Destroying old test database for alias %s..." % ( self._get_database_display_str(verbosity, target_database_name), )) cursor.execute("DROP DATABASE %s" % qn(target_database_name)) cursor.execute("CREATE DATABASE %s WITH TEMPLATE %s" % ( qn(target_database_name), qn(source_database_name))) except Exception as e: sys.stderr.write("Got an error cloning the test database: %s\n" % e) sys.exit(2)
yephper/django
django/db/backends/postgresql/creation.py
Python
bsd-3-clause
1,912
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2016-03-09 19:21 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('drives', '0010_linking_up_new_foreignkeys'), ] operations = [ migrations.RemoveField( model_name='harddrive', name='host' ), migrations.RemoveField( model_name='harddrive', name='manufacturer' ), migrations.RemoveField( model_name='harddrive', name='model' ), migrations.RenameField( model_name='harddrive', old_name='host_new', new_name='host' ), migrations.RenameField( model_name='harddrive', old_name='manufacturer_new', new_name='manufacturer' ), migrations.RenameField( model_name='harddrive', old_name='model_new', new_name='model' ), ]
rohankapoorcom/drivetracker
drivetracker/drives/migrations/0011_rename_foreign_keys_new_models.py
Python
mit
1,052
"""Provides the TotalDict class.""" class TotalDict(dict): """Track the total value of all dictionary keys.""" def __init__(self): dict.__init__(self) self.total = 0 def __setitem__(self, key, value): prev_value = self[key] if key in self else 0 dict.__setitem__(self, key, value) self.total += value - prev_value
ConstantineLignos/constantinelignos.github.io
pybootcamp/examples/totaldict.py
Python
gpl-3.0
370
# 6.00x Problem Set 4A Template # # The 6.00 Word Game # Created by: Kevin Luu <luuk> and Jenna Wiens <jwiens> # Modified by: Sarina Canelake <sarina> # import random import string import os VOWELS = 'aeiou' CONSONANTS = 'bcdfghjklmnpqrstvwxyz' HAND_SIZE = 13 SCRABBLE_LETTER_VALUES = { 'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10 } # ----------------------------------- # Helper code # (you don't need to understand this helper code) WORDLIST_FILENAME = os.path.dirname(__file__)+"/words.txt" print WORDLIST_FILENAME def loadWords(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print "Loading word list from file..." # inFile: file inFile = open(WORDLIST_FILENAME, 'r', 0) # wordList: list of strings wordList = [] for line in inFile: wordList.append(line.strip().lower()) print " ", len(wordList), "words loaded." return wordList def getFrequencyDict(sequence): """ Returns a dictionary where the keys are elements of the sequence and the values are integer counts, for the number of times that an element is repeated in the sequence. sequence: string or list return: dictionary """ # freqs: dictionary (element_type -> int) freq = {} for x in sequence: freq[x] = freq.get(x,0) + 1 return freq # (end of helper code) # ----------------------------------- # # Problem #1: Scoring a word # def getWordScore(word, n): """ Returns the score for a word. Assumes the word is a valid word. The score for a word is the sum of the points for letters in the word, multiplied by the length of the word, PLUS 50 points if all n letters are used on the first turn. Letters are scored as in Scrabble; A is worth 1, B is worth 3, C is worth 3, D is worth 2, E is worth 1, and so on (see SCRABBLE_LETTER_VALUES) word: string (lowercase letters) n: integer (HAND_SIZE; i.e., hand size required for additional points) returns: int >= 0 """ score=0 for letter in word: score+=SCRABBLE_LETTER_VALUES[letter] length=len(word) score*=length if length==n: score+=50 return score # # Problem #2: Make sure you understand how this function works and what it does! # def displayHand(hand): """ Displays the letters currently in the hand. For example: >>> displayHand({'a':1, 'x':2, 'l':3, 'e':1}) Should print out something like: a x x l l l e The order of the letters is unimportant. hand: dictionary (string -> int) """ for letter in hand.keys(): for j in range(hand[letter]): print letter, # print all on the same line print # print an empty line # # Problem #2: Make sure you understand how this function works and what it does! # def dealHand(n): """ Returns a random hand containing n lowercase letters. At least n/3 the letters in the hand should be VOWELS. Hands are represented as dictionaries. The keys are letters and the values are the number of times the particular letter is repeated in that hand. n: int >= 0 returns: dictionary (string -> int) """ hand={} numVowels = n / 3 for i in range(numVowels): x = VOWELS[random.randrange(0,len(VOWELS))] hand[x] = hand.get(x, 0) + 1 for i in range(numVowels, n): x = CONSONANTS[random.randrange(0,len(CONSONANTS))] hand[x] = hand.get(x, 0) + 1 return hand # # Problem #2: Update a hand by removing letters # def updateHand(hand, word): """ Assumes that 'hand' has all the letters in word. In other words, this assumes that however many times a letter appears in 'word', 'hand' has at least as many of that letter in it. Updates the hand: uses up the letters in the given word and returns the new hand, without those letters in it. Has no side effects: does not modify hand. word: string hand: dictionary (string -> int) returns: dictionary (string -> int) """ # TO DO ... <-- Remove this comment when you code this function handCopy=hand.copy() for letter in word: handCopy[letter]-=1 if handCopy[letter]==0: del handCopy[letter] return handCopy # # Problem #3: Test word validity # def isValidWord(word, hand, wordList): """ Returns True if word is in the wordList and is entirely composed of letters in the hand. Otherwise, returns False. Does not mutate hand or wordList. word: string hand: dictionary (string -> int) wordList: list of lowercase strings """ # TO DO ... <-- Remove this comment when you code this function handCopy=hand.copy() for letter in word: if letter in handCopy: handCopy[letter]-=1 if handCopy[letter]<0: return False else: return False if word in wordList: return True return False # # Problem #4: Playing a hand # def calculateHandlen(hand): """ Returns the length (number of letters) in the current hand. hand: dictionary (string-> int) returns: integer """ # TO DO... <-- Remove this comment when you code this function length=0 for key in hand.keys(): length+=hand[key] return length def playHand(hand, wordList, n): """ Allows the user to play the given hand, as follows: * The hand is displayed. * The user may input a word or a single period (the string ".") to indicate they're done playing * Invalid words are rejected, and a message is displayed asking the user to choose another word until they enter a valid word or "." * When a valid word is entered, it uses up letters from the hand. * After every valid word: the score for that word is displayed, the remaining letters in the hand are displayed, and the user is asked to input another word. * The sum of the word scores is displayed when the hand finishes. * The hand finishes when there are no more unused letters or the user inputs a "." hand: dictionary (string -> int) wordList: list of lowercase strings n: integer (HAND_SIZE; i.e., hand size required for additional points) """ # BEGIN PSEUDOCODE <-- Remove this comment when you code this function; do your coding within the pseudocode (leaving those comments in-place!) # Keep track of the total score totalScore=0 # As long as there are still letters left in the hand: while calculateHandlen(hand)>0: # Display the hand print "\nCurrent Hand: ", displayHand(hand) # Ask user for input word=raw_input('Enter word, or a "." to indicate you are finished: ') # If the input is a single period: if word=='.': # End the game (break out of the loop) break # Otherwise (the input is not a single period): else: # If the word is not valid: if not isValidWord(word, hand, wordList): # Reject invalid word (print a message followed by a blank line) print "Invalid word, please try again." # Otherwise (the word is valid): else: # Tell the user how many points the word earned, and the updated total score, in one line followed by a blank line score=getWordScore(word, n) totalScore+=score print '"'+word+'" earned ',str(score), " points. Total: ",str(totalScore)+" points" # Update the hand hand=updateHand(hand,word) # Game is over (user entered a '.' or ran out of letters), so tell user the total score if word==".": print "Goodbye! ", else: print "\nRun out of letters. ", print "Total score: "+str(totalScore)+" points" # # Problem #5: Playing a game # def playGame(wordList): """ Allow the user to play an arbitrary number of hands. 1) Asks the user to input 'n' or 'r' or 'e'. * If the user inputs 'n', let the user play a new (random) hand. * If the user inputs 'r', let the user play the last hand again. * If the user inputs 'e', exit the game. * If the user inputs anything else, tell them their input was invalid. 2) When done playing the hand, repeat from step 1 """ # TO DO ... <-- Remove this comment when you code this function newHand={} while True: choice=raw_input("Enter n to deal a new hand, r to replay the last hand, or e to end game: ") if choice=='n': newHand=dealHand(HAND_SIZE) playHand(newHand, wordList, HAND_SIZE) elif choice=='r': if len(newHand)==0: print "You have not played hand yet. Please play a new hand first!" else: playHand(newHand, wordList, HAND_SIZE) elif choice=='e': break else: print 'Invalid command' # # Build data structures used for entire session and play game # if __name__ == '__main__': wordList = loadWords()
arielisidro/myprograms
python/6.00.1x Files/ps4/ps4a.py
Python
gpl-2.0
9,787
# This Python file uses the following encoding: utf-8 """ Subject line. Main text. """ from unittest import TestCase from classes.Index import index_for from classes.Variable import Variable __author__ = 'Chao Li' class TestIndexFor(TestCase): def setUp(self): self.A = Variable(1, "A", ['a1', 'a2', 'a3']) self.B = Variable(2, "B", ['b1', 'b2']) self.C = Variable(3, "C", ['c1', 'b2']) self.X = [ self.B, self.A] self.Y = [ self.C, self.B] self.Z = [ self.C, self.B, self.A] def test_IndexFor(self): """ References ---------- D. Koller and N. Friedman (2009). Probabilistic Graphical Models: Principles and Techniques. edited by . MIT Press. page 107, Figure 4.3 An example of factor product """ index_X4Z = index_for(self.X, self.Z) assert 0 == index_X4Z[0] assert 0 == index_X4Z[1] assert 1 == index_X4Z[2] assert 1 == index_X4Z[3] assert 5 == index_X4Z[10] assert 5 == index_X4Z[11] index_Y4Z = index_for(self.Y, self.Z) assert 0 == index_Y4Z[8] assert 1 == index_Y4Z[9] assert 2 == index_Y4Z[10] assert 3 == index_Y4Z[11]
chaoli314/openbn
classes/test_indexFor.py
Python
apache-2.0
1,236
# Django settings for {{ project_name }} project. import os PROJECT_PATH = os.path.abspath(os.path.dirname(__file__)) DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', '[email protected]'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': '', # Or path to database file if using sqlite3. # The following settings are not used with sqlite3: 'USER': '', 'PASSWORD': '', 'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP. 'PORT': '', # Set to empty string for default. } } # Hosts/domain names that are valid for this site; required if DEBUG is False # See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts ALLOWED_HOSTS = ['127.0.0.1'] # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # In a Windows environment this must be set to your system time zone. TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # If you set this to False, Django will not format dates, numbers and # calendars according to the current locale. USE_L10N = True # If you set this to False, Django will not use timezone-aware datetimes. USE_TZ = True # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/var/www/example.com/media/" MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash. # Examples: "http://example.com/media/", "http://media.example.com/" MEDIA_URL = '' # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/var/www/example.com/static/" STATIC_ROOT = '' # URL prefix for static files. # Example: "http://example.com/static/", "http://static.example.com/" STATIC_URL = '/static/' # Additional locations of static files STATICFILES_DIRS = ( # Put strings here, like "/home/html/static" or "C:/www/django/static". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) # Make this unique, and don't share it with anybody. SECRET_KEY = '6qdivt%_$r&86jn_%k--g&7vj3c#1pj2)enp_yyo1o$=y551y-' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', # 'django.template.loaders.eggs.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', # Uncomment the next line for simple clickjacking protection: # 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = '{{ project_name }}.urls' # Python dotted path to the WSGI application used by Django's runserver. WSGI_APPLICATION = '{{ project_name }}.wsgi.application' INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Uncomment the next line to enable the admin: # 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', '{{ project_name }}', 'sekizai', ) TEMPLATE_CONTEXT_PROCESSORS = ( 'django.contrib.auth.context_processors.auth', 'django.core.context_processors.debug', 'django.core.context_processors.i18n', 'django.core.context_processors.media', 'django.core.context_processors.static', 'django.core.context_processors.tz', 'django.core.context_processors.request', 'django.contrib.messages.context_processors.messages', 'sekizai.context_processors.sekizai', ) # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error when DEBUG=False. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } } from django.template import add_to_builtins add_to_builtins('django.templatetags.i18n') add_to_builtins('sekizai.templatetags.sekizai_tags')
IlianIliev/django-for-prototyping
prototyping_template/project_name/settings.py
Python
bsd-3-clause
5,878
import os import tempfile import unittest import logging from pyidf import ValidationLevel import pyidf from pyidf.idf import IDF from pyidf.surface_construction_elements import WindowMaterialSimpleGlazingSystem log = logging.getLogger(__name__) class TestWindowMaterialSimpleGlazingSystem(unittest.TestCase): def setUp(self): self.fd, self.path = tempfile.mkstemp() def tearDown(self): os.remove(self.path) def test_create_windowmaterialsimpleglazingsystem(self): pyidf.validation_level = ValidationLevel.error obj = WindowMaterialSimpleGlazingSystem() # alpha var_name = "Name" obj.name = var_name # real var_ufactor = 3.50005 obj.ufactor = var_ufactor # real var_solar_heat_gain_coefficient = 0.5 obj.solar_heat_gain_coefficient = var_solar_heat_gain_coefficient # real var_visible_transmittance = 0.5 obj.visible_transmittance = var_visible_transmittance idf = IDF() idf.add(obj) idf.save(self.path, check=False) with open(self.path, mode='r') as f: for line in f: log.debug(line.strip()) idf2 = IDF(self.path) self.assertEqual(idf2.windowmaterialsimpleglazingsystems[0].name, var_name) self.assertAlmostEqual(idf2.windowmaterialsimpleglazingsystems[0].ufactor, var_ufactor) self.assertAlmostEqual(idf2.windowmaterialsimpleglazingsystems[0].solar_heat_gain_coefficient, var_solar_heat_gain_coefficient) self.assertAlmostEqual(idf2.windowmaterialsimpleglazingsystems[0].visible_transmittance, var_visible_transmittance)
rbuffat/pyidf
tests/test_windowmaterialsimpleglazingsystem.py
Python
apache-2.0
1,672
# -*- coding: utf-8 -*- # # Copyright (C) 2007-2011 UNINETT AS # # This file is part of Network Administration Visualized (NAV). # # NAV is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License version 2 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 General Public License for more # details. You should have received a copy of the GNU General Public License # along with NAV. If not, see <http://www.gnu.org/licenses/>. # """Django URL config for ipdevinfo""" from django.conf.urls.defaults import url, patterns from nav.web.ipdevinfo.views import (search, service_list, service_matrix, port_counter_graph) from nav.web.ipdevinfo.views import (ipdev_details, module_details, port_details, get_port_view, render_affected, get_graphite_render_url, render_host_info) # The patterns are relative to the base URL of the subsystem urlpatterns = patterns('', # Search url(r'^$', search, name='ipdevinfo-search'), # Service list url(r'^service/$', service_list, name='ipdevinfo-service-list-all'), url(r'^service/handler=(?P<handler>\w+)/$', service_list, name='ipdevinfo-service-list-handler'), # Service matrix url(r'^service/matrix/$', service_matrix, name='ipdevinfo-service-matrix'), # IP Device details url(r'^ip=(?P<addr>[a-f\d\.:]+)/$', ipdev_details, name='ipdevinfo-details-by-addr'), url(r'^id=(?P<netbox_id>\d+)/$', ipdev_details, name='ipdevinfo-details-by-id'), url(r'^(?P<name>[^/]+)/$', ipdev_details, name='ipdevinfo-details-by-name'), # Module details url(r'^(?P<netbox_sysname>[^/]+)/module=(?P<module_name>.+)/$', module_details, name='ipdevinfo-module-details'), # Interface details url(r'^(?P<netbox_sysname>[^/]+)/interface=(?P<port_id>\d+)/$', port_details, name='ipdevinfo-interface-details'), url(r'^(?P<netbox_sysname>[^/]+)/ifname=(?P<port_name>[^&]+)/$', port_details, name='ipdevinfo-interface-details-by-name'), url(r'^g/port/(?P<interfaceid>\d+)/$', port_counter_graph, name='interface-counter-graph'), url(r'^g/port/(?P<interfaceid>\d+)/(?P<kind>[^/]+)/$', port_counter_graph, name='interface-counter-graph'), # Modules url(r'^(?P<netbox_sysname>.+)/modules/(?P<perspective>\w+)/$', get_port_view, name='ipdevinfo-get-port-view'), # What happens if the device goes down url(r'(?P<netboxid>\d+)/affected', render_affected, name="ipdevinfo-affected"), # DNS url(r'hostinfo/(?P<identifier>.+)', render_host_info, name="ipdevinfo-hostinfo"), #metrics url(r'graphite-render/(?P<metric>.+)/$', get_graphite_render_url, name="graphite-render-url") )
alexanderfefelov/nav
python/nav/web/ipdevinfo/urls.py
Python
gpl-2.0
3,082
""" sphinx.testing ~~~~~~~~~~~~~~ Sphinx test utilities You can require sphinx.testing pytest fixtures in a test module or a conftest file like this: pytest_plugins = 'sphinx.testing.fixtures' :copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. """
lmregus/Portfolio
python/design_patterns/env/lib/python3.7/site-packages/sphinx/testing/__init__.py
Python
mit
341
# Copyright 2009 Christopher Czyzewski # This file is part of Project Mage. # # Project Mage 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. # # Project Mage 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 Project Mage. If not, see <http://www.gnu.org/licenses/>. import os import sys import pygame import view from constants import * class View(view.View): def __init__(self, model=None, screen=None): super(View, self).__init__() def update(self, tickClock=True): self.model.background.draw(self.screen) self.model.nameBox.draw(self.screen) self.screen.blit(self.model.veil, (0,0)) if tickClock: pygame.display.flip()
Wopple/Mage
chapterNameScreen_v.py
Python
gpl-3.0
1,164
#!/usr/bin/env python """ .. module:: robotplus.py .. moduleauthor:: Zoltan Siki Sample application to nod by the totalstation """ from sys import argv, path path.append('../pyapi/') from angle import Angle from leicatca1800 import LeicaTCA1800 from serialiface import SerialIface from totalstation import TotalStation mu = LeicaTCA1800() si = SerialIface("si", "/dev/ttyUSB0") ts = TotalStation("yes", mu, si) if len(argv) < 2: yes = 1 else: yes = int(argv[1]) if yes: dhz = Angle(0) dv = Angle(30, "DEG") else: dhz = Angle(30, "DEG") dv = Angle(0) shz = Angle(0) sv = Angle(90, "DEG") n = 3 for i in range(n): ts.Move(shz - dhz, sv - dv) ts.Move(shz + dhz, sv + dv) ts.Move(shz,sv)
zsiki/ulyxes
pyapps/yesno.py
Python
gpl-2.0
729
#!/usr/bin/python3 # do pairwise essential matrix solve and back out relative poses. Then look # at relative ned heading vs. pose/essential/match heading and estimate a # yaw error. This can be fed back into the smart matcher to improve it's # results (hopefully.) # Assuming images are taking looking straight down, then given the # pose of image1 and the matches/essential matrix relative to image2, # we can compute the estimate direction in NED space image2 should be # from image1. We can also compute their actual direction based on # gps coordinates. If we trust gps, then the difference should be # comparable to the EKF yaw error. import argparse import cv2 import math import numpy as np from props import getNode from lib import camera from lib import project from lib import smart from lib import srtm from lib import transformations parser = argparse.ArgumentParser(description='Keypoint projection.') parser.add_argument('project', help='project directory') args = parser.parse_args() proj = project.ProjectMgr(args.project) proj.load_images_info() # proj.load_features(descriptors=False) proj.load_match_pairs() r2d = 180 / math.pi d2r = math.pi / 180 # lookup ned reference ref_node = getNode("/config/ned_reference", True) ref = [ ref_node.getFloat('lat_deg'), ref_node.getFloat('lon_deg'), ref_node.getFloat('alt_m') ] # setup SRTM ground interpolator srtm.initialize( ref, 6000, 6000, 30 ) smart.load(proj.analysis_dir) # compute the 3d triangulation of the matches between a pair of # images. This is super fancy when it works, but I'm struggling with # some cases that break so I clearly don't understand some nuance, or # have made a mistake somewhere. #method = cv2.RANSAC method = cv2.LMEDS def find_essential(i1, i2): # quick sanity checks if i1 == i2: return None if not i2.name in i1.match_list: return None if len(i1.match_list[i2.name]) == 0: return None if not i1.kp_list or not len(i1.kp_list): i1.load_features() if not i2.kp_list or not len(i2.kp_list): i2.load_features() # camera calibration K = camera.get_K() IK = np.linalg.inv(K) # setup data structurs of cv2 call uv1 = []; uv2 = []; indices = [] for pair in i1.match_list[i2.name]: uv1.append( i1.kp_list[ pair[0] ].pt ) uv2.append( i2.kp_list[ pair[1] ].pt ) uv1 = np.float32(uv1) uv2 = np.float32(uv2) E, mask = cv2.findEssentialMat(uv1, uv2, K, method=method) print(i1.name, 'vs', i2.name) print("E:\n", E) print() (n, R, tvec, mask) = cv2.recoverPose(E, uv1, uv2, K) print(' inliers:', n, 'of', len(uv1)) print(' R:', R) print(' tvec:', tvec) # convert R to homogeonous #Rh = np.concatenate((R, np.zeros((3,1))), axis=1) #Rh = np.concatenate((Rh, np.zeros((1,4))), axis=0) #Rh[3,3] = 1 # extract the equivalent quaternion, and invert q = transformations.quaternion_from_matrix(R) q_inv = transformations.quaternion_inverse(q) (ned1, ypr1, quat1) = i1.get_camera_pose() (ned2, ypr2, quat2) = i2.get_camera_pose() diff = np.array(ned2) - np.array(ned1) dist = np.linalg.norm( diff ) dir = diff / dist print('dist:', dist, 'ned dir:', dir[0], dir[1], dir[2]) crs_gps = 90 - math.atan2(dir[0], dir[1]) * r2d if crs_gps < 0: crs_gps += 360 if crs_gps > 360: crs_gps -= 360 print('crs_gps: %.1f' % crs_gps) Rbody2ned = i1.get_body2ned() cam2body = i1.get_cam2body() body2cam = i1.get_body2cam() est_dir = Rbody2ned.dot(cam2body).dot(R).dot(tvec) est_dir = est_dir / np.linalg.norm(est_dir) # normalize print('est dir:', est_dir.tolist()) crs_fit = 90 - math.atan2(-est_dir[0], -est_dir[1]) * r2d if crs_fit < 0: crs_fit += 360 if crs_fit > 360: crs_fit -= 360 print('est crs_fit: %.1f' % crs_fit) print("est yaw error: %.1f" % (crs_fit - crs_gps)) # print('Computing essential matrix for pairs:') # for i, i1 in enumerate(proj.image_list): # ned, ypr, quat = i1.get_camera_pose() # srtm_elev = srtm.ned_interp( [ned[0], ned[1]] ) # i1_node = smart.surface_node.getChild(i1.name, True) # i1_node.setFloat("srtm_surface_m", "%.1f" % srtm_elev) # for j, i2 in enumerate(proj.image_list): # if j > i: # find_essential(i1, i2) print("Computing affine matrix for pairs:") for i, i1 in enumerate(proj.image_list): ned, ypr, quat = i1.get_camera_pose() srtm_elev = srtm.ned_interp( [ned[0], ned[1]] ) i1_node = smart.smart_node.getChild(i1.name, True) for j, i2 in enumerate(proj.image_list): yaw_error = smart.update_yaw_error_estimate(i1, i2) smart.save(proj.analysis_dir)
UASLab/ImageAnalysis
scripts/sandbox/match-yaw1.py
Python
mit
4,737
import tensorflow as tf import numpy as np # Load in mnist dataset using one_hot from tensorflow.examples.tutorials.mnist import input_data data = input_data.read_data_sets("data/MNIST/", one_hot=True) # Get basic information about dataset print("Training Size:\t\t{}".format(len(data.train.labels))) print("Test Size:\t\t{}".format(len(data.test.labels))) # Each image size is 28px by 28px img_size = 28 img_size_flat = img_size * img_size img_shape = (img_size, img_size) num_classes = 10 batch_size = 100 data.test.cls = np.array([label.argmax() for label in data.test.labels]) X = tf.placeholder(tf.float32, [None, img_size_flat]) y_one_hot = tf.placeholder(tf.float32, [None, num_classes]) y_true = tf.placeholder(tf.int64, [None]) feed_dict_test = {X: data.test.images, y_one_hot: data.test.labels, y_true: data.test.cls} # Weight matrix that is img_size_flat X num_classes # To be modified in TF backprop weights = tf.Variable(tf.zeros([img_size_flat, num_classes])) # Bias 1D Array of size num_classes biases = tf.Variable(tf.zeros([num_classes])) # Generate logits logits = tf.matmul(X, weights) + biases predicted = tf.nn.softmax(logits) predicted_cls = tf.argmax(predicted, dimension=1) # Calculate cross entropy + cost function cost_fn = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y_one_hot)) # Using gradient decent to optimize our single layer optimizer = tf.train.GradientDescentOptimizer( learning_rate=0.5).minimize(cost_fn) correct_prediction = tf.equal(predicted_cls, y_true) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) # Create new TF session and initialize session = tf.Session() session.run(tf.global_variables_initializer()) def optimize(num_iterations): for i in range(num_iterations): x_batch, y_one_hot_batch = data.train.next_batch(batch_size) feed_dict_train = {X: x_batch, y_one_hot: y_one_hot_batch} session.run(optimizer, feed_dict=feed_dict_train) # Set up the test feed dict with the separate test data feed_dict_test = {X: data.test.images, y_one_hot: data.test.labels, y_true: data.test.cls} def optimization_run(num_iters=1): optimize(num_iterations=num_iters) acc = session.run(accuracy, feed_dict=feed_dict_test) print('Accuracy for {0} iteration: {1:.1%}'.format(num_iters, acc)) # Attempt running a varible number of times to locate where we begin to see # diminishing returns optimization_run(1) optimization_run(5) optimization_run(20) optimization_run(100) optimization_run(1000) # We can see diminishing returns after 10000 iterations optimization_run(10000) session.close()
j-crowe/digit_recognizer
single_layer.py
Python
mit
2,793
"""The tests for Core components.""" # pylint: disable=protected-access import asyncio import unittest from unittest.mock import Mock, patch import pytest import voluptuous as vol import yaml from homeassistant import config import homeassistant.components as comps from homeassistant.components.homeassistant import ( SERVICE_CHECK_CONFIG, SERVICE_RELOAD_CORE_CONFIG, SERVICE_SET_LOCATION, ) from homeassistant.const import ( ATTR_ENTITY_ID, ENTITY_MATCH_ALL, ENTITY_MATCH_NONE, EVENT_CORE_CONFIG_UPDATE, SERVICE_HOMEASSISTANT_RESTART, SERVICE_HOMEASSISTANT_STOP, SERVICE_TOGGLE, SERVICE_TURN_OFF, SERVICE_TURN_ON, STATE_OFF, STATE_ON, ) import homeassistant.core as ha from homeassistant.exceptions import HomeAssistantError, Unauthorized from homeassistant.helpers import entity from homeassistant.setup import async_setup_component from tests.common import ( async_capture_events, async_mock_service, get_test_home_assistant, mock_service, patch_yaml_files, ) def turn_on(hass, entity_id=None, **service_data): """Turn specified entity on if possible. This is a legacy helper method. Do not use it for new tests. """ if entity_id is not None: service_data[ATTR_ENTITY_ID] = entity_id hass.services.call(ha.DOMAIN, SERVICE_TURN_ON, service_data) def turn_off(hass, entity_id=None, **service_data): """Turn specified entity off. This is a legacy helper method. Do not use it for new tests. """ if entity_id is not None: service_data[ATTR_ENTITY_ID] = entity_id hass.services.call(ha.DOMAIN, SERVICE_TURN_OFF, service_data) def toggle(hass, entity_id=None, **service_data): """Toggle specified entity. This is a legacy helper method. Do not use it for new tests. """ if entity_id is not None: service_data[ATTR_ENTITY_ID] = entity_id hass.services.call(ha.DOMAIN, SERVICE_TOGGLE, service_data) def stop(hass): """Stop Home Assistant. This is a legacy helper method. Do not use it for new tests. """ hass.services.call(ha.DOMAIN, SERVICE_HOMEASSISTANT_STOP) def restart(hass): """Stop Home Assistant. This is a legacy helper method. Do not use it for new tests. """ hass.services.call(ha.DOMAIN, SERVICE_HOMEASSISTANT_RESTART) def check_config(hass): """Check the config files. This is a legacy helper method. Do not use it for new tests. """ hass.services.call(ha.DOMAIN, SERVICE_CHECK_CONFIG) def reload_core_config(hass): """Reload the core config. This is a legacy helper method. Do not use it for new tests. """ hass.services.call(ha.DOMAIN, SERVICE_RELOAD_CORE_CONFIG) class TestComponentsCore(unittest.TestCase): """Test homeassistant.components module.""" # pylint: disable=invalid-name def setUp(self): """Set up things to be run when tests are started.""" self.hass = get_test_home_assistant() assert asyncio.run_coroutine_threadsafe( async_setup_component(self.hass, "homeassistant", {}), self.hass.loop ).result() self.hass.states.set("light.Bowl", STATE_ON) self.hass.states.set("light.Ceiling", STATE_OFF) self.addCleanup(self.hass.stop) def test_is_on(self): """Test is_on method.""" assert comps.is_on(self.hass, "light.Bowl") assert not comps.is_on(self.hass, "light.Ceiling") assert comps.is_on(self.hass) assert not comps.is_on(self.hass, "non_existing.entity") def test_turn_on_without_entities(self): """Test turn_on method without entities.""" calls = mock_service(self.hass, "light", SERVICE_TURN_ON) turn_on(self.hass) self.hass.block_till_done() assert 0 == len(calls) def test_turn_on(self): """Test turn_on method.""" calls = mock_service(self.hass, "light", SERVICE_TURN_ON) turn_on(self.hass, "light.Ceiling") self.hass.block_till_done() assert 1 == len(calls) def test_turn_off(self): """Test turn_off method.""" calls = mock_service(self.hass, "light", SERVICE_TURN_OFF) turn_off(self.hass, "light.Bowl") self.hass.block_till_done() assert 1 == len(calls) def test_toggle(self): """Test toggle method.""" calls = mock_service(self.hass, "light", SERVICE_TOGGLE) toggle(self.hass, "light.Bowl") self.hass.block_till_done() assert 1 == len(calls) @patch("homeassistant.config.os.path.isfile", Mock(return_value=True)) def test_reload_core_conf(self): """Test reload core conf service.""" ent = entity.Entity() ent.entity_id = "test.entity" ent.hass = self.hass ent.schedule_update_ha_state() self.hass.block_till_done() state = self.hass.states.get("test.entity") assert state is not None assert state.state == "unknown" assert state.attributes == {} files = { config.YAML_CONFIG_FILE: yaml.dump( { ha.DOMAIN: { "latitude": 10, "longitude": 20, "customize": {"test.Entity": {"hello": "world"}}, } } ) } with patch_yaml_files(files, True): reload_core_config(self.hass) self.hass.block_till_done() assert self.hass.config.latitude == 10 assert self.hass.config.longitude == 20 ent.schedule_update_ha_state() self.hass.block_till_done() state = self.hass.states.get("test.entity") assert state is not None assert state.state == "unknown" assert state.attributes.get("hello") == "world" @patch("homeassistant.config.os.path.isfile", Mock(return_value=True)) @patch("homeassistant.components.homeassistant._LOGGER.error") @patch("homeassistant.config.async_process_ha_core_config") def test_reload_core_with_wrong_conf(self, mock_process, mock_error): """Test reload core conf service.""" files = {config.YAML_CONFIG_FILE: yaml.dump(["invalid", "config"])} with patch_yaml_files(files, True): reload_core_config(self.hass) self.hass.block_till_done() assert mock_error.called assert mock_process.called is False @patch("homeassistant.core.HomeAssistant.async_stop", return_value=None) def test_stop_homeassistant(self, mock_stop): """Test stop service.""" stop(self.hass) self.hass.block_till_done() assert mock_stop.called @patch("homeassistant.core.HomeAssistant.async_stop", return_value=None) @patch("homeassistant.config.async_check_ha_config_file", return_value=None) def test_restart_homeassistant(self, mock_check, mock_restart): """Test stop service.""" restart(self.hass) self.hass.block_till_done() assert mock_restart.called assert mock_check.called @patch("homeassistant.core.HomeAssistant.async_stop", return_value=None) @patch( "homeassistant.config.async_check_ha_config_file", side_effect=HomeAssistantError("Test error"), ) def test_restart_homeassistant_wrong_conf(self, mock_check, mock_restart): """Test stop service.""" restart(self.hass) self.hass.block_till_done() assert mock_check.called assert not mock_restart.called @patch("homeassistant.core.HomeAssistant.async_stop", return_value=None) @patch("homeassistant.config.async_check_ha_config_file", return_value=None) def test_check_config(self, mock_check, mock_stop): """Test stop service.""" check_config(self.hass) self.hass.block_till_done() assert mock_check.called assert not mock_stop.called async def test_turn_on_skips_domains_without_service(hass, caplog): """Test if turn_on is blocking domain with no service.""" await async_setup_component(hass, "homeassistant", {}) async_mock_service(hass, "light", SERVICE_TURN_ON) hass.states.async_set("light.Bowl", STATE_ON) hass.states.async_set("light.Ceiling", STATE_OFF) # We can't test if our service call results in services being called # because by mocking out the call service method, we mock out all # So we mimic how the service registry calls services service_call = ha.ServiceCall( "homeassistant", "turn_on", {"entity_id": ["light.test", "sensor.bla", "binary_sensor.blub", "light.bla"]}, ) service = hass.services._services["homeassistant"]["turn_on"] with patch( "homeassistant.core.ServiceRegistry.async_call", return_value=None, ) as mock_call: await service.job.target(service_call) assert mock_call.call_count == 1 assert mock_call.call_args_list[0][0] == ( "light", "turn_on", {"entity_id": ["light.bla", "light.test"]}, ) assert mock_call.call_args_list[0][1] == { "blocking": True, "context": service_call.context, } assert ( "The service homeassistant.turn_on does not support entities binary_sensor.blub, sensor.bla" in caplog.text ) async def test_entity_update(hass): """Test being able to call entity update.""" await async_setup_component(hass, "homeassistant", {}) with patch( "homeassistant.helpers.entity_component.async_update_entity", return_value=None, ) as mock_update: await hass.services.async_call( "homeassistant", "update_entity", {"entity_id": ["light.kitchen"]}, blocking=True, ) assert len(mock_update.mock_calls) == 1 assert mock_update.mock_calls[0][1][1] == "light.kitchen" async def test_setting_location(hass): """Test setting the location.""" await async_setup_component(hass, "homeassistant", {}) events = async_capture_events(hass, EVENT_CORE_CONFIG_UPDATE) # Just to make sure that we are updating values. assert hass.config.latitude != 30 assert hass.config.longitude != 40 await hass.services.async_call( "homeassistant", "set_location", {"latitude": 30, "longitude": 40}, blocking=True, ) assert len(events) == 1 assert hass.config.latitude == 30 assert hass.config.longitude == 40 async def test_require_admin(hass, hass_read_only_user): """Test services requiring admin.""" await async_setup_component(hass, "homeassistant", {}) for service in ( SERVICE_HOMEASSISTANT_RESTART, SERVICE_HOMEASSISTANT_STOP, SERVICE_CHECK_CONFIG, SERVICE_RELOAD_CORE_CONFIG, ): with pytest.raises(Unauthorized): await hass.services.async_call( ha.DOMAIN, service, {}, context=ha.Context(user_id=hass_read_only_user.id), blocking=True, ) assert False, f"Should have raises for {service}" with pytest.raises(Unauthorized): await hass.services.async_call( ha.DOMAIN, SERVICE_SET_LOCATION, {"latitude": 0, "longitude": 0}, context=ha.Context(user_id=hass_read_only_user.id), blocking=True, ) async def test_turn_on_off_toggle_schema(hass, hass_read_only_user): """Test the schemas for the turn on/off/toggle services.""" await async_setup_component(hass, "homeassistant", {}) for service in SERVICE_TURN_ON, SERVICE_TURN_OFF, SERVICE_TOGGLE: for invalid in None, "nothing", ENTITY_MATCH_ALL, ENTITY_MATCH_NONE: with pytest.raises(vol.Invalid): await hass.services.async_call( ha.DOMAIN, service, {"entity_id": invalid}, context=ha.Context(user_id=hass_read_only_user.id), blocking=True, ) async def test_not_allowing_recursion(hass, caplog): """Test we do not allow recursion.""" await async_setup_component(hass, "homeassistant", {}) for service in SERVICE_TURN_ON, SERVICE_TURN_OFF, SERVICE_TOGGLE: await hass.services.async_call( ha.DOMAIN, service, {"entity_id": "homeassistant.light"}, blocking=True, ) assert ( f"Called service homeassistant.{service} with invalid entities homeassistant.light" in caplog.text ), service
partofthething/home-assistant
tests/components/homeassistant/test_init.py
Python
apache-2.0
12,669
#!/usr/bin/python # Copyright (C) 2014 The Android Open Source Project # # 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 print_function from optparse import OptionParser import os.path import re import sys parser = OptionParser() opts, args = parser.parse_args() if not len(args): parser.error('not enough arguments') elif len(args) > 1: parser.error('too many arguments') new_version = args[0] pattern = re.compile(r'(\s*)<version>[-.\w]+</version>') for project in ['gerrit-extension-api', 'gerrit-plugin-api', 'gerrit-plugin-archetype', 'gerrit-plugin-gwt-archetype', 'gerrit-plugin-gwtui', 'gerrit-plugin-js-archetype', 'gerrit-war']: pom = os.path.join(project, 'pom.xml') try: outxml = "" found = False for line in open(pom, "r"): m = pattern.match(line) if m and not found: outxml += "%s<version>%s</version>\n" % (m.group(1), new_version) found = True else: outxml += line with open(pom, "w") as outfile: outfile.write(outxml) except IOError as err: print('error updating %s: %s' % (pom, err), file=sys.stderr)
Saulis/gerrit
tools/version.py
Python
apache-2.0
1,665
import sys, re from setuptools import setup from setuptools.command.test import test as TestCommand PYTHON3 = (sys.version_info >= (3, 0)) if PYTHON3: trepan_version ='trepan3k' else: trepan_version = 'trepan2' class PyTest(TestCommand): """ Overrides setup "test" command, taken from here: http://pytest.org/latest/goodpractises.html """ def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): # import here, cause outside the eggs aren't loaded import pytest errno = pytest.main([]) sys.exit(errno) import os def get_srcdir(): filename = os.path.normcase(os.path.dirname(os.path.abspath(__file__))) return os.path.realpath(filename) # version.py sets variable __version__. __version__ = None exec(open(os.path.join(get_srcdir(), 'pytest_trepan', 'version.py')).read()) setup( name="pytest-trepan", version=__version__, packages=['pytest_trepan'], entry_points={ 'pytest11': ['trepan = pytest_trepan.plugin'], }, install_requires=[ 'pytest', '%s>=0.8.10' % trepan_version ], zip_safe=False, # metadata for upload to PyPI author = 'Rocky Bernstein', author_email = '[email protected]', description = 'Pytest plugin for trepan debugger.', long_description=open('README.rst').read(), keywords="debugger pytest trepan", url="http://github.com/rocky/pytest-trepan", classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Topic :: Software Development :: Debuggers', "Framework :: Pytest", ], cmdclass={'test': PyTest}, )
rocky/pytest-trepan
setup.py
Python
lgpl-3.0
2,184
from pylons import c from formencode import validators as fev from formencode import All import formencode from bson import ObjectId import ew as ew_core import ew.jinja2_ew as ew from allura.lib.widgets import forms as ff from allura.lib.widgets import form_fields as ffw from allura.lib import helpers as h from forgediscussion import model as DM class OptionsAdmin(ff.AdminForm): defaults=dict( ff.ForgeForm.defaults, submit_text = 'Save') @property def fields(self): fields = [ ew.SingleSelectField( name='PostingPolicy', label='Posting Policy', options=[ ew.Option(py_value='ApproveOnceModerated', label='Approve Once Moderated'), ew.Option(py_value='ApproveAll', label='Approve All')]) ] return fields class AddForum(ff.AdminForm): template = 'jinja:forgediscussion:templates/discussion_widgets/add_forum.html' defaults=dict( ff.ForgeForm.defaults, name="add_forum", value=None, app=None, submit_text = 'Save') @property def fields(self): fields = [ ew.HiddenField(name='app_id', label='App'), ew.TextField(name='name', label='Name', validator=fev.UnicodeString()), ew.TextField(name='shortname', label='Short Name', validator=All( fev.Regex(ur"^[^\s\/\.]*$", not_empty=True, messages={ 'invalid':'Shortname cannot contain space . or /', 'empty':'You must create a short name for the forum.'}), UniqueForumShortnameValidator())), ew.TextField(name='parent', label='Parent Forum'), ew.TextField(name='description', label='Description',validator=fev.UnicodeString()), ew.TextField(name='monitoring_email', label='Monitoring Email',validator=fev.Email()), ffw.FileChooser(name='icon', label='Icon'), ew.Checkbox(name="members_only", label="Developer Only"), ew.Checkbox(name="anon_posts", label="Allow Anonymous Posts") ] return fields class AddForumShort(AddForum): template = 'jinja:forgediscussion:templates/discussion_widgets/add_forum_short.html' class UniqueForumShortnameValidator(fev.FancyValidator): def _to_python(self, value, state): forums = DM.Forum.query.find(dict(app_config_id=ObjectId(state.full_dict['app_id']))).all() value = h.really_unicode(value.lower() or '') if value in [ f.shortname for f in forums ]: raise formencode.Invalid('A forum already exists with that short name, please choose another.', value, state) return value
Bitergia/allura
ForgeDiscussion/forgediscussion/widgets/admin.py
Python
apache-2.0
2,818
# # 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. # """Dataflow credentials and authentication.""" import datetime import json import logging import os import urllib2 from oauth2client.client import GoogleCredentials from oauth2client.client import OAuth2Credentials from apache_beam.utils import retry # When we are running in GCE, we can authenticate with VM credentials. is_running_in_gce = False # When we are running in GCE, this value is set based on worker startup # information. executing_project = None def set_running_in_gce(worker_executing_project): """For internal use only; no backwards-compatibility guarantees. Informs the authentication library that we are running in GCE. When we are running in GCE, we have the option of using the VM metadata credentials for authentication to Google services. Args: worker_executing_project: The project running the workflow. This information comes from worker startup information. """ global is_running_in_gce global executing_project is_running_in_gce = True executing_project = worker_executing_project class AuthenticationException(retry.PermanentException): pass class _GCEMetadataCredentials(OAuth2Credentials): """For internal use only; no backwards-compatibility guarantees. Credential object initialized using access token from GCE VM metadata.""" def __init__(self, user_agent=None): """Create an instance of GCEMetadataCredentials. These credentials are generated by contacting the metadata server on a GCE VM instance. Args: user_agent: string, The HTTP User-Agent to provide for this application. """ super(_GCEMetadataCredentials, self).__init__( None, # access_token None, # client_id None, # client_secret None, # refresh_token datetime.datetime(2010, 1, 1), # token_expiry, set to time in past. None, # token_uri user_agent) @retry.with_exponential_backoff( retry_filter=retry.retry_on_server_errors_and_timeout_filter) def _refresh(self, http_request): refresh_time = datetime.datetime.now() metadata_root = os.environ.get( 'GCE_METADATA_ROOT', 'metadata.google.internal') token_url = ('http://{}/computeMetadata/v1/instance/service-accounts/' 'default/token').format(metadata_root) req = urllib2.Request(token_url, headers={'Metadata-Flavor': 'Google'}) token_data = json.loads(urllib2.urlopen(req).read()) self.access_token = token_data['access_token'] self.token_expiry = (refresh_time + datetime.timedelta(seconds=token_data['expires_in'])) def get_service_credentials(): """For internal use only; no backwards-compatibility guarantees. Get credentials to access Google services.""" user_agent = 'beam-python-sdk/1.0' if is_running_in_gce: # We are currently running as a GCE taskrunner worker. # # TODO(ccy): It's not entirely clear if these credentials are thread-safe. # If so, we can cache these credentials to save the overhead of creating # them again. return _GCEMetadataCredentials(user_agent=user_agent) else: client_scopes = [ 'https://www.googleapis.com/auth/bigquery', 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/devstorage.full_control', 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/datastore' ] try: credentials = GoogleCredentials.get_application_default() credentials = credentials.create_scoped(client_scopes) logging.debug('Connecting using Google Application Default ' 'Credentials.') return credentials except Exception: logging.warning('Unable to find default credentials to use.') raise
wtanaka/beam
sdks/python/apache_beam/internal/gcp/auth.py
Python
apache-2.0
4,582
"""Tests for distutils.pypirc.pypirc.""" import sys import os import unittest import tempfile from distutils.core import PyPIRCCommand from distutils.core import Distribution from distutils.log import set_threshold from distutils.log import WARN from distutils.tests import support from test.support import run_unittest PYPIRC = """\ [distutils] index-servers = server1 server2 [server1] username:me password:secret [server2] username:meagain password: secret realm:acme repository:http://another.pypi/ """ PYPIRC_OLD = """\ [server-login] username:tarek password:secret """ WANTED = """\ [distutils] index-servers = pypi [pypi] username:tarek password:xxx """ class PyPIRCCommandTestCase(support.TempdirManager, support.LoggingSilencer, support.EnvironGuard, unittest.TestCase): def setUp(self): """Patches the environment.""" super(PyPIRCCommandTestCase, self).setUp() self.tmp_dir = self.mkdtemp() os.environ['HOME'] = self.tmp_dir self.rc = os.path.join(self.tmp_dir, '.pypirc') self.dist = Distribution() class command(PyPIRCCommand): def __init__(self, dist): PyPIRCCommand.__init__(self, dist) def initialize_options(self): pass finalize_options = initialize_options self._cmd = command self.old_threshold = set_threshold(WARN) def tearDown(self): """Removes the patch.""" set_threshold(self.old_threshold) super(PyPIRCCommandTestCase, self).tearDown() def test_server_registration(self): # This test makes sure PyPIRCCommand knows how to: # 1. handle several sections in .pypirc # 2. handle the old format # new format self.write_file(self.rc, PYPIRC) cmd = self._cmd(self.dist) config = cmd._read_pypirc() config = list(sorted(config.items())) waited = [('password', 'secret'), ('realm', 'pypi'), ('repository', 'http://pypi.python.org/pypi'), ('server', 'server1'), ('username', 'me')] self.assertEqual(config, waited) # old format self.write_file(self.rc, PYPIRC_OLD) config = cmd._read_pypirc() config = list(sorted(config.items())) waited = [('password', 'secret'), ('realm', 'pypi'), ('repository', 'http://pypi.python.org/pypi'), ('server', 'server-login'), ('username', 'tarek')] self.assertEqual(config, waited) def test_server_empty_registration(self): cmd = self._cmd(self.dist) rc = cmd._get_rc_file() self.assertTrue(not os.path.exists(rc)) cmd._store_pypirc('tarek', 'xxx') self.assertTrue(os.path.exists(rc)) f = open(rc) try: content = f.read() self.assertEqual(content, WANTED) finally: f.close() def test_suite(): return unittest.makeSuite(PyPIRCCommandTestCase) if __name__ == "__main__": run_unittest(test_suite())
invisiblek/python-for-android
python3-alpha/python3-src/Lib/distutils/tests/test_config.py
Python
apache-2.0
3,149
# 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 setuptools import setup, find_packages from hueversion import VERSION setup( name = "liboozie", version = VERSION, url = 'http://github.com/cloudera/hue', description = "Oozie Libraries", packages = find_packages('src'), package_dir = {'': 'src' }, install_requires = ['setuptools', 'desktop'], # Even libraries need to be registered as desktop_apps, # if they have configuration, like this one. entry_points = { 'desktop.sdk.lib': 'liboozie=liboozie' }, )
vmanoria/bluemix-hue-filebrowser
hue-3.8.1-bluemix/desktop/libs/liboozie/setup.py
Python
gpl-2.0
1,293
from flask import jsonify from app.exceptions import ValidationError from . import api def bad_request(message): response = jsonify({'error': 'bad request', 'message': message}) response.status_code = 400 return response def unauthorized(message): response = jsonify({'error': 'unauthorized', 'message': message}) response.status_code = 401 return response def forbidden(message): response = jsonify({'error': 'forbidden', 'message': message}) response.status_code = 403 return response @api.errorhandler(ValidationError) def validation_error(e): return bad_request(e.args[0])
SteveClement/IPRangeMess
app/api_1_0/errors.py
Python
gpl-3.0
605
from django.conf import settings from django.contrib.auth.forms import AuthenticationForm from django.core.urlresolvers import reverse from django.db.models import Count from django.http import Http404, HttpResponse, HttpResponseRedirect from django.shortcuts import get_object_or_404, redirect, render from django.views.decorators.csrf import ensure_csrf_cookie from core.common import * from posts.forms import PostForm from posts.models import Post from users.models import User @ensure_csrf_cookie def post_form(request, post_id=None): user = User.objects.get(user=request.user) post = Post.objects.get(pk=post_id) if user == post.author: form = PostForm(instance=post, request=request) else: return reject_user() return render(request, 'posts/edit.html', { 'settings': settings, 'user': user, 'title': 'Edit ' + post.title, 'post': post, 'form': form, }) @ensure_csrf_cookie def gallery(request, query=None): return render(request, 'posts/booru.html', { 'settings': settings, 'user': get_user(request.user), 'posts': Post.objects.exclude(media=False, hidden=False), })
PrincessTeruko/TsunArt
posts/views.py
Python
mit
1,114
import numpy import math from datetime import datetime from datetime import timedelta from copy import copy def load_rating_file(file_path, time_format="%Y-%m-%d"): ratings = [] with open(file_path,"r") as f: for line in f.readlines(): rating = line.rstrip().split(",") rating[0] = int(rating[0]) rating[1] = int(rating[1]) rating[2] = float(rating[2]) if len(rating)==4 : rating[3] = datetime.strptime(rating[3],time_format) ratings.append(rating) return ratings def load_touch_file(file_path): touchs = [] with open(file_path,"r") as f: for line in f.readlines(): touch = line.rstrip().split(",") touch[0] = int(touch[0]) touch[1] = int(touch[1]) touchs.append(touch) return touchs class Normalization: def __init__(self): self.min_element = 0. self.max_element = 1. def log(self, R_list): for index in range(len(R_list)): R_list[index][2] = math.log(R_list[index][2]) return R_list def log_revert(self, R_list): for index in range(len(R_list)): R_list[index][2] = math.exp(R_list[index][2]) return R_list def minmax(self, R_list): self.min_element = min(list(float(rating[2]) for rating in R_list)) self.max_element = max(list(float(rating[2]) for rating in R_list)) for index in range(len(R_list)): R_list[index][2] = (R_list[index][2] - self.min_element) / (self.max_element - self.min_element) return R_list def minmax_revert(self, R_list): for index in range(len(R_list)): R_list[index][2] = (R_list[index][2] * (self.max_element - self.min_element)) + self.min_element return R_list
JalexChang/cross-media-attribution
src/mta/utility.py
Python
bsd-2-clause
1,643
# -*- coding: utf-8 -*- """ pygments.styles.perldoc ~~~~~~~~~~~~~~~~~~~~~~~ Style similar to the style used in the `perldoc`_ code blocks. .. _perldoc: http://perldoc.perl.org/ :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ from pygments.style import Style from pygments.token import Keyword, Name, Comment, String, Error, \ Number, Operator, Generic, Whitespace class PerldocStyle(Style): """ Style similar to the style used in the perldoc code blocks. """ background_color = '#eeeedd' default_style = '' styles = { Whitespace: '#bbbbbb', Comment: '#228B22', Comment.Preproc: '#1e889b', Comment.Special: '#8B008B bold', String: '#CD5555', String.Heredoc: '#1c7e71 italic', String.Regex: '#B452CD', String.Other: '#cb6c20', String.Regex: '#1c7e71', Number: '#B452CD', Operator.Word: '#8B008B', Keyword: '#8B008B bold', Keyword.Type: '#00688B', Name.Class: '#008b45 bold', Name.Exception: '#008b45 bold', Name.Function: '#008b45', Name.Namespace: '#008b45 underline', Name.Variable: '#00688B', Name.Constant: '#00688B', Name.Decorator: '#707a7c', Name.Tag: '#8B008B bold', Name.Attribute: '#658b00', Name.Builtin: '#658b00', Generic.Heading: 'bold #000080', Generic.Subheading: 'bold #800080', Generic.Deleted: '#aa0000', Generic.Inserted: '#00aa00', Generic.Error: '#aa0000', Generic.Emph: 'italic', Generic.Strong: 'bold', Generic.Prompt: '#555555', Generic.Output: '#888888', Generic.Traceback: '#aa0000', Error: 'bg:#e3d2d2 #a61717' }
hacksterio/pygments.rb
vendor/pygments-main/pygments/styles/perldoc.py
Python
mit
2,175
#! /usr/bin/env python # -*- coding:utf-8 -*- # Time-stamp: <2012-09-22 15:38 [email protected]> import pygame, random pygame.init() screen = pygame.display.set_mode((0,0),pygame.FULLSCREEN) pygame.mouse.set_visible(False) r = screen.get_rect() W, H = r.width, r.height WHITE = (255, 255, 255) BLACK = (0, 0, 0) ntrials = 10 reaction_times = [] try: for t in range(ntrials): waiting_time=random.randint(1000,2000) pygame.time.delay(waiting_time) pygame.event.clear() t0 = pygame.time.get_ticks() pygame.draw.circle(screen, WHITE, (W/2, H/2), 4) pygame.display.update() buttonpressed = False while not(buttonpressed): for ev in pygame.event.get(): if ev.type == pygame.MOUSEBUTTONDOWN: t1 = pygame.time.get_ticks() buttonpressed = True if ev.type == pygame.KEYDOWN and ev.key == pygame.K_ESCAPE: raise Exception() reaction_times.append(t1-t0) screen.fill(BLACK) pygame.display.update() except: pass finally: saveresults = file('reaction_times.csv','w') for t,r in enumerate(reaction_times): saveresults.write(str(t) + ", " + str(r) +"\n") saveresults.close() pygame.quit()
chrplr/AIP2015
resources/python-scripts/simple-detection.py
Python
gpl-2.0
1,355
# -*- coding: utf-8 -*- # © 2016 Andrea Cometa # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from . import distinta_qweb
linkitspa/l10n-italy
l10n_it_ricevute_bancarie/report/__init__.py
Python
agpl-3.0
141
#!/usr/bin/env python from fabric.api import local, require, settings, task from fabric.state import env from termcolor import colored import app_config # Other fabfiles import assets import data import issues import render import text import utils if app_config.DEPLOY_TO_SERVERS: import servers if app_config.DEPLOY_CRONTAB: import cron_jobs """ Base configuration """ env.user = app_config.SERVER_USER env.forward_agent = True env.hosts = [] env.settings = None """ Environments Changing environment requires a full-stack test. An environment points to both a server and an S3 bucket. """ @task def production(): """ Run as though on production. """ env.settings = 'production' app_config.configure_targets(env.settings) env.hosts = app_config.SERVERS @task def staging(): """ Run as though on staging. """ env.settings = 'staging' app_config.configure_targets(env.settings) env.hosts = app_config.SERVERS """ Branches Changing branches requires deploying that branch to a host. """ @task def stable(): """ Work on stable branch. """ env.branch = 'stable' @task def master(): """ Work on development branch. """ env.branch = 'master' @task def branch(branch_name): """ Work on any specified branch. """ env.branch = branch_name @task def tests(): """ Run Python unit tests. """ local('nosetests') """ Deployment Changes to deployment requires a full-stack test. Deployment has two primary functions: Pushing flat files to S3 and deploying code to a remote server if required. """ def _deploy_to_s3(path='.gzip'): """ Deploy the gzipped stuff to S3. """ # Clear files that should never be deployed local('rm -rf %s/live-data' % path) local('rm -rf %s/sitemap.xml' % path) exclude_flags = '' include_flags = '' with open('gzip_types.txt') as f: for line in f: exclude_flags += '--exclude "%s" ' % line.strip() include_flags += '--include "%s" ' % line.strip() exclude_flags += '--exclude "www/assets" ' sync = 'aws s3 sync %s/ %s --acl "public-read" ' + exclude_flags + ' --cache-control "max-age=5" --region "us-east-1"' sync_gzip = 'aws s3 sync %s/ %s --acl "public-read" --content-encoding "gzip" --exclude "*" ' + include_flags + ' --cache-control "max-age=5" --region "us-east-1"' sync_assets = 'aws s3 sync %s/ %s --acl "public-read" --cache-control "max-age=86400" --region "us-east-1"' for bucket in app_config.S3_BUCKETS: local(sync % (path, 's3://%s/' % (bucket))) local(sync_gzip % (path, 's3://%s/' % (bucket))) local(sync_assets % ('www/assets/', 's3://%s/' % (bucket))) def _gzip(in_path='www', out_path='.gzip'): """ Gzips everything in www and puts it all in gzip """ local('python gzip_assets.py %s %s' % (in_path, out_path)) @task def update(): """ Update all application data not in repository (copy, assets, etc). """ text.update() assets.sync() data.update() @task def deploy(remote='origin'): """ Deploy the latest app to S3 and, if configured, to our servers. """ require('settings', provided_by=[production, staging]) if app_config.DEPLOY_TO_SERVERS: require('branch', provided_by=[stable, master, branch]) if (app_config.DEPLOYMENT_TARGET == 'production' and env.branch != 'stable'): utils.confirm( colored("You are trying to deploy the '%s' branch to production.\nYou should really only deploy a stable branch.\nDo you know what you're doing?" % env.branch, "red") ) servers.checkout_latest(remote) servers.fabcast('text.update') servers.fabcast('assets.sync') servers.fabcast('data.update') if app_config.DEPLOY_CRONTAB: servers.install_crontab() if app_config.DEPLOY_SERVICES: servers.deploy_confs() update() render.render_all() _gzip('www', '.gzip') _deploy_to_s3() """ Destruction Changes to destruction require setup/deploy to a test host in order to test. Destruction should remove all files related to the project from both a remote host and S3. """ @task def shiva_the_destroyer(): """ Deletes the app from s3 """ require('settings', provided_by=[production, staging]) utils.confirm( colored("You are about to destroy everything deployed to %s for this project.\nDo you know what you're doing?')" % app_config.DEPLOYMENT_TARGET, "red") ) with settings(warn_only=True): sync = 'aws s3 rm %s --recursive --region "us-east-1"' for bucket in app_config.S3_BUCKETS: local(sync % ('s3://%s/' % (bucket))) if app_config.DEPLOY_TO_SERVERS: servers.delete_project() if app_config.DEPLOY_CRONTAB: servers.uninstall_crontab() if app_config.DEPLOY_SERVICES: servers.nuke_confs()
onyxfish/pixelcite
fabfile/__init__.py
Python
mit
5,020
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Hotel.notes' db.add_column(u'rsvp_hotel', 'notes', self.gf('django.db.models.fields.TextField')(default=u'None'), keep_default=False) def backwards(self, orm): # Deleting field 'Hotel.notes' db.delete_column(u'rsvp_hotel', 'notes') models = { u'rsvp.event': { 'Meta': {'object_name': 'Event'}, 'guests': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['rsvp.Guest']", 'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'location': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['rsvp.Location']", 'null': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, u'rsvp.guest': { 'Meta': {'ordering': "['-last_name', '-first_name']", 'object_name': 'Guest'}, 'attending': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'city': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'display_as': ('django.db.models.fields.CharField', [], {'max_length': '91', 'null': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '45'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '45'}), 'max_guests': ('django.db.models.fields.IntegerField', [], {'default': '0', 'null': 'True', 'blank': 'True'}), 'prefix': ('django.db.models.fields.CharField', [], {'max_length': '4', 'null': 'True', 'blank': 'True'}), 'primary': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'primary_email': ('django.db.models.fields.EmailField', [], {'max_length': '254'}), 'relation': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['rsvp.Guest']", 'null': 'True', 'blank': 'True'}), 'state': ('django.db.models.fields.CharField', [], {'max_length': '2'}), 'street_addr': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'zip_code': ('django.db.models.fields.IntegerField', [], {'max_length': '5'}) }, u'rsvp.hotel': { 'Meta': {'object_name': 'Hotel'}, 'guests': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['rsvp.Guest']", 'null': 'True', 'blank': 'True'}), 'hotel_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'nights': ('django.db.models.fields.IntegerField', [], {'max_length': '1'}), 'notes': ('django.db.models.fields.TextField', [], {}), 'total_guest_count': ('django.db.models.fields.IntegerField', [], {'max_length': '2', 'null': 'True', 'blank': 'True'}) }, u'rsvp.location': { 'Meta': {'object_name': 'Location'}, 'distance': ('django.db.models.fields.DecimalField', [], {'max_digits': '3', 'decimal_places': '2'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, u'rsvp.room': { 'Meta': {'object_name': 'Room'}, 'guests': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['rsvp.Guest']", 'null': 'True', 'blank': 'True'}), 'hotel': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['rsvp.Hotel']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'max_occupancy': ('django.db.models.fields.IntegerField', [], {}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'room_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['rsvp.Roomtype']", 'null': 'True', 'blank': 'True'}) }, u'rsvp.roomtype': { 'Meta': {'object_name': 'Roomtype'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, u'rsvp.table': { 'Meta': {'object_name': 'Table'}, 'guests': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['rsvp.Guest']", 'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}) } } complete_apps = ['rsvp']
gboone/wedding.harmsboone.org
rsvp/migrations/0015_auto__add_field_hotel_notes.py
Python
mit
5,269
# coding: utf8 { '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" is een SQL-expressie zoals "field1=\'newvalue\'". U kunt de resultaten van een JOIN niet updaten of wissen', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', '%s rows deleted': '%s kaarten gewist', '%s rows updated': '*** %s kaarten veranderd', 'About': 'Info', 'Act': 'Act', 'Add': 'Voegtoe', 'Admin Panel': 'Admin Paneel', 'Are you sure to delete this category?': 'Weet u zeker dat u deze categorie wilt wissen?', 'Are you sure you want to delete this category?': 'Weet u zeker dat u deze categorie wilt wissen?', 'Article added': 'Artikel toegevoegd', 'Articles in Archive ': 'Artikel in Archief ', 'Articles with ': 'Artikel met ', 'Articles with category': 'Artikel met categorie', 'Articles with tag': 'Artikelen with kenmerk', 'Available databases and tables': 'Beschikbare gegevensbestanden en tabellen', 'Avatar uploaded': 'Avatar opgestuurd', 'Avatars are disable.': 'Avatars zijn uitgeschakeld.', 'Avatars are disabled.': 'Avatars zijn uitgeschakeld.', 'Back to the index page': 'Terug naar de startpagina', 'Cannot be empty': 'Mag niet leeg zijn', 'Cats': 'Catn', 'Change Avatar': 'Verander Avatar', 'Change about': 'Verander info', 'Change author': 'Verander auteur', 'Change content': 'Verander inhoud', 'Change css': 'Verander css', 'Change description': 'Verander omschrijving', 'Change email': 'Verander e-mail', 'Change extract': 'Verander samenvatting', 'Change first name': 'Verander voornaam', 'Change footer': 'Verander voettekst', 'Change front page': 'Verander voorpagina', 'Change keywords (sep. by ,)': 'Verander trefwoorden (gesch. dr. ,)', 'Change last name': 'Verander achternaam', 'Change logo url': 'Verander logo url', 'Change name': 'Verander naam', 'Change password': 'Verander wachtwoord', 'Change site information': 'Verander site informatie', 'Change subtitle': 'Verander de subtitel', 'Change title': 'Verander de titel', 'Change url': 'Verander de url', 'Check to delete': 'Vink aan om te wissen', 'Check to delete:': 'Vink aan om te wissen:', 'Click if you want to make this article a link to a site, to list in panels need to be a page also': 'Klik als u van dit artikel een link naar een site wilt maken. (Om getoond te worden in de panelen moet het ook een Pagina zijn)', 'Click if you want to make this article a page': 'Klik als u van dit artikel een Pagina (met menuknop) wilt maken', 'Click to change about content': 'Klik om Info aan te passen', 'Click to change categories of this article': 'Klik om categorieën van artikel aan te passen', 'Click to change footer content': 'Klik om voettekst aan te passen', 'Click to change keywords of the site': 'Klik om trefwoorden aan te passen', 'Click to change keywords of this article': 'Klik om trefwoorden aan te passen', 'Click to change name of this article': 'Klik om aan te passen name of this article', 'Click to change the content of the article, content is all the body of the article': 'Klik om inhoud van artikel aan te passen, inhoud de z.g. body van het artikel', 'Click to change the description of the site': 'Klik om omschrijving van de site aan te passen', 'Click to change the extract of the article, extract is a slice of the content you want to show in search': 'Klik om aan te passen the extract of the article, extract is a slice of the content you want to show in search', 'Click to change the frontpage of the site': 'Klik om voorpagina aan te passen', 'Click to change the logo': 'Klik om het logo aan te passen', 'Click to change the subtitle of the site': 'Klik om subtitel van de site aan te passen', 'Click to change the title of the article': 'Klik om titel van artikel aan te passen', 'Click to change the title of the site': 'Klik om titel van de site aan te passen', 'Click to delete this article': 'Klik om dit artikel te wissen', 'Click to preview the article (publish or not)': 'Klik om dit artikel te bekijken (publiek of niet)', 'Click to publish this article': 'Klik omdit artikel te publiceren', 'Client IP': 'Client IP', 'Close this window': 'Sluit dit venster', 'Comment edit': 'Comment aanpassing', 'Content': 'Inhoud', 'Controller': 'Controller', 'Copyright': 'Copyright', 'Create new article': 'Maak nieuw artikel', 'Current request': 'Huidige request', 'Current response': 'Huidige response', 'Current session': 'Huidige session', 'DB Model': 'DB Model', 'Database': 'Database', 'Delete:': 'Wis:', 'Description': 'Omschrijving', 'E-mail': 'E-mail', 'Edit': 'Verander', 'Edit This App': 'Pas deze App aan', 'Edit current record': 'Pas huidige kaart aan', 'Error 400!': 'Fout 400!', 'Error 404!': 'Fout 404!', 'Extract': 'Extract', 'First name': 'Voornaam', 'Footer': 'Voettekst', 'Front Page': 'Voorpagina', 'Go back to main page': 'Ga terug naar start pagina', 'Group %(group_id)s created': 'Groep %(group_id)s aangemaakt', 'Group ID': 'Groep ID', 'Group uniquely assigned to user %(id)s': 'Groep exclusief toegekend aan gebruiker %(id)s', 'Hello World': 'Salve Mondo', 'Home': 'Start', 'Image': 'Image', 'Import/Export': 'Import/Export', 'Index': 'Index', 'Internal State': 'Internal State', 'Invalid Query': 'Query invalida', 'Invalid email': 'Invalid email', 'Invalid login': 'Invalid login', 'Invalid password': 'Invalid password', 'Keywords': 'Keywords', 'Language': 'Language', 'Last name': 'Last name', 'Layout': 'Layout', 'Leave a Reply': 'Leave a Reply', 'List articles': 'List articles', 'Logged in': 'Logged in', 'Logged out': 'Logged out', 'Login': 'Login', 'Logo': 'Logo', 'Logout': 'Logout', 'Lost password': 'Lost password', 'Main Menu': 'Main Menu', 'Make sure all words are spelled correctly': 'Make sure all words are spelled correctly', 'Menu Model': 'Menu Model', 'My Profile': 'Mijn profiel', 'NO': 'NO', 'Name': 'Naam', 'New Record': 'Nieuw Record', 'New password': 'Nieuw password', 'No Title': 'Geen Titel', 'No articles': 'Geen artikelen', 'No comments loaded yet!. If persist enable javascript or update your browser.': 'Commentaren nog niet geladen! Als dit zo blijft zet javascript-ondersteuning aan of ververs browser.', 'No databases in this application': 'Geen databases in deze applicatie', 'No description': 'Geen omschrijving', 'No message receive from server': 'Geen mededeling ontvangen van server', 'Old password': 'Oude wachtwoord', 'Origin': 'Afkomstig', 'Page': 'Pagina', 'PageUrl': 'PaginaUrl', 'Pages': 'Pagina\'s', 'Password': 'Wachtwoord', 'Password changed': 'Wachtwoord aangepast', "Password fields don't match": "Wachtwoordvelden komen niet overeen", 'Powered by': 'Aangedreven door', 'Powered by Instant Press': 'Aangedreven door Instant Press', 'Powered by Web2py Enterprise Framework': 'Aangedreven door Web2py Enterprise Framework', 'Powered by python': 'Aangedreven door python', 'Problem with avatars': 'Probleem met avatars', 'Problem with categorie id value!': 'Probleem met categorie id waarde!', 'Problem with id value': 'Probleem met id waarde', 'Problem with some submitted values': 'Probleem met enkele opgestuurde waardes', 'Problem with the values submitted': 'Probleem met opgestuurde waardes', 'Profile': 'Profiel', 'Public': 'Publiek', 'Query:': 'Query:', 'Record %(id)s updated': 'Kaart %(id)s aangepast', 'Record ID': 'Kaart ID', 'Record Updated': 'Kaart Aangepast', 'Refresh': 'Ververs', 'Register': 'Registeer', 'Registration key': 'Registratie sleutel', 'Registration successful': 'Registratie successful', 'Reload the list': 'Ververs de lijst', 'Remember me (for 30 days)': 'Onthoud me (30 dagen)', 'Request reset password': 'Verzoek om wachtwoord terug te zetten', 'Reset Password key': 'Zet Wachtwoord terug', 'Role': 'Rol', 'Rows in table': 'Rijen in tabel', 'Rows selected': 'Rijen geselecteerd', 'Rss': 'Rss', 'Rss last comments': 'Rss laatste commentaren', 'Rss last posts': 'Rss laatste plaatsingen', 'Save the content': 'Sla de inhoud op', 'Search': 'Zoek', 'Search in title': 'Zoek in de titel', 'Show articles': 'Toon artikelen', 'Show categories': 'Toon categorieën', 'Show comments': 'Toon commentaren', 'Show images': 'Toon beeldmateriaal', 'Show links': 'Toon verwijzingen', 'Show or hide the admin panel': 'Toon of verberg beheerpaneel', 'Show styles': 'Toon sjablonen', 'Show the list of articles': 'Toon de artikellijst', 'Show the list of categories': 'Toon de categorielijst', 'Show the list of comments': 'Toon de commentaarijst', 'Show the list of images': 'Toon de lijst met beeldmateriaal', 'Show the list of links': 'Toon de verwijzingenlijst', 'Show the list of styles': 'Toon de sjablonenlijst', 'Show the list of users': 'Toon de gebruikerslijst', 'Show users': 'Toon gebruiker', 'Showing': 'Toont', 'Sign in': 'Log in', 'Sign in with your google account': 'Log in met uw google registratie', "Sorry, but this article doesn't exist!": 'Sorry, dit artikel bestaat niet!', 'Stylesheet': 'Sjabloon', 'Submit': 'Stuurop', 'Subtitle': 'Subtitel', 'Sure you want to delete this article?': 'Weet u zeker dat u dit artikel wilt wissen?', 'Sure you want to delete this comment?': 'Weet u zeker dat u dit commentaaar wilt wissen?', 'Sure you want to delete this image?': 'Weet u zeker dat u dit plaatje wilt wissen?', 'Sure you want to delete this link?': 'Weet u zeker dat deze verwijzing wilt wissen?', 'Sure you want to delete this object?': 'Weet u zeker dat u dit object wilt wissen?', 'Sure you want to delete this style?': 'Weet u zeker dat dit sjabloon wilt wissen?', 'Sure you want to delete this user?': 'Weet u zeker dat u deze gebruiker wilt wissen?', 'Table name': 'Tabel naam', 'Tags': 'Labels', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'De "query" is a conditie zoals "db.table1.field1==\'value\'". Iets als "db.table1.field1==db.table2.field2" resulteert in een SQL JOIN.', "The article id doesn't exist": 'Het artikel id bestaat niet', "The article id or page number doesn't exist": 'Het artikel id or paginanummer bestaat niet', "The article id, page number, or reply doesn't exist": 'Het artikel id, paginanummer, or commentaar bestaat niet', "The comment id doesn't exist": 'Het comment id bestaat niet', 'The output of the file is a dictionary that was rendered by the view': 'De uitvoer van het bestand is een dictionary die omgezet is wordt door de view', 'The output of the file is a dictionary that was rendered by this view': 'De uitvoer van het bestand is een dictionary die omgezet is wordt door de view', 'The search for': 'Het zoeken naar', 'There was a problem with values of Year - Month': 'Er was een probleem met de waarden van Jaar - Maand', 'This article was updated on': 'Dit artikel is aangepast op', "This function doesn't exist": 'Deze functie bestaat niet', "This function doesn't exist!": 'Deze functie bestaat niet!', 'This is a copy of the scaffolding application': 'Dit is een kopie van de skelet applicatie', 'This is a copy of the scaffolding application.': 'Dit is een kopie van de skelet applicatie.', 'Timestamp': 'Tijdstempel', 'Title': 'Titel', 'Update:': 'Aangepast:', 'Updated': 'Aangepast', 'Upload from url': 'Haal gegeven van een url op', 'Upload your image': 'Haal uw plaatje op', 'Url to an image': 'Url naar een plaatje', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Gebruik (...)&(...) voor EN, (...)|(...) voor OF, en ~(...) voor NIET om complexere zoekopdrachten te maken.', 'Use more general keywords': 'Gebruik meer algemene trefwoorden', 'User %(id)s Logged-in': 'Gebruiker %(id)s Logde in', 'User %(id)s Logged-out': 'Gebruiker %(id)s Logde uit', 'User %(id)s Password changed': 'Gebruiker %(id)s Wachtwoord is veranderd', 'User %(id)s Password reset': 'Gebruiker %(id)s Wachtwoord teruggezet', 'User %(id)s Profile updated': 'Gebruiker %(id)s Profiel aangepast', 'User %(id)s Registered': 'Gebruiker %(id)s geregistreerd', 'User ID': 'Gebruiker ID', 'Verify Password': 'Controle wachtwoord', 'View': 'View', 'Warning: This will replace your css with the default value from current style. Are you sure you want to continue?': 'Waarschuwing dit zal de css code door de standaard waarde van het gekozen sjabloon. Wilt u echt doorgaan?', 'Welcome %s': 'Welkom %s', 'Welcome to web2py': 'Welkom bij web2py', 'Which called the function': 'Die de volgende functie aanriep:', 'You are not logged in': 'U bent niet ingelogd', 'You are successfully running web2py': 'U heeft web2py succesvol aan de praat', 'You are successfully running web2py.': 'U heeft web2py succesvol aan de praat.', 'You can modify this application and adapt it to your needs': 'U kunt deze applicatie aanpassen', 'You can modify this application and adapt it to your needs.': 'U kunt deze applicatie aanpassen.', 'You have to sign in to your account before comment': 'Als u een commenteer wilt geven, dient u eerst in te loggen', 'You need to sign in as an admin': 'U dient in te loggen als beheerder', 'You need to submit your search text.': 'U dient een zoektekst op te geven.', 'You visited the url': 'U bezocht de url', 'appadmin is disabled because insecure channel': 'appadmin is uitgeschakeld, onveilig kanaal', 'back': 'terug', 'cache': 'cache', 'change password': 'verander wachtwoord', 'click here for online examples': 'klik hier om voorbeelden te zien', 'click here for the administrative interface': 'klik hier voor beheer', 'customize me!': 'pas me aan!', 'data uploaded': 'gegevens opgestuurd', 'database': 'database', 'database %s select': 'database %s geselecteerd', 'db': 'db', 'design': 'ontwerp', 'documentation': 'documentatie', 'done!': 'gedaan!', 'edit profile': 'verander profiel', 'export as csv file': 'export als csv bestand', 'in categories': 'in categorieën', 'insert new': 'voeg nieuw(e)', 'insert new %s': 'voeg nieuw(e) %s toe', 'invalid request': 'ongeldig verzoek!', 'located in the file': 'aanwezig in bestand', 'login': 'log in', 'logout': 'log uit', 'lost password': 'vergeten wachtwoord', 'lost password?': 'vergeten wachtwoord?', 'new record inserted': 'nieuwe kaart toegevoegd', 'next 100 rows': 'volgende 100 rijen', 'not yield any results': 'gaf geen resultaat', 'or import from csv file': 'of importeer uit csv bestand', 'previous 100 rows': 'vorige 100 rijen', 'record': 'kaart', 'record does not exist': 'kaart bestaat niet', 'record id': 'kaart id', 'register': 'registreer', 'results': 'resultaten', 'selected': 'geselecteerde', 'state': 'status', 'table': 'tabel', 'unable to parse csv file': 'kon csv bestand niet verwerken', }
danisuke0781/instant-press
languages/nl.py
Python
gpl-2.0
14,840