repo_name
stringlengths
5
100
path
stringlengths
4
231
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
6
947k
score
float64
0
0.34
prefix
stringlengths
0
8.16k
middle
stringlengths
3
512
suffix
stringlengths
0
8.17k
mpvillafranca/hear-cloud
apps/audio/models.py
Python
gpl-3.0
464
0.00216
from django.db import models import datetime # Create your models he
re. class AudioFile(models.Model): # Titulo: string. No nulo # Link permanente: string. No nulo # Modo de compartir (público/privado): String # URL de la imagen: string # Descripcion: string # Duracion: int # Genero: string # Descargable: bool # Fecha creacion: datetime. No nulo. # Fecha actualizacion: datetime. No nulo. # Usuario al que
pertenece
Alberto-Beralix/Beralix
i386-squashfs-root/usr/share/system-config-printer/authconn.py
Python
gpl-3.0
18,164
0.012387
#!/usr/bin/python ## Copyright (C) 2007, 2008, 2009, 2010 Red Hat, Inc. ## Author: Tim Waugh <twaugh@redhat.com> ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## You should have received a copy of the GNU General Public License ## along with this program; if not, write to the Free Software ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import threading import cups import cupspk import gobject import gtk import os from errordialogs import * from debug import * from gettext import gettext as _ N_ = lambda x: x class AuthDialog(gtk.Dialog): AUTH_FIELD={'username': N_("Username:"), 'password': N_("Password:"), 'domain': N_("Domain:")} def __init__ (self, title=None, parent=None, flags=gtk.DIALOG_MODAL | gtk.DIALOG_NO_SEPARATOR, buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OK, gtk.RESPONSE_OK), auth_info_required=['username', 'password'], allow_remember=False): if title == None: title = _("Authentication") gtk.Dialog.__init__ (self, title, parent, flags, buttons) self.auth_info_required = auth_info_required self.set_default_response (gtk.RESPONSE_OK) self.set_border_width (6) self.set_resizable (False) hbox = gtk.HBox (False, 12) hbox.set_border_width (6) image = gtk.Image () image.set_from_stock (gtk.STOCK_DIALOG_AUTHENTICATION, gtk.ICON_SIZE_DIALOG) image.set_alignment (0.0, 0.0) hbox.pack_start (image, False, False, 0) vbox = gtk.VBox (False, 12) self.prompt_label = gtk.Label () vbox.pack_start (self.prompt_label, False, False, 0) num_fields = len (auth_info_required) table = gtk.Table (num_fields, 2) table.set_row_spacings (6) table.set_col_spacings (6) self.field_entry = [] for i in range (num_fields): field = auth_info_required[i] label = gtk.Label (_(self.AUTH_FIELD.get (field, field))) label.set_alignment (0, 0.5) table.attach (label, 0, 1, i, i + 1) entry = gtk.Entry () entry.set_visibility (field != 'password') table.attach (entry, 1, 2, i, i + 1, 0, 0) self.field_entry.append (entry) self.field_entry[num_fields - 1].set_activates_default (True) vbox.pack_start (table, False, False, 0) hbox.pack_start (vbox, False, False, 0) self.vbox.pack_start (hbox) if allow_remember: cb = gtk.CheckButton (_("Remember password")) cb.set_active (False) vbox.pack_start (cb) self.remember_checkbox = cb self.vbox.show_all () def set_prompt (self, prompt): self.prompt_label.set_markup ('<span weight="bold" size="larger">' + prompt + '</span>') self.prompt_label.set_use_markup (True) self.prompt_label.set_alignment (0, 0) self.prompt_label.set_line_wrap (True) def set_auth_info (self, auth_info): for i in range (len (self.field_entry)): self.field_entry[i].set_text (auth_info[i]) def get_auth_info (self): return map (lambda x: x.get_text (), self.field_entry) def get_remember_password (self): try: return self.remember_checkbox.get_active () except AttributeError: return False def field_grab_focus (self, field): i = self.auth_info_required.index (field) self.field_entry[i].grab_focus () ### ### An auth-info cache. ### class _AuthInfoCache: def __init__ (self): self.creds = dict() # by (host,port) def cache_auth_info (self, data, host=None, port=None): if port == None: port = 631 self.creds[(host,port)] = data def lookup_auth_info (self, host=None, port=None): if port == None: port = 631 try: return self.creds[(host,port)] except KeyError: return None global_authinfocache = _AuthInfoCache () class Connection: def __init__ (self, parent=None, try_as_root=True, lock=False, host=None, port=None, encryption=None): if host != None: cups.setServer (host) if port != None: cups.setPort (port) if encryption != None: cups.setEncryption (encryption) self._use_password = '' self._parent = parent self._try_as_root = try_as_root self._use_user = cups.getUser () self._server = cups.getServer () self._port = cups.getPort() self._encryption = cups.getEncryption () self._prompt_allowed = True self._operation_stack = [] self._lock = lock self._gui_event = threading.Event () creds = global_authinfocache.lookup_auth_info (host=host, port=port) if creds != None: if (creds[0] != 'root' or try_as_root): (self._use_user, self._use_password) = creds del creds self._connect () def _begin_operation (self, operation): debugprint ("%s: Operation += %s" % (self, repr (operation))) self._operation_stack.append (operation) def _end_operation (self): debugprint ("%s: Operation ended" % self) self._operation_stack.pop () def _get_prompt_allowed (self, ): return self._prompt_allowed def _set_prompt_allowed (self, allowed): self._prompt_allowed = allowed def _set_lock (self, whether): self._lock = whether def _connect (self, allow_pk=True): cups.setUser (self._use_user) self._use_pk = (allow_pk and (self._server[0] == '/' or self._server == 'localhost') and os.getuid () != 0) self._use_pk = False
if self._use_pk: create_object = cupspk.Connection else: create_object = cups.Connection self._connection = create_object (host=self._server, port=self._port,
encryption=self._encryption) if self._use_pk: self._connection.set_parent(self._parent) self._user = self._use_user debugprint ("Connected as user %s" % self._user) methodtype_lambda = type (self._connection.getPrinters) methodtype_real = type (self._connection.addPrinter) for fname in dir (self._connection): if fname[0] == '_': continue fn = getattr (self._connection, fname) if not type (fn) in [methodtype_lambda, methodtype_real]: continue setattr (self, fname, self._make_binding (fname, fn)) def _make_binding (self, fname, fn): return lambda *args, **kwds: self._authloop (fname, fn, *args, **kwds) def _authloop (self, fname, fn, *args, **kwds): self._passes = 0 c = self._connection retry = False while True: try: if self._perform_authentication () == 0: break if c != self._connection: # We have reconnected. fn = getattr (self._connection, fname) c = self._connection cups.setUser (self._use_user) result = fn.__call__ (*args, **kwds) if fname == 'adminGetServerSettings': # Special case for a rubbish bit o
ds17/reptiles_gh
lianjia/lianjia.py
Python
apache-2.0
37
0.027027
# -
*- co
ding:utf-8 -*- import scrapy
Hijacker/vmbot
test/test_acl_decorators.py
Python
gpl-3.0
2,199
0.002729
# coding: utf-8 from __future__ import absolute_import, division, unicode_literals, print_function import unittest import mock from xmpp.protocol import JID, Message from vmbot.helpers import database as db from vmbot.models.user import User from vmbot.helpers.decorators import requires_role, requires_dir_chat @requires_role("admin") def role_acl(self, mess, args): return True @requires_dir_chat def dir_chat_acl(self, mess, args): return True @mock.patch.dict("config.JABBER", {'director_chatrooms': ("DirRoom@domain.tld",)}) class TestACLDecorators(unittest.TestCase): db_engine = db.create_engine("sqlite://") default_mess = Message(frm=JID("Room@domain.tld")) default_args = "" get_uname_from_mess = mock.MagicMock(name="get_uname_from_mess", return_value=JID("user@domain.tld/res")) @classmethod def setUpClass(cls): db.init_db(cls.db_engine) db.Session.configure(bind=cls.db_engine) admin_usr = User("admin@domain.tld") admin_usr.allow_admin = True sess = db.Session() sess.add(admin_usr) sess.commit() sess.close() @classmethod def tearDownClass(cls): db.Session.configure(bind=db.engine) cls.db_engine.dispose() del cls.db_engine def test_requires_invalidrole(self): self.assertRaises(ValueError, requires_role, "invalid role") def test_requires_role(self): self.get_uname_from_mess = mock.MagicMock(name="get_uname_from_mess", return_value=JID("admin@domain.tld/res")) self.assertTrue(role_acl(self, self.default_mess, self.default_args)) def test_requires_role_denied(self): self.assertIsNone(role_acl(self, self.default_mess, self.default_args))
def test_requires_dir_chat(self): self.assertTrue(dir_chat_acl(self, Message(frm=JID("DirRoom@domain.tld")), self.default_args)) def test_requires_dir_chat_denied(self): self.assertIsNone(dir_chat_acl(self, self.default_mess, self.default_
args)) if __name__ == "__main__": unittest.main()
fracpete/python-weka-wrapper-examples
src/wekaexamples/flow/for_loop.py
Python
gpl-3.0
1,959
0.001531
# This program is free software: you can redistribute it and/or m
odify # 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 WIT
HOUT 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/>. # for_loop.py # Copyright (C) 2015 Fracpete (pythonwekawrapper at gmail dot com) import traceback import weka.core.jvm as jvm from weka.flow.control import Flow, Trigger from weka.flow.source import ForLoop from weka.flow.sink import Console from weka.flow.transformer import SetStorageValue def main(): """ Just runs some example code. """ # setup the flow flow = Flow(name="example loop") outer = ForLoop() outer.name = "outer" outer.config["max"] = 3 flow.actors.append(outer) ssv = SetStorageValue() ssv.config["storage_name"] = "max" flow.actors.append(ssv) trigger = Trigger() flow.actors.append(trigger) inner = ForLoop() inner.name = "inner" inner.config["max"] = "@{max}" trigger.actors.append(inner) console = Console() trigger.actors.append(console) # run the flow msg = flow.setup() if msg is None: print("\n" + flow.tree + "\n") msg = flow.execute() if msg is not None: print("Error executing flow:\n" + msg) else: print("Error setting up flow:\n" + msg) flow.wrapup() flow.cleanup() if __name__ == "__main__": try: jvm.start() main() except Exception, e: print(traceback.format_exc()) finally: jvm.stop()
selentd/pythontools
pytools/src/IndexEval/fetchdata.py
Python
apache-2.0
5,671
0.010933
''' Created on 15.02.2015 @author: diesel ''' import datetime from indexdata import IndexData, IndexHistory import indexdatabase def _selectTrue( idxData ): return True class FetchData(): ''' classdocs ''' def __init__(self, indexName): ''' Constructor ''' self.indexName = indexName self.startDate = datetime.datetime(1900, 1, 1) self.endDate = datetime.datetime.today() self.selectFunc = _selectTrue self.indexDB = indexdatabase.getIndexDatabase() self.collection = self.indexDB.getIndexCollection(self.indexName) self.selectFunc = _selectTrue def _fetchData(self, select): history = IndexHistory() for entry in self.collection.find({'date': {'$gte': self.startDate, '$lt': self.endDate} }).sort('date'): indexEntry = IndexData() indexEntry.setDictionary(entry) if self.selectFunc( indexEntry ): history.addIndexData(indexEntry) return history ''' Get a index history by date. ''' def fetchDataByDate(self, startDate, endDate, select=_selectTrue ): self.startDate = startDate self.endDate = endDate return self._fetchData( select ) ''' Get the index history for one month ''' def fetchDataByMonth(self, year, month, select=_selectTrue ): self.startDate = datetime.datetime( year, month, 1) if month == 12: self.endDate = datetime.datetime( year + 1, 1, 1) else: self.endDate = datetime.datetime( year, month+1, 1) return self._fetchData( select ) ''' Get a list of monthly index histories ''' def fetchMonthlyHistory(self, startDate, endDate, select=_selectTrue): def _getNextMonth(year, month): if month == 12: year = year + 1 month = 1 else: month += 1 return( year, month ) def _getFirstMonth(startDate): return( startDate.year, startDate.month ) def _isEndOfPeriod(year, month, endDate): checkIsEndOfPeriod = (year >= endDate.year) checkIsEndOfPeriod = checkIsEndOfPeriod and (month >= endDate.month) return checkIsEndOfPeriod # --- start of function --- monthlyHistory = list() currentPeriod = _getFirstMonth( startDate ) while not (_isEndOfPeriod(currentPeriod[0], currentPeriod[1], endDate)): indexHistory = self.fetchDataByMonth(currentPeriod[0], currentPeriod[1], select) if indexHistory.len()
> 0: monthlyHistory.append( indexHistory ) currentPeriod = _getNextMonth(currentPeriod[0], currentPeriod[1]) return monthlyHistory def fetchSelectedHistory(self, startDate, endDate, startFunc, endFunc): isInTransaction = False meanHi
storyList = list() idxHistory = IndexHistory() for idxData in self.collection.find({'date': {'$gte': self.startDate, '$lt': self.endDate} }).sort('date'): if isInTransaction: if endFunc.checkEndTransaction( idxData, idxHistory.len() ): meanHistoryList.append( idxHistory ) isInTransaction = False else: idxHistory.addIndexData( idxData ) if not isInTransaction: if startFunc.checkStartTransaction( idxData ): isInTransaction = True idxHistory = IndexHistory() idxHistory.addIndexData( idxData ) endFunc.reset( idxData ) if isInTransaction: meanHistoryList.append( idxHistory ) return meanHistoryList def fetchHistoryValue(self, year, month, day): searchDate = datetime.datetime( year, month, day ) startDate = searchDate startDate = startDate + datetime.timedelta(-1) hasEntry = False idxEntry = IndexData() ''' if self.collection.find_one({'date': {'$lt': searchDate} }) != None: entry = None while entry == None: entry = self.collection.find_one({'date': {'$gte': startDate, '$lt': searchDate} }) if entry == None: startDate = startDate + datetime.timedelta(-1) idxEntry = IndexData() idxEntry.setDictionary(entry) return idxEntry else: return None ''' for entry in self.collection.find({'date' : {'$lt': searchDate}}).sort('date', -1).limit(1): idxEntry.setDictionary(entry) hasEntry = True if hasEntry: return idxEntry else: return None def fetchNextHistoryValue(self, year, month, day): searchDate = datetime.datetime( year, month, day ) hasEntry = False idxEntry = IndexData() for entry in self.collection.find( {'date' : {'$gte' : searchDate}}).sort('date', 1).limit(1): idxEntry.setDictionary(entry) hasEntry = True if hasEntry: return idxEntry else: return None def fetchLastDayOfMonth(self, year, month): if month == 12: month = 1 year = year + 1 else: month = month+1 return self.fetchHistoryValue( year, month, 1) if __name__ == '__main__': start = datetime.datetime(1998, 1, 2, 0, 0); end = datetime.datetime(1998, 2, 1, 0, 0) fetchData = FetchData( 'dax',) fetchData.fetchDataByDate( start, end )
ucd-cws/arcproject-wq-processing
arcproject/scripts/verify.py
Python
mit
5,159
0.024423
from datetime import datetime import tempfile import os import arcpy import pandas as pd import geodatabase_tempfile import amaptor import scripts.exceptions import scripts.funcs from .. import waterquality from ..waterquality import classes from ..waterquality import api from .. import scripts from ..scripts import funcs as wq_funcs from . import mapping class Point(object): """ This could probably just be a three-tuple instead of a class, but this keeps things more consistent """ def __init__(self, x, y, date_time, format_string=None): self.x = x self.y = y self._date_time = date_time self.date_time = None # will be set when extract_time is called if format_string: if format_string == "default": # doing it this way so we don't have to hardcode the default in multiple places self.extract_time() else: self.extract_time(format_string) def extract_time(self, format_string="%m/%d/%Y_%H:%M:%S%p"): self.date_time = datetime.strptime(self._date_time, format_string) def __repr__(self): return "Point taken at {} at location {}, {}".format(self.date_time, self.x, self.y) class SummaryFile(object): def __init__(self, path, date_field, time_format_string=None, setup_and_load=True): self.path = path self.points = [] self.crs_code = None self.date_field = date_field self.time_format_string = time_format_string if setup_and_load: self.get_crs() self.load_points() if time_format_string: self.extract_time() def get_crs(self): desc = arcpy.Describe(self.path) self.crs_code = desc.spatialReference.factoryCode del desc def load_points(self): for row in arcpy.da.SearchCursor(self.path, ["SHAPE@XY", self.date_field]): self.points.append(Point( row[0][0], row[0][1], row[1] ) ) def extract_time(self): for
point in self.points: point.extract_time(self.time_format_string) def check_in_same_projection(summary_file, verification_date): """ Checks t
he summary file against the spatial reference of the records for a provided date - returns a reprojected version of it that matches the spatial reference of the stored features :param summary_file: :param verification_date: :return: """ # get some records wq = api.get_wq_for_date(verification_date) sr_code = wq_funcs.get_wq_df_spatial_reference(wq) return scripts.funcs.reproject_features(summary_file, sr_code) def verify_summary_file(month, year, summary_file, max_point_distance="10 Meters", max_missing_points=50, map_package_export_folder=r"C:\Users\dsx.AD3\Box Sync\arcproject\validation"): """ Given a path to a file and a list of datetime objects, loads the summary file data and verifies the data for each date has been entered into the DB :param summary_file_path: :param dates: :param date_field: :param time_format_string: :return: """ temp_points = geodatabase_tempfile.create_gdb_name("arcroject", scratch=True) try: mapping.generate_layer_for_month(month, year_to_use=year, output_location=temp_points) except scripts.exceptions.NoRecordsError: print("DATE FAILED: {} {} - no records found for that date\n".format(month, year)) raise # copy it out so we can add the Near fields temp_summary_file_location = geodatabase_tempfile.create_gdb_name("arcrproject_summary_file", scratch=True) print("Verification feature class at {}".format(temp_summary_file_location)) arcpy.CopyFeatures_management(summary_file, temp_summary_file_location) print('Running Near to Find Missing Locations') arcpy.Near_analysis(temp_summary_file_location, temp_points, max_point_distance) print("Reading Results for Missing Locations") print("") missing_locations = arcpy.da.SearchCursor( in_table=temp_summary_file_location, field_names=["GPS_Date", "NEAR_FID"], where_clause="NEAR_FID IS NULL OR NEAR_FID = -1", ) num_missing = 0 missing_dates = {} for point in missing_locations: num_missing += 1 missing_dates[datetime.strftime(point[0], "%x")] = 1 # use the locale-appropriate date as the key in the dictionary status = None if num_missing > max_missing_points: # if we cross the threshold for notification print("CROSSED THRESHOLD: {} Missing Points. Possibly missing transects".format(num_missing)) for key in missing_dates.keys(): print("Unmatched point(s) on {}".format(key)) status = False map_output = tempfile.mktemp(prefix="missing_data_{}_{}".format(month, year), ) project = mapping.map_missing_segments(temp_summary_file_location, temp_points, map_output) export_map_package(project, map_package_export_folder, month, year) print("Map output to {}.{}".format(map_output, amaptor.MAP_EXTENSION)) else: status = True print("ALL ClEAR for {} {}".format(month, year)) print("\n") return status def export_map_package(project, folder, month, year): if not os.path.exists(folder): os.mkdir(folder) output_name = os.path.join(folder, "{}_{}.ppkx".format(month, year)) if os.path.exists(output_name): os.remove(output_name) print("Exporting project to {}".format(output_name)) project.to_package(output_name, summary="data verification", tags="data verify")
Oreder/PythonSelfStudy
Exe_02.py
Python
mit
302
0.003311
# A comment, this is so you can read your program later. # Anything after the # is ignored by python. print("I could have code like this.") # and the comment after is ignored # You can also use a comment to "disable" or comment out a
piece of code: # print "This won't run.
" print("This will run.")
larsks/python-ftn
fidonet/apps/makemsg.py
Python
gpl-3.0
3,792
0.003692
#!/usr/bin/python import sys import time import random from fidonet import Address from fidonet.formats import * import fidonet.app class App (fidonet.app.AppUsingAddresses, fidonet.app.AppUsingNames): logtag = 'fidonet.makemsg' def create_parser(self): p = super(App, self).create_parser() p.add_option('-k', '--kludge', action='append', default=[]) p.add_option('-s', '--subject') p.add_option('-T', '--time') p.add_option('-A', '--area') p.add_option('-g', '--flag', action='append', default=[]) p.add_option('--originline', '--oline')
p.add_option('--output', '--out') p.add_option('--disk', action='store_false', dest='packed') p.add_option('--packed', action='store_true', dest='packed') p.set_default('packed', True) return p def handle_args (self, args): if self.opts.packed: msg = packedmessa
ge.MessageParser.create() else: msg = diskmessage.MessageParser.create() if not self.opts.origin: try: self.opts.origin = self.cfg.get('fidonet', 'address') self.log.debug('got origin address = %s' % self.opts.origin) except: pass if not self.opts.time: self.opts.time = time.strftime('%d %b %y %H:%M:%S', time.localtime()) if self.opts.from_name: msg.fromUsername = self.opts.from_name self.log.debug('set fromUsername = %s' % msg.fromUsername) if self.opts.to_name: msg.toUsername = self.opts.to_name self.log.debug('set toUsername = %s' % msg.toUsername) if self.opts.subject: msg.subject = self.opts.subject self.log.debug('set subject = %s' % msg.subject) if self.opts.origin: msg.origAddr = Address(self.opts.origin) self.log.debug('set originAddr = %s' % msg.origAddr) if self.opts.destination: msg.destAddr = Address(self.opts.destination) self.log.debug('set destAddr = %s' % msg.destAddr) if self.opts.time: msg.dateTime = self.opts.time self.log.debug('set dateTime = %s' % msg.dateTime) # set message attributes attr = attributeword.AttributeWordParser.create() for f in self.opts.flag: attr[f] = 1 msg.attributeWord = attr if self.opts.area: msg.parsed_body.area = self.opts.area # Generate an origin line if this is an echomail post. if not self.opts.originline and self.opts.area: try: self.opts.originline = '%s (%s)' % ( self.cfg.get('fidonet', 'sysname'), Address(self.cfg.get('fidonet', 'address'))) except: pass if self.opts.originline: msg.parsed_body.origin = self.opts.originline msg.parsed_body.klines['PID:'] = ['python-ftn'] msg.parsed_body.klines['MSGID:'] = [ '%(origAddr)s ' % msg + '%08x' % self.next_message_id() ] for k in self.opts.kludge: k_name, k_val = k.split(' ', 1) msg.parsed_body.klines[k_name] = msg.parsed_body.klines.get(k_name, []) + [k_val] if args: sys.stdin = open(args[0]) if self.opts.output: sys.stdout = open(self.opts.output, 'w') msg.parsed_body.text = sys.stdin.read() msg.write(sys.stdout) def next_message_id(self): '''so really this should generate message ids from a monotonically incrementing sequence...''' return random.randint(0,2**32) if __name__ == '__main__': App.run()
Johnzero/OE7
openerp/addons/mail/mail_mail.py
Python
agpl-3.0
16,471
0.005161
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2010-today OpenERP SA (<http://www.openerp.com>) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # publis
hed by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the # GNU Affero General Public License for more details # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/> # ############################################################################## import base64 import logging import re from urllib import urlencode from urlparse import urljoin from openerp import tools from openerp import SUPERUSER_ID from openerp.osv import fields, osv from openerp.osv.orm import except_orm from openerp.tools.translate import _ _logger = logging.getLogger(__name__) class mail_mail(osv.Model): """ Model holding RFC2822 email messages to send. This model also provides facilities to queue and send new email messages. """ _name = 'mail.mail' _description = 'Outgoing Mails' _inherits = {'mail.message': 'mail_message_id'} _order = 'id desc' _columns = { 'mail_message_id': fields.many2one('mail.message', 'Message', required=True, ondelete='cascade'), 'mail_server_id': fields.many2one('ir.mail_server', 'Outgoing mail server', readonly=1), 'state': fields.selection([ ('outgoing', 'Outgoing'), ('sent', 'Sent'), ('received', 'Received'), ('exception', 'Delivery Failed'), ('cancel', 'Cancelled'), ], 'Status', readonly=True), 'auto_delete': fields.boolean('Auto Delete', help="Permanently delete this email after sending it, to save space"), 'references': fields.text('References', help='Message references, such as identifiers of previous messages', readonly=1), 'email_from': fields.char('From', help='Message sender, taken from user preferences.'), 'email_to': fields.text('To', help='Message recipients'), 'email_cc': fields.char('Cc', help='Carbon copy message recipients'), 'reply_to': fields.char('Reply-To', help='Preferred response address for the message'), 'body_html': fields.text('Rich-text Contents', help="Rich-text/HTML message"), # Auto-detected based on create() - if 'mail_message_id' was passed then this mail is a notification # and during unlink() we will not cascade delete the parent and its attachments 'notification': fields.boolean('Is Notification') } def _get_default_from(self, cr, uid, context=None): this = self.pool.get('res.users').browse(cr, uid, uid, context=context) if this.alias_domain: return '%s@%s' % (this.alias_name, this.alias_domain) elif this.email: return this.email raise osv.except_osv(_('Invalid Action!'), _("Unable to send email, please configure the sender's email address or alias.")) _defaults = { 'state': 'outgoing', 'email_from': lambda self, cr, uid, ctx=None: self._get_default_from(cr, uid, ctx), } def default_get(self, cr, uid, fields, context=None): # protection for `default_type` values leaking from menu action context (e.g. for invoices) # To remove when automatic context propagation is removed in web client if context and context.get('default_type') and context.get('default_type') not in self._all_columns['type'].column.selection: context = dict(context, default_type=None) return super(mail_mail, self).default_get(cr, uid, fields, context=context) def create(self, cr, uid, values, context=None): if 'notification' not in values and values.get('mail_message_id'): values['notification'] = True return super(mail_mail, self).create(cr, uid, values, context=context) def unlink(self, cr, uid, ids, context=None): # cascade-delete the parent message for all mails that are not created for a notification ids_to_cascade = self.search(cr, uid, [('notification', '=', False), ('id', 'in', ids)]) parent_msg_ids = [m.mail_message_id.id for m in self.browse(cr, uid, ids_to_cascade, context=context)] res = super(mail_mail, self).unlink(cr, uid, ids, context=context) self.pool.get('mail.message').unlink(cr, uid, parent_msg_ids, context=context) return res def mark_outgoing(self, cr, uid, ids, context=None): return self.write(cr, uid, ids, {'state': 'outgoing'}, context=context) def cancel(self, cr, uid, ids, context=None): return self.write(cr, uid, ids, {'state': 'cancel'}, context=context) def process_email_queue(self, cr, uid, ids=None, context=None): """Send immediately queued messages, committing after each message is sent - this is not transactional and should not be called during another transaction! :param list ids: optional list of emails ids to send. If passed no search is performed, and these ids are used instead. :param dict context: if a 'filters' key is present in context, this value will be used as an additional filter to further restrict the outgoing messages to send (by default all 'outgoing' messages are sent). """ if context is None: context = {} if not ids: filters = ['&', ('state', '=', 'outgoing'), ('type', '=', 'email')] if 'filters' in context: filters.extend(context['filters']) ids = self.search(cr, uid, filters, context=context) res = None try: # Force auto-commit - this is meant to be called by # the scheduler, and we can't allow rolling back the status # of previously sent emails! res = self.send(cr, uid, ids, auto_commit=True, context=context) except Exception: _logger.exception("Failed processing mail queue") return res def _postprocess_sent_message(self, cr, uid, mail, context=None): """Perform any post-processing necessary after sending ``mail`` successfully, including deleting it completely along with its attachment if the ``auto_delete`` flag of the mail was set. Overridden by subclasses for extra post-processing behaviors. :param browse_record mail: the mail that was just sent :return: True """ if mail.auto_delete: # done with SUPERUSER_ID to avoid giving large unlink access rights self.unlink(cr, SUPERUSER_ID, [mail.id], context=context) return True def send_get_mail_subject(self, cr, uid, mail, force=False, partner=None, context=None): """ If subject is void and record_name defined: '<Author> posted on <Resource>' :param boolean force: force the subject replacement :param browse_record mail: mail.mail browse_record :param browse_record partner: specific recipient partner """ if force or (not mail.subject and mail.model and mail.res_id): return 'Re: %s' % (mail.record_name) return mail.subject def send_get_mail_body(self, cr, uid, mail, partner=None, context=None): """ Return a specific ir_email body. The main purpose of this method is to be inherited by Portal, to add a link for signing in, in each notification email a partner receives. :param browse_record mail
huxianglin/pythonstudy
week05-胡湘林/ATM/shop/shop_conf/settings.py
Python
gpl-3.0
665
0.019549
#!/usr/bin/
env python # encoding:utf-8 # __author__: huxianglin # date: 2016-09-18 # blog: http://huxianglin.cnblogs.com/ http://xianglinhu.blog.51cto.com/ import os import logging BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) USER_DATABASE = { "name":"users", "path": os.path.join(os.path.join(BASE_DIR,"shop_data"),"users_info") } DATABASE_ENGINE="file_storage" # support mysql in the future GOODS_DATABASE={
"name":"goods", "path": os.path.join(os.path.join(BASE_DIR,"shop_data"),"goods_data.json") } LOG_INFO = { "shop_path":os.path.join(BASE_DIR,"shop_logs"), "LOG_LEVEL":logging.INFO } BANK_CARD="666666"
andysalerno/reversi_ai
agents/q_learning_agent.py
Python
mit
8,477
0.000708
"""This Q-Lea
rning neural network agent is still a work in progress and is not complete yet.""" import random from agents import Agent from keras.layers import Dense from keras.models import Sequential, model_from_json from keras.optimizers import RMSprop, SGD from util import info, opponent, color_name, numpify, best_move_val MODEL_FILENAME = 'neural/q_model' WEIGHTS_FILENAME = 'neural/q_weights' HID
DEN_SIZE = 42 ALPHA = 1.0 BATCH_SIZE = 64 WIN_REWARD = 1 LOSE_REWARD = -1 optimizer = RMSprop() # optimizer = SGD(lr=0.01, momentum=0.0) class QLearningAgent(Agent): def __init__(self, reversi, color, **kwargs): self.color = color self.reversi = reversi self.learning_enabled = kwargs.get('learning_enabled', False) self.model = self.get_model(kwargs.get('model_file', None)) self.minimax_enabled = kwargs.get('minimax', False) weights_num = kwargs.get('weights_num', '') self.load_weights(weights_num) # training values self.epsilon = 0.0 if self.learning_enabled: self.epoch = 0 self.train_count = random.choice(range(BATCH_SIZE)) self.memory = None self.prev_move = None self.prev_state = None if kwargs.get('model_file', None) is None: # if user didn't specify a model file, save the one we generated self.save_model(self.model) def set_epsilon(self, val): self.epsilon = val if not self.learning_enabled: info('Warning -- set_epsilon() was called when learning was not enabled.') def set_memory(self, memory): self.memory = memory def set_epoch(self, epoch): self.epoch = epoch def get_action(self, state, legal_moves=None): """Agent method, called by the game to pick a move.""" if legal_moves is None: legal_moves = self.reversi.legal_moves(state) if not legal_moves: # no actions available return None else: move = None if self.epsilon > random.random(): move = random.choice(legal_moves) else: move = self.policy(state, legal_moves) if self.learning_enabled: self.train(state, legal_moves) self.prev_move = move self.prev_state = state return move def minimax(self, state, depth=2, alpha=-float('inf'), beta=float('inf')): # pdb.set_trace() """Given a state, find its minimax value.""" assert state[1] == self.color or state[1] == opponent[self.color] player_turn = True if state[1] == self.color else False legal = self.reversi.legal_moves(state) winner = self.reversi.winner(state) if not legal and winner is False: # no legal moves, but game isn't over, so pass turn return self.minimax(self.reversi.next_state(state, None)) elif depth == 0 or winner is not False: if winner == self.color: return 9999999 elif winner == opponent[self.color]: return -9999999 else: q_vals = self.model.predict(numpify(state)) best_move, best_q = best_move_val(q_vals, legal) print('best_q: {}'.format(best_q)) return best_q if player_turn: val = -float('inf') for move in legal: new_state = self.reversi.next_state(state, move) val = max(val, self.minimax(new_state, depth - 1, alpha, beta)) alpha = max(alpha, val) if beta <= alpha: break return val else: val = float('inf') for move in legal: new_state = self.reversi.next_state(state, move) val = min(val, self.minimax(new_state, depth - 1, alpha, beta)) beta = min(beta, val) if beta <= alpha: break return val def observe_win(self, state): """Called by the game at end of game to present the agent with the final board state.""" if self.learning_enabled: winner = self.reversi.winner(state) self.train(state, [], winner) def reset(self): """Resets the agent to prepare it to play another game.""" self.reset_learning() def reset_learning(self): self.prev_move = None self.prev_state = None def policy(self, state, legal_moves): """The policy of picking an action based on their weights.""" if not legal_moves: return None if not self.minimax_enabled: # don't use minimax if we're in learning mode best_move, _ = best_move_val( self.model.predict(numpify(state)), legal_moves ) return best_move else: next_states = {self.reversi.next_state( state, move): move for move in legal_moves} move_scores = [] for s in next_states.keys(): score = self.minimax(s) move_scores.append((score, s)) info('{}: {}'.format(next_states[s], score)) best_val = -float('inf') best_move = None for each in move_scores: if each[0] > best_val: best_val = each[0] best_move = next_states[each[1]] assert best_move is not None return best_move def train(self, state, legal_moves, winner=False): assert self.memory is not None, "can't train without setting memory first" self.train_count += 1 model = self.model if self.prev_state is None: # on first move, no training to do yet self.prev_state = state else: # add new info to replay memory reward = 0 if winner == self.color: reward = WIN_REWARD elif winner == opponent[self.color]: reward = LOSE_REWARD elif winner is not False: raise ValueError self.memory.remember(self.prev_state, self.prev_move, reward, state, legal_moves, winner) # get an experience from memory and train on it if self.train_count % BATCH_SIZE == 0 or winner is not False: states, targets = self.memory.get_replay( model, BATCH_SIZE, ALPHA) model.train_on_batch(states, targets) def get_model(self, filename=None): """Given a filename, load that model file; otherwise, generate a new model.""" model = None if filename: info('attempting to load model {}'.format(filename)) try: model = model_from_json(open(filename).read()) except FileNotFoundError: print('could not load file {}'.format(filename)) quit() print('loaded model file {}'.format(filename)) else: print('no model file loaded, generating new model.') size = self.reversi.size ** 2 model = Sequential() model.add(Dense(HIDDEN_SIZE, activation='relu', input_dim=size)) # model.add(Dense(HIDDEN_SIZE, activation='relu')) model.add(Dense(size)) model.compile(loss='mse', optimizer=optimizer) return model @staticmethod def save_model(model): """Given a model, save it to disk.""" as_json = model.to_json() with open(MODEL_FILENAME, 'w') as f: f.write(as_json) print('model saved to {}'.format(MODEL_FILENAME)) def save_weights(self, suffix): filename = '{}{}{}{}'.format(WEIGHTS_FILENAME, color_name[ self.color], suffix, '.h5') print('saving weights to {}'.format(filename)) self.model.save_weights(filename, overwrite=True) def load_weights(self, suffix): filen
jorgegil/kpo-pilot
KPOpilot/test/test_resources.py
Python
gpl-3.0
1,017
0.00295
# coding=utf-8 """Resources test. .. note:: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. """ __author__ = 'gil.jorge@gmail.com' __date__ = '2016-12-19' __copyright__ = 'Copyright 2016, Jorge Gil' import unittest from PyQt4.QtGui import QIcon class KPOpilotDialogTest(unitt
est.TestCase): """Test rerources work.""" def setUp(self): """Runs before each test.""" pass def tearDown(self): """Runs after each test.""" pass def test_icon_png(self): """Test we can click OK.""" path
= ':/plugins/KPOpilot/icon.png' icon = QIcon(path) self.assertFalse(icon.isNull()) if __name__ == "__main__": suite = unittest.makeSuite(KPOpilotResourcesTest) runner = unittest.TextTestRunner(verbosity=2) runner.run(suite)
hachreak/invenio-pages
setup.py
Python
gpl-2.0
4,023
0
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2015, 2016 CERN. # # Invenio is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public
License as # published by the Free Software Fou
ndation; either version 2 of the # License, or (at your option) any later version. # # Invenio is distributed in the hope that it will be # useful, but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Invenio; if not, write to the # Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307, USA. # # In applying this license, CERN does not # waive the privileges and immunities granted to it by virtue of its status # as an Intergovernmental Organization or submit itself to any jurisdiction. """Static pages module for Invenio.""" import os from setuptools import find_packages, setup readme = open('README.rst').read() history = open('CHANGES.rst').read() tests_require = [ 'check-manifest>=0.25', 'coverage>=4.0', 'isort>=4.2.2', 'pydocstyle>=1.0.0', 'pytest-cache>=1.0', 'pytest-cov>=1.8.0', 'pytest-pep8>=1.0.6', 'pytest>=2.8.0', ] extras_require = { 'docs': [ 'Sphinx>=1.4.2', ], 'mysql': [ 'invenio-db[mysql,versioning]>=1.0.0b2', ], 'postgresql': [ 'invenio-db[postgresql,versioning]>=1.0.0b2', ], 'sqlite': [ 'invenio-db[versioning]>=1.0.0b2', ], 'tests': tests_require, } extras_require['all'] = [] for name, reqs in extras_require.items(): if name in ('mysql', 'postgresql', 'sqlite'): continue extras_require['all'].extend(reqs) setup_requires = [ 'Babel>=1.3', 'pytest-runner>=2.6.2', ] install_requires = [ 'Flask-BabelEx>=0.9.2', 'Flask>=0.11.1', 'invenio-admin>=1.0.0a3', ] packages = find_packages() # Get the version string. Cannot be done with import! g = {} with open(os.path.join('invenio_pages', 'version.py'), 'rt') as fp: exec(fp.read(), g) version = g['__version__'] setup( name='invenio-pages', version=version, description=__doc__, long_description=readme + '\n\n' + history, keywords='invenio pages', license='GPLv2', author='CERN', author_email='info@inveniosoftware.org', url='https://github.com/inveniosoftware/invenio-pages', packages=packages, zip_safe=False, include_package_data=True, platforms='any', entry_points={ 'invenio_base.apps': [ 'invenio_pages = invenio_pages:InvenioPages', ], 'invenio_i18n.translations': [ 'messages = invenio_pages', ], 'invenio_admin.views': [ 'invenio_pages_page = invenio_pages.admin:pages_adminview', ], 'invenio_db.models': [ 'invenio_pages = invenio_pages.models', ], 'invenio_base.blueprints': [ 'invenio_pages = invenio_pages.views:blueprint', ], }, extras_require=extras_require, install_requires=install_requires, setup_requires=setup_requires, tests_require=tests_require, classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License v2 (GPLv2)', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: Implementation :: CPython', 'Development Status :: 1 - Planning', ], )
desvox/bbj
server.py
Python
mit
27,166
0.000699
from src.exceptions import BBJException, BBJParameterError, BBJUserError from src import db, schema, formatting from functools import wraps from uuid import uuid1 from sys import argv import traceback import cherrypy import sqlite3 import json dbname = "data.sqlite" # any values here may be overrided in the config.json. Any values not listed # here will have no effect on the server. default_config = { "admins": [], "port": 7099, "host": "127.0.0.1", "instance_name": "BBJ", "allow_anon": True, "debug": False } try: with open("config.json", "r") as _in: app_config = json.load(_in) # update the file with new keys if necessary for key, default_value in default_config.items(): # The application will never store a config value # as the NoneType, so users may set an option as # null in their file to reset it to default if key not in app_config or app_config[key] == None: app_config[key] = default_value # else just use the defaults except FileNotFoundError: app_config = default_config finally: with open("config.json", "w") as _out: json.dump(app_config, _out, indent=2) def api_method(function): """ A wrapper that handles encoding of objects and errors to a standard format for the API, resolves and authorizes users from header data, and prepares the arguments for each method. In the body of each api method and all the functions they utilize, BBJExceptions are caught and their attached schema is dispatched to the client. All other unhandled exceptions will throw a code 1 back at the client and log it for inspection. Errors related to JSON decoding are caught as well and returned to the client as code 0. """ function.exposed = True @wraps(function) def wrapper(self, *args, **kwargs): response = None debug = app_config["debug"] try: connection = sqlite3.connect(dbname) # read in the body from the request to a string... if cherrypy.request.method == "POST": read_in = str(cherrypy.request.body.read(), "utf8") if not read_in: # the body may be empty, not all methods require input body = {} else: body = json.loads(read_in) if not isinstance(body, dict): raise BBJParameterError("Non-JSONObject input") # lowercase all of its top-level keys body = {key.lower(): value for key, value in body.items()} else: body = {} username = cherrypy.request.headers.get("User") auth = cherrypy.request.headers.get("Auth") if (username and not auth) or (auth and not username): raise BBJParameterError( "User or Auth was given without the other.") elif not username and not auth: user = db.anon else: user = db.user_resolve(connection, username) if not user: raise BBJUserError("User %s is not registered" % username) elif auth.lower() != user["auth_hash"].lower(): raise BBJException( 5, "Invalid authorization key for user.") # api_methods may choose to bind a usermap into the thread_data # which will send it off with the response cherrypy.thread_data.usermap = {} value = function(self, body, connection, user)
response = schema.response(value, cherrypy.thread_data.usermap)
except BBJException as e: response = e.schema except json.JSONDecodeError as e: response = schema.error(0, str(e)) except Exception as e: error_id = uuid1().hex response = schema.error( 1, "Internal server error: code {} {}".format( error_id, repr(e))) with open("logs/exceptions/" + error_id, "a") as log: traceback.print_tb(e.__traceback__, file=log) log.write(repr(e)) print("logged code 1 exception " + error_id) finally: connection.close() return json.dumps(response) return wrapper def create_usermap(connection, obj, index=False): """ Creates a mapping of all the user_ids that occur in OBJ to their full user objects (names, profile info, etc). Can be a thread_index or a messages object from one. """ user_set = {item["author"] for item in obj} if index: [user_set.add(item["last_author"]) for item in obj] return { user_id: db.user_resolve( connection, user_id, externalize=True, return_false=False) for user_id in user_set } def do_formatting(format_spec, messages): if not format_spec: return None elif format_spec == "sequential": method = formatting.sequential_expressions else: raise BBJParameterError("invalid formatter specification") formatting.apply_formatting(messages, method) return True def validate(json, args): """ Ensure the json object contains all the keys needed to satisfy its endpoint (and isnt empty) """ if not json: raise BBJParameterError( "JSON input is empty. This method requires the following " "arguments: {}".format(", ".join(args))) for arg in args: if arg not in json.keys(): raise BBJParameterError( "Required parameter {} is absent from the request. " "This method requires the following arguments: {}" .format(arg, ", ".join(args))) def no_anon_hook(user, message=None, user_error=True): if user is db.anon: exception = BBJUserError if user_error else BBJParameterError if message: raise exception(message) elif not app_config["allow_anon"]: raise exception( "Anonymous participation has been disabled on this instance.") class API(object): """ This object contains all the API endpoints for bbj. The html serving part of the server is not written yet, so this is currently the only module being served. The docstrings below are specifically formatted for the mkdocs static site generator. The ugly `doctype` and `arglist` attributes assigned after each method definition are for use in the `mkendpoints.py` script. """ @api_method def instance_info(self, args, database, user, **kwargs): """ Return configuration info for this running instance of the BBJ server. """ return { "allow_anon": app_config["allow_anon"], "instance_name": app_config["instance_name"], "admins": app_config["admins"] } @api_method def user_register(self, args, database, user, **kwargs): """ Register a new user into the system and return the new user object on success. The returned object includes the same `user_name` and `auth_hash` that you supply, in addition to all the default user parameters. Returns code 4 errors for any failures. """ validate(args, ["user_name", "auth_hash"]) return db.user_register( database, args["user_name"], args["auth_hash"]) user_register.doctype = "Users" user_register.arglist = ( ("user_name", "string: the desired display name"), ("auth_hash", "string: a sha256 hash of a password") ) @api_method def user_update(self, args, database, user, **kwargs): """ Receives new parameters and assigns them to the user object. This method requires that you send a valid User/Auth header pair with your request, and the changes are made to that account. Take care to keep your client's User/Auth header pair up to date after using this method.
code-sauce/tensorflow
tensorflow/python/training/server_lib_test.py
Python
apache-2.0
16,137
0.003718
# Copyright 2017 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. # ============================================================================== """Tests for tf.GrpcServer.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import time import numpy as np from tensorflow.core.protobuf import config_pb2 from tensorflow.core.protobuf import tensorflow_server_pb2 from tensorflow.python.client import session from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import errors_impl from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import data_flow_ops from tensorflow.
python.ops import math_ops from tensorflow.python.ops import variables from tensorflow.python.platform import test from tensorflow.python.training import server_lib clas
s GrpcServerTest(test.TestCase): def __init__(self, methodName="runTest"): # pylint: disable=invalid-name super(GrpcServerTest, self).__init__(methodName) self._cached_server = server_lib.Server.create_local_server() def testRunStep(self): server = self._cached_server with session.Session(server.target) as sess: c = constant_op.constant([[2, 1]]) d = constant_op.constant([[1], [2]]) e = math_ops.matmul(c, d) self.assertAllEqual([[4]], sess.run(e)) # TODO(mrry): Add `server.stop()` and `server.join()` when these work. def testMultipleSessions(self): server = self._cached_server c = constant_op.constant([[2, 1]]) d = constant_op.constant([[1], [2]]) e = math_ops.matmul(c, d) sess_1 = session.Session(server.target) sess_2 = session.Session(server.target) self.assertAllEqual([[4]], sess_1.run(e)) self.assertAllEqual([[4]], sess_2.run(e)) sess_1.close() sess_2.close() # TODO(mrry): Add `server.stop()` and `server.join()` when these work. # Verifies various reset failures. def testResetFails(self): # Creates variable with container name. with ops.container("test0"): v0 = variables.Variable(1.0, name="v0") # Creates variable with default container. v1 = variables.Variable(2.0, name="v1") # Verifies resetting the non-existent target returns error. with self.assertRaises(errors_impl.NotFoundError): session.Session.reset("nonexistent", ["test0"]) # Verifies resetting with config. # Verifies that resetting target with no server times out. with self.assertRaises(errors_impl.DeadlineExceededError): session.Session.reset( "grpc://localhost:0", ["test0"], config=config_pb2.ConfigProto(operation_timeout_in_ms=5)) # Verifies no containers are reset with non-existent container. server = self._cached_server sess = session.Session(server.target) sess.run(variables.global_variables_initializer()) self.assertAllEqual(1.0, sess.run(v0)) self.assertAllEqual(2.0, sess.run(v1)) # No container is reset, but the server is reset. session.Session.reset(server.target, ["test1"]) # Verifies that both variables are still valid. sess = session.Session(server.target) self.assertAllEqual(1.0, sess.run(v0)) self.assertAllEqual(2.0, sess.run(v1)) def _useRPCConfig(self): """Return a `tf.ConfigProto` that ensures we use the RPC stack for tests. This configuration ensures that we continue to exercise the gRPC stack when testing, rather than using the in-process optimization, which avoids using gRPC as the transport between a client and master in the same process. Returns: A `tf.ConfigProto`. """ return config_pb2.ConfigProto(rpc_options=config_pb2.RPCOptions( use_rpc_for_inprocess_master=True)) def testLargeConstant(self): server = self._cached_server with session.Session(server.target, config=self._useRPCConfig()) as sess: const_val = np.empty([10000, 3000], dtype=np.float32) const_val.fill(0.5) c = constant_op.constant(const_val) shape_t = array_ops.shape(c) self.assertAllEqual([10000, 3000], sess.run(shape_t)) def testLargeFetch(self): server = self._cached_server with session.Session(server.target, config=self._useRPCConfig()) as sess: c = array_ops.fill([10000, 3000], 0.5) expected_val = np.empty([10000, 3000], dtype=np.float32) expected_val.fill(0.5) self.assertAllEqual(expected_val, sess.run(c)) def testLargeFeed(self): server = self._cached_server with session.Session(server.target, config=self._useRPCConfig()) as sess: feed_val = np.empty([10000, 3000], dtype=np.float32) feed_val.fill(0.5) p = array_ops.placeholder(dtypes.float32, shape=[10000, 3000]) min_t = math_ops.reduce_min(p) max_t = math_ops.reduce_max(p) min_val, max_val = sess.run([min_t, max_t], feed_dict={p: feed_val}) self.assertEqual(0.5, min_val) self.assertEqual(0.5, max_val) def testCloseCancelsBlockingOperation(self): server = self._cached_server sess = session.Session(server.target, config=self._useRPCConfig()) q = data_flow_ops.FIFOQueue(10, [dtypes.float32]) enqueue_op = q.enqueue(37.0) dequeue_t = q.dequeue() sess.run(enqueue_op) sess.run(dequeue_t) def blocking_dequeue(): with self.assertRaises(errors_impl.CancelledError): sess.run(dequeue_t) blocking_thread = self.checkedThread(blocking_dequeue) blocking_thread.start() time.sleep(0.5) sess.close() blocking_thread.join() def testInteractiveSession(self): server = self._cached_server # Session creation will warn (in C++) that the place_pruned_graph option # is not supported, but it should successfully ignore it. sess = session.InteractiveSession(server.target) c = constant_op.constant(42.0) self.assertEqual(42.0, c.eval()) sess.close() def testSetConfiguration(self): config = config_pb2.ConfigProto( gpu_options=config_pb2.GPUOptions(per_process_gpu_memory_fraction=0.1)) # Configure a server using the default local server options. server = server_lib.Server.create_local_server(config=config, start=False) self.assertEqual(0.1, server.server_def.default_session_config.gpu_options. per_process_gpu_memory_fraction) # Configure a server using an explicit ServerDefd with an # overridden config. cluster_def = server_lib.ClusterSpec({ "localhost": ["localhost:0"] }).as_cluster_def() server_def = tensorflow_server_pb2.ServerDef( cluster=cluster_def, job_name="localhost", task_index=0, protocol="grpc") server = server_lib.Server(server_def, config=config, start=False) self.assertEqual(0.1, server.server_def.default_session_config.gpu_options. per_process_gpu_memory_fraction) def testInvalidHostname(self): with self.assertRaisesRegexp(errors_impl.InvalidArgumentError, "port"): _ = server_lib.Server( { "local": ["localhost"] }, job_name="local", task_index=0) def testTimeoutRaisesException(self): server = self._cached_server q = data_flow_ops.FIFOQueue(1, [dtypes.float32]) blocking_t = q.dequeue() with session.Session(server.target) as sess: with self.assertRaises(errors_impl.DeadlineExceededError): sess.run(blocking_t, options=config_pb2.RunOptions(timeout_in_ms=1000)) with session.Session(server.target, config=self._useRPCConfig()) as sess: with
zxgaoray/calculate_play
calculator/Taowa.py
Python
mit
1,409
0.006388
user_input = raw_input() class Taowa: def __init__(self): return def setSize(self, m1, m2): self.width = m1 self.height = m2 self.area = m1 * m2 class Sorter: def __init__(self): self.taowas = [] self.lastWidth = 0 self.lastHeight = 0 return def setArray(self, str): self.arr = str.split(' ') for idx in range(len(self.arr)): self.arr[idx] = int(self.arr[idx]) def makeTaowa(self): l = len(self.arr) / 2 for idx in range(l): m1 = self.arr[idx*2] m2 = self.arr[idx*2+1] taowa = Taowa() taowa.setSize(m1, m2) self.taowas.append(taowa) def sortTaowa(self): self.taowas.sort(ke
y=lambda taowa:taowa.width) def calculate(self): l = len(self.taowas) self.lastHeight = self.taowas[0].height self.lastWidth = self.taowas[0].width m = 1 for idx in range(1, l, 1): taowa = self.taowas[idx] w = taowa.width h = taowa.height if w > self.lastWidth and h > self.lastHeight : m = m+1 self.lastWidth = w self.lastHeight = h
return m sorter = Sorter() sorter.setArray(user_input) sorter.makeTaowa() sorter.sortTaowa() user_input = sorter.calculate() print user_input
rsalmaso/wagtail
wagtail/core/migrations/0024_alter_page_content_type_on_delete_behaviour.py
Python
bsd-3-clause
684
0.001462
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2015-12-22 09:34 from django.db import migrations, models import wagtail.core.models class Migration(migrations.Migration): dependencies = [ ("wagtailcore", "0023_alter_page_revision_on_delete_behaviour"), ] operations = [ migrations.AlterField(
model_name="page", name="content_type", field=models.ForeignKey( on_delete=models.SET(wagtail.core.models.get_default_page_content_type), related_name="pages", to="contentty
pes.ContentType", verbose_name="content type", ), ), ]
kfieldho/SMQTK
TPL/libsvm-3.1-custom/tools/easy.py
Python
bsd-3-clause
2,835
0.029277
#!/usr/bin/env python import sys import os from subprocess import * if len(sys.argv) <= 1: print('Usage: {0} training_file [testing_file]'.format(sys.argv[0])) raise SystemExit # svm, grid, and gnuplot executable files is_win32 = (sys.platform == 'win32') if not is_win32: svmscale_exe = "/Users/sun/bin/svm-scale" svmtrain_exe = "/Users/sun/bin/svm-train" svmpredict_exe = "/Users/sun/bin/svm-predict" grid_py = "./grid.py" gnuplot_exe = "/opt/local/bin/gnuplot" else: # example for windows svmscale_exe = r"..\windows\svm-scale.exe" svmtrain_exe = r"..\windows\svm-train.exe" svmpredict_exe = r"..\windows\svm-predict.exe" gnuplot_exe = r"c:\tmp\gnuplot\bin\pgnuplot.exe" gri
d_py = r".\grid.py" assert os.path.exists(svmscale_exe),"svm-scale
executable not found" assert os.path.exists(svmtrain_exe),"svm-train executable not found" assert os.path.exists(svmpredict_exe),"svm-predict executable not found" assert os.path.exists(gnuplot_exe),"gnuplot executable not found" assert os.path.exists(grid_py),"grid.py not found" train_pathname = sys.argv[1] assert os.path.exists(train_pathname),"training file not found" file_name = os.path.split(train_pathname)[1] scaled_file = file_name + ".scale" model_file = file_name + ".model" range_file = file_name + ".range" if len(sys.argv) > 2: test_pathname = sys.argv[2] file_name = os.path.split(test_pathname)[1] assert os.path.exists(test_pathname),"testing file not found" scaled_test_file = file_name + ".scale" predict_test_file = file_name + ".predict" cmd = '{0} -s "{1}" "{2}" > "{3}"'.format(svmscale_exe, range_file, train_pathname, scaled_file) print('Scaling training data...') print( cmd ) Popen(cmd, shell = True, stdout = PIPE).communicate() cmd = '{0} -svmtrain "{1}" -gnuplot "{2}" "{3}"'.format(grid_py, svmtrain_exe, gnuplot_exe, scaled_file) print('Cross validation...') print( cmd ) f = Popen(cmd, shell = True, stdout = PIPE).stdout line = '' while True: last_line = line line = f.readline() if not line: break c,g,rate = map(float,last_line.split()) print('Best c={0}, g={1} CV rate={2}'.format(c,g,rate)) cmd = '{0} -c {1} -g {2} "{3}" "{4}"'.format(svmtrain_exe,c,g,scaled_file,model_file) print('Training...') print( cmd ) Popen(cmd, shell = True, stdout = PIPE).communicate() print('Output model: {0}'.format(model_file)) if len(sys.argv) > 2: cmd = '{0} -r "{1}" "{2}" > "{3}"'.format(svmscale_exe, range_file, test_pathname, scaled_test_file) print('Scaling testing data...') print( cmd ) Popen(cmd, shell = True, stdout = PIPE).communicate() cmd = '{0} "{1}" "{2}" "{3}"'.format(svmpredict_exe, scaled_test_file, model_file, predict_test_file) print('Testing...') print( cmd ) Popen(cmd, shell = True).communicate() print('Output prediction: {0}'.format(predict_test_file))
victor-gonzalez/AliPhysics
PWGJE/EMCALJetTasks/Tracks/analysis/Draw/DrawRawSpectrumFit.py
Python
bsd-3-clause
2,015
0.011414
#************************************************************************** #* Copyright(c) 1998-2014, ALICE Experiment at CERN, All rights reserved. * #* * #* Author: The ALICE Off-line Project. * #* Contributors are mentioned in the code where appropriate. * #* * #* Permission to use, copy, modify and distribute this software and its * #* documentation strictly for non-commercial purposes is hereby granted * #* without fee, provided that the above copyright notice appears in all * #* copies and that both the copyright notice and this permission notice * #* appear in the supporting documentation. The authors make no claims * #* about the suitability of this software for any purpose. It is * #* provided "as is" without express or implied warranty. * #********************************
****************************************** from PWG.PWGJE.EMCALJetTasks.Tracks.analysis.base.FileHandler import ResultDataBuilder from PWG.PWGJE.EMCALJetTasks.Tracks.analysis.base.struct.DataContainers import SpectrumContainer from plots.RawDataFittingPlot import RawDataFittingPlot def MakeNormalisedRawSpectrum(data): try: data.SetVertexRange(-10., 10.) data.SetPileupRejection(True) data.SelectTrackCuts(1) except
SpectrumContainer.RangeException as e: print str(e) return data.MakeProjection(0, "ptSpectrum%s", "p_{#rm{t}} (GeV/c)", "1/N_{event} 1/(#Delta p_{#rm t}) dN/dp_{#rm{t}} ((GeV/c)^{-2}") def DrawRawSpectrumIntegral(filename, trigger = "MinBias"): reader = ResultDataBuilder("lego", filename) content = reader.ReadFile() isMinBias = (trigger == "MinBias") plot = RawDataFittingPlot(MakeNormalisedRawSpectrum(content.GetData(trigger).FindTrackContainer("tracksAll")), isMinBias) plot.Create() return plot
google/vulkan_test_applications
gapid_tests/command_buffer_tests/vkCmdBindVertexBuffers_test/vkCmdBindVertexBuffers_test.py
Python
apache-2.0
3,026
0.001322
# Copyright 2017 Google Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from gapit_test_framework import gapit_test, require, require_equal from gapit_test_framework import require_not_equal, little_endian_bytes_to_int from gapit_test_framework import GapitTest, get_read_offset_function import gapit_test_framework from struct_offsets import VulkanStruct, UINT32_T, SIZE_T, POINTER from struct_offsets import HANDLE, FLOAT, CHAR, ARRAY, DEVICE_SIZE from vulkan_constants import * @gapit_test("vkCmdBindVertexBuffers_test") class SingleBuffer(GapitTest): def expect(self): architecture = self.architecture cmd_bind_vertex_buffers = require( self.next_call_of("vkCmdBindVertexBuffers")) require_not_equal(0, cmd_bind_vertex_buffers.int_commandBuffer) require_equal(0, cmd_bind_vertex_buffers.int_firstBinding) require_equal(1, cmd_bind_vertex_buffers.int_bindingCount) require_not_equal(0, cmd_bind_vertex_buffers.hex_pBuffers) require_not_equal(0, cmd_bind_vertex_buffers.hex_pOffsets) sent_buffer = little_endian_bytes_to_int( require( cmd_bind_vertex_buffers.get_read_data( cmd_bind_vertex_buffers.hex_pBuffers, NON_DISPATCHABLE_HANDLE_SIZE))) require_not_equal(sent_buffer, 0) sent_offset = little_endian_bytes_to_int( require( cmd_bind_vertex_buffers.get_read_data( cmd_bind_vertex_buffers.hex_pOffsets, 8))) require_equal(0, sent_offset) BUFFER_COPY = [ ("srcOffset", DEVICE_SIZE), ("dstOffset", DEVICE_SIZE), ("size", DEVICE_SIZE) ] @gapit_test("vkCmdBindVertexBuffers_test") class CopyBuffer(GapitTest): def expect(self): architecture = self.architecture cmd_copy_buffer = require( self.next_call_of("vkCmdCopyBuffer")) require_not_equal(0, cmd_copy_buffer.int_commandBuffer) require_not_equal(0, cmd_copy_buffer.int_srcBuffer) require_not_equal(0, cmd_copy_buffer.int_dstBuffer) require_equal(1, cmd_copy_buffer.int_regionCount) require_not_equal(0, cmd_copy_buffer.hex_pRegions) copy = VulkanStruct( architecture, BUFF
ER_COPY, get_read_offset_function(cmd_copy_buffer, cmd_copy_buffer.hex_pRegions)) require_equal(0, c
opy.srcOffset) require_equal(0, copy.dstOffset) require_equal(1024, copy.size)
ahawker/decorstate
setup.py
Python
apache-2.0
1,177
0
""" decorstate ~~~~~~~~~~ Simple "state machines" with
Python decorators. :copyright: (c) 2015-2017 Andrew Hawker :license: Apache 2.0, see LICENSE for more details. """ try: from setuptools import setup except ImportError: from distutils.core import setup setup( name='decorstate', version='0.0.3', description='Simple "state machines" wi
th Python decorators', long_description=open('README.md').read(), author='Andrew Hawker', author_email='andrew.r.hawker@gmail.com', url='https://github.com/ahawker/decorstate', license='Apache 2.0', py_modules=['decorstate'], classifiers=( 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ) )
tbrittoborges/protein_motif_encoder
tests/test_protein_motif_encoder.py
Python
mit
597
0.001675
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_protein_motif_encoder --
-------------------------------- Tests for `protein_motif_encoder` module. """ import pandas as pd import pytest from click.testing import CliRunner import cli def test_command_line_interface(): runner = CliRunner()
result = runner.invoke(cli.main) assert result.exit_code == 0 assert 'protein_motif_encoder.cli.main' in result.output help_result = runner.invoke(cli.main, ['--help']) assert help_result.exit_code == 0 assert '--help Show this message and exit.' in help_result.output
StarbotDiscord/Starbot
api/settings.py
Python
apache-2.0
3,398
0.002649
# Copyright 2017 Starbot Discord 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. '''Functions for commonly used database items''' from api import database from api.database.table import Table, TableTypes # Manage stored prefixes in database. def prefix_set(id_server, prefix): '''Set a server\'s prefix.''' database.init() table_prefix = Table('prefixes', TableTypes.pGlobal) try: entry_prefix = Table.search(table_prefix, 'serverid', '{}'.format(id_server)) except: # TODO: Narrow this and other Exception clauses.
# Table must be empty. entry_prefix = None if entry_prefix: entry_prefix.edit(dict(serverid=id_server, prefix=prefix)) else: # Create new entry Table.insert(table_prefix, dict(serverid=id_server, prefix=prefix)) def prefix_get(id_server): '''Get a server\'s prefix.''' database.init() table_prefix = Table('prefixes', TableTypes.pGl
obal) try: entry_prefix = Table.search(table_prefix, 'serverid', '{}'.format(id_server)) except: # TODO: Narrow this and other Exception clauses. # Table must be empty. entry_prefix = None if entry_prefix: return entry_prefix.data[1] else: return '!' # Manage bot ownership. def owners_check(id_user): '''Check if a user is an owner''' database.init() table_owners = Table('owners', TableTypes.pGlobal) try: entry_owner = Table.search(table_owners, 'userid', '{}'.format(id_user)) except: # TODO: Narrow this and other Exception clauses. # Table must be empty. entry_owner = None if entry_owner: return True else: return False # TODO: Make tables iterable. # def owners_get(): # database.init() # table_owners = table('owners', tableTypes.pGlobal) # owners = [] # for entry in table_owners: # owners.append(entry.data[0]) # return owners def owners_get(): '''Return an array of owner IDs from the database''' import sqlite3 conn = sqlite3.connect("bot.db3") cursor = conn.cursor() cursor.execute('CREATE TABLE IF NOT EXISTS owners (userid INTEGER)') try: cur = cursor.execute('SELECT userid FROM owners') except: return [] owners = [] for row in list(cur): owners.append(row[0]) conn.commit() conn.close() return owners def owners_add(id_user): '''Add an owner to the database''' database.init() table_owners = Table('owners', TableTypes.pGlobal) try: entry_owner = Table.search(table_owners, 'userid', '{}'.format(id_user)) except: # TODO: Narrow this and other Exception clauses. # Table must be empty. entry_owner = None if not entry_owner: Table.insert(table_owners, dict(userid=id_user))
javiersanp/CatAtom2Osm
test/test_layer.py
Python
bsd-2-clause
55,167
0.005384
# -*- coding: utf-8 -*- import unittest import mock import os import random from collections import Counter import logging logging.disable(logging.WARNING) import gdal from qgis.core import * from PyQt4.QtCore import QVariant os.environ['LANGUAGE'] = 'C' import setup import osm from layer import * from catatom2osm import QgsSingleton qgs = QgsSingleton() class TestPoint(unittest.TestCase): def test_init(self): p = Point(1, 2) q = Point(p) r = Point((1,2)) self.assertEquals(q.x(), r.x()) self.assertEquals(q.y(), r.y()) def test_boundigBox(self): radius = random.uniform(0, 100) point = Point(random.uniform(0, 100), random.uniform(0, 100)) r = point.boundingBox(radius) self.assertEquals(round(r.center().x()*100), round(point.x()*100)) self.assertEquals(round(r.center().y()*100), round(point.y()*100)) self.assertEquals(round(r.width()*100), round(radius*200)) self.assertEquals(round(r.height()*100), round(radius*200)) def test_get_corner_context(self): square = QgsGeometry.fromPolygon([[ QgsPoint(0, 0), QgsPoint(50, 0.6), # dist > 0.5, angle < 5 QgsPoint(100, 0), QgsPoint(105, 50), # dist > 0.5, angle > 5 QgsPoint(100, 100), QgsPoint(2, 100.3), #dist < 0.5, angle > 5 QgsPoint(0, 100), QgsPoint(0.3, 50), #dist < 0.5, angle < 5 QgsPoint(0, 1), QgsPoint(-50, 0), # acute QgsPoint(0, 0) ]]) acute_thr = 10 straight_thr = 5 cath_thr = 0.5 (a, is_acute, is_corner, c) = Point(50, 0.4).get_corner_context(square, acute_thr, straight_thr, cath_thr) self.assertFalse(is_acute) self.assertFalse(is_corner, "%f %s %s %f" % (a, is_acute, is_corner, c)) (a, is_acute, is_corner, c) = Point(105, 51).get_corner_context(square, acute_thr, straight_thr, cath_thr) self.assertTrue(is_corner, "%f %s %s %f" % (a, is_acute, is_corner, c)) (a, is_acute, is_corner, c) = Point(5.1, 100).get_corner_context(square, acute_thr, straight_thr, cath_thr) self.assertFalse(is_corner, "%f %s %s %f" % (a, is_acute, is_corner, c)) (a, is_acute, is_corner, c) = Point(0.4, 50).get_corner_context(square, acute_thr, straight_thr, cath_thr) self.assertFalse(is_corner, "%f %s %s %f" % (a, is_acute, is_corner, c)) (a, is_acute, is_corner, c) = Point(-51, 0).get_corner_context(square, acute_thr, straight_thr, cath_thr) self.assertTrue(is_acute) def test_get_spike_context(self): square = QgsGeometry.fromPolygon([[ QgsPoint(0, 50), # spike angle_v < 5 angle_a > 5 c < 0.5 QgsPoint(50, 50.4), QgsPoint(49.9, 76), QgsPoint(50, 74), # zig-zag QgsPoint(50, 130), QgsPoint(50.4, 100), QgsPoint(75, 110), # spike QgsPoint(99, 100), QgsPoint(100, 130), # spike but c > 0.5 QgsPoint(100.2, 60), QgsPoint(100, 90), # zig-zag but c > 0.1 QgsPoint(99.8, 0), # spike QgsPoint(99.5, 50), QgsPoint(70, 55), QgsPoint(60, 50), # not zig-zag QgsPoint(0, 50) ]]) acute_thr = 5 straight_thr = 5 threshold = 0.5 angle_v, angle_a, ndx, ndxa, is_acute, is_zigzag, is_spike, vx = \ Point(50, 50.4).get_spike_context(square, acute_thr, straight_thr, threshold) self.assertFalse(is_spike) angle_v, angle_a, ndx, ndxa, is_acute, is_zigzag, is_spike, vx = \ Point(0, 50.1).get_spike_context(square, acute_thr, straight_thr, threshold) self.assertTrue(is_spike) self.assertEquals(ndxa, 1) self.assertEquals(round(vx.x(), 4), 50.0016) self.assertEquals(vx.y(), 50.0) angle_v, angle_a, ndx, ndxa, is_acute, is_zigzag, is_spike, vx = \ Point(50, 74).get_spike_context(square, acute_thr, straight_thr, threshold) self.assertTrue(is_zigzag) self.assertEquals(ndx, 3) self.assertEquals(ndxa, 2) angle_v, angle_a, ndx, ndxa, is_acute, is_zigzag, is_spike, vx = \ Point(50, 130).get_spike_context(square, acute_thr, straight_thr, threshold) self.assertTrue(is_spike) self.assertEquals(ndx, 4) self.assertEquals(ndxa, 5) self.assertEquals(vx.x(), 50) self.assertEquals(round(vx.y(),4), 99.8374) angle_v, angle_a, ndx, ndxa, is_acute, is_zigzag, is_spike, vx = \ Point(100, 130).get_spike_context(square, acute_thr, straight_thr, threshold) self.assertTrue(is_acute) self.assertFalse(is_spike) angle_v, angle_a, ndx, ndxa, is_acute, is_zigzag, is_spike, vx = \ Point(100, 90).get_spike_context(square, acute_thr, straight_thr, 0.1) self.assertFalse(is_spike) self.assertFalse(is_zigzag) angle_v, angle_a, ndx, ndxa, is_acute, is_zigzag, is_spike, vx = \ Point(100, 0).get_spike_context(square, acute_thr, straight_thr, threshold) self.assertTrue(is_spike) self.assertEquals(ndx, 11)
self.assertEquals(ndxa, 12) self.assertEquals(round(vx.x(),
4), 99.9109) self.assertEquals(round(vx.y(),4), 49.9234) angle_v, angle_a, ndx, ndxa, is_acute, is_zigzag, is_spike, vx = \ Point(60, 50).get_spike_context(square, acute_thr, straight_thr, threshold) self.assertFalse(is_zigzag) class TestBaseLayer(unittest.TestCase): def setUp(self): self.fixture = QgsVectorLayer('test/building.gml', 'building', 'ogr') self.assertTrue(self.fixture.isValid()) fn = 'test_layer.shp' BaseLayer.create_shp(fn, self.fixture.crs()) self.layer = PolygonLayer(fn, 'building', 'ogr') self.assertTrue(self.layer.isValid()) fields1 = [] fields1.append(QgsField("A", QVariant.String)) fields1.append(QgsField("B", QVariant.Int)) self.layer.writer.addAttributes(fields1) self.layer.updateFields() def tearDown(self): del self.layer BaseLayer.delete_shp('test_layer.shp') def test_copy_feature_with_resolve(self): feature = self.fixture.getFeatures().next() resolve = { 'A': ('gml_id', '[0-9]+[A-Z]+[0-9]+[A-Z]') } new_fet = self.layer.copy_feature(feature, resolve=resolve) self.assertEquals(feature['localId'], new_fet['A']) resolve = { 'A': ('gml_id', 'Foo[0-9]+') } new_fet = self.layer.copy_feature(feature, resolve=resolve) self.assertEquals(new_fet['A'], None) def test_copy_feature_with_rename(self): feature = self.fixture.getFeatures().next() rename = {"A": "gml_id", "B": "value"} new_fet = self.layer.copy_feature(feature, rename) self.assertEquals(feature['gml_id'], new_fet['A']) self.assertEquals(feature['value'], new_fet['B']) self.assertTrue(feature.geometry().equals(new_fet.geometry())) def test_copy_feature_all_fields(self): layer = BaseLayer("Polygon", "test", "memory") self.assertTrue(layer.startEditing()) self.assertTrue(layer.isValid()) feature = self.fixture.getFeatures().next() new_fet = layer.copy_feature(feature) self.assertTrue(layer.commitChanges()) self.assertEquals(feature['gml_id'], new_fet['gml_id']) self.assertEquals(feature['localId'], new_fet['localId']) self.assertTrue(feature.geometry().equals(new_fet.geometry())) def test_append_with_rename(self): rename = {"A": "gml_id", "B": "value"} self.layer.append(self.fixture, rename) self.assertEquals(self.layer.featureCount(), self.fixture.featureCount()) feature = self.fixture.getFeatures().next() new_fet = self.layer.getFeatures().next() self.assertEquals(feature['gml_id'], new_fet['A']) def test_append_all_fields(self): layer = BaseLayer("Polygon", "test", "memory") self
nanshihui/ipProxyDec
ProxyServe/manage.py
Python
gpl-3.0
253
0
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_
SETTINGS_MODULE", "ProxyServe.settings")
from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
purduesigbots/pros-cli
pros/conductor/interactive/NewProjectModal.py
Python
mpl-2.0
2,998
0.002668
import os.path from typing import * from click import Context, get_current_context from pros.common import ui from pros.common.ui.interactive import application, components, parameters from pros.conductor import Conductor from .parameters import NonExistentProjectParameter class NewProjectModal(application.Modal[None]): targets = parameters.OptionParameter('v5', ['v5', 'cortex']) kernel_versions = parameters.OptionParameter('latest', ['latest']) install_default_libraries = parameters.BooleanParameter(True) project_name = parameters.Parameter(None) advanced_collapsed = parameters.BooleanParameter(True) def __init__(self, ctx: Context = None, conductor: Optional[Conductor] = None, directory=os.path.join(os.path.expanduser('~'), 'My PROS Project')): super().__init__('Create a new project') self.conductor = conductor or Conductor() self.click_ctx = ctx or get_current_context() self.directory = NonExistentProjectParameter(directory) cb = self.targets.on_changed(self.target_changed, asynchronous=True) cb(self.targets) def target_changed(self, new_target): templates = self.conductor.resolve_templates('kernel', target=new_target.value) if len(templates) == 0: self.kernel_versions.options = ['latest'] else: self.kernel_versions.options = ['latest'] + sorted({t.version for t in templates}, reverse=True) self.redraw() def confirm(self, *args, **kwargs): assert self.can_confirm self.exit() project = self.conductor.new_project( path=self.directory.value, target=self.targets.value, version=self.kernel_versions.value, no_default_libs=not self.install_default_libraries.value, project_name=self.project_name.value ) from pros.conductor.project import ProjectReport report = ProjectReport(project) ui.finalize('project-report', report) with ui.Notification(): ui.echo('Building project...') project.compile([]) @property def can_confirm(self): return self.directory.is_valid() and self.targets.is_valid() and self.kernel_versions.is_valid() def build(self) -> Generator[components.Component, None, None]: yield components.DirectorySelector('Project Directory', self.directory) yield components.ButtonGroup('Target', self.tar
gets) project_name_placeholder = os.path.basename(os.path.normpath(os.path.abspath(self.directory.value))) yield components.Container( components.InputBox('Project Name', self.project_name, placeholder=project_name_placeholder), components.DropDownBox('Kernel Version', self.kernel_versions),
components.Checkbox('Install default libraries', self.install_default_libraries), title='Advanced', collapsed=self.advanced_collapsed )
mozilla/socorro
webapp-django/crashstats/api/tests/test_jinja_helpers.py
Python
mpl-2.0
503
0
# This Source Code Form is subj
ect to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from crashstats.api.templatetags.jinja_helpers import pluralize class TestPluralize(object): def test_basics(self): assert pluralize(0) == "s" assert pluralize(1) == "" assert pluralize(59) == "s" def test_overide_s(self): assert pluralize(59,
"ies") == "ies"
FAB4D/humanitas
data_collection/social_media/twitter/merge.py
Python
bsd-3-clause
933
0.013934
#--------------------------------- #Joseph Boyd - joseph.boyd@epfl.ch #--------------------------------- import os ; import sys ; import pickle def main(): num_partitions = 8 unique_users = {} print "Merging..." for filename in os.listdir("."): if filename[filename.rfind('.')+1:] == 'pickle': f = open(filename, 'rb') users = pickle.load(f) f.close() print len(users) for user in users: unique_users[user['screen_name']] = user print "Unique users: %s"%(len(unique_users)) print "Partitionin
g..." partition_size = len(unique_users) / num_partitions for i in range(num_partitions): f_unique_users = open('outputs/%s.pickle'%(i), 'wb') pickle.dump(unique_users.values()[i*partition_s
ize:(i+1)*partition_size], f_unique_users) f_unique_users.close() if __name__ == '__main__': main()
Sezzh/tifis_platform
tifis_platform/tifis_platform/urls.py
Python
gpl-2.0
975
0.002051
"""tifis_platform URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$
', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls
)) """ from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^i18n/', include('django.conf.urls.i18n')), #perfom translations url(r'^', include('usermodule.urls', namespace='usermodule')), url(r'^', include('groupmodule.urls', namespace='groupmodule')), url(r'^admin/', include(admin.site.urls)), ]
spinicist/QUIT
Python/Tests/test_utils.py
Python
mpl-2.0
2,502
0.001199
from pathlib import Path from os import chdir import unittest from math import sqrt from nipype.interfaces.base import CommandLine from qipype.commands import NewImage, Diff from qipype.utils import PolyImage, PolyFit, Filter, RFProfile vb = True CommandLine.terminal_output = 'allatonce' class Utils(unittest.TestCase): def setUp(self): Path('testdata').mkdir(exist_ok=True) chdir('testdata') def tearDown(self): chdir('../') def test_poly(self): sz = 16 scale = sqrt(3 * (sz/2)**2) poly = {'center': [0, 0, 0], 'scale': scale, 'coeffs': [1, 1, 2, 4, 1, 0, 0, 1,
0, 1] } poly_sim = 'poly_sim.nii.gz' mask_file = 'poly_mask.nii.gz' NewImage(img_size=[sz, sz, sz], grad_dim=0, grad_vals=(0, 1), grad_steps=1, out_file=mask_file, verbose=vb).run() PolyImage(ref_file=mask_file, out_file=poly_sim, order=2, poly=poly, verbose=vb).run() fit = PolyFit(in_file=poly_sim, order=2, robust=True).run() terms_diff = sum([abs(x - y) for x,
y in zip(poly['coeffs'], fit.outputs.poly['coeffs'])]) self.assertLessEqual(terms_diff, 1.e-6) PolyImage(ref_file=mask_file, out_file='poly_sim2.nii.gz', order=2, poly=fit.outputs.poly, verbose=vb).run() img_diff = Diff(baseline=poly_sim, in_file='poly_sim2.nii.gz', noise=1).run() self.assertLessEqual(img_diff.outputs.out_diff, 1.e-3) def test_kfilter(self): NewImage(out_file='steps.nii.gz', img_size=[64, 64, 64], grad_dim=0, grad_vals=(0, 8), grad_steps=4, verbose=vb).run() Filter(in_file='steps.nii.gz', filter_spec='Gauss,2.0', verbose=vb).run() def test_rfprofile(self): NewImage(out_file='rf_b1plus.nii.gz', img_size=[32, 32, 32], fill=1.0, verbose=vb).run() RFProfile(in_file='rf_b1plus.nii.gz', out_file='rf_slab.nii.gz', rf={'rf_pos': [0, 1], 'rf_vals': [0, 1]}, verbose=vb).run() NewImage(out_file='rf_ref.nii.gz', img_size=[32, 32, 32], grad_dim=2, grad_vals=(-16, 15), verbose=vb).run() rf_diff = Diff(baseline='rf_ref.nii.gz', in_file='rf_slab.nii.gz', noise=1, abs_diff=True, verbose=vb).run() self.assertLessEqual(rf_diff.outputs.out_diff, 1.e-3) if __name__ == '__main__': unittest.main()
zeqing-guo/SPAKeyManager
MergeServer/migrations/0002_auto_20160113_0600.py
Python
gpl-3.0
480
0
# -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-01-13 06:00 from __future__ import unicode_literals import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('MergeServer', '0001_initial'), ] operations = [ migrations.AlterField( model_name='results', name='start_time', field=models.TimeField(default=datetime.datetime.now),
), ]
lwerdna/chess
Sjeng.py
Python
gpl-3.0
3,014
0.006304
#!/usr/bin/python # Copyright 2012, 2013 Andrew Lamoureux # # This file is a part of FunChess # # FunChess 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/>. #!/usr/bin/python import re import string import subprocess def runGetOutput(cmdAndArgs): print "opening on -%s-" % cmdAndArgs try: poObj = subprocess.Popen(cmdAndArgs, stdout=subprocess.PIPE); while(1): print "calling communicate..." text = poObj.communicate()[0] return text except: pass def searchMate(time, bfen): # split the bfen into array # form args cmdAndArgs = ['./sjengshim', 'bughouse', str(time), bfen] output = runGetOutput(cmdAndArgs) print "it returned: " + output # maxMateValue = 0 bestScore = -1; bestLine = '' mateLine = '' lines = string.split(output, '\n') # Sjeng
maybe return earlier lines with supposed mate, but when further nodes are searched # you'll see that the opponent can counter... so we search for the very very last line for line in lines: # format is: <i_depth> <score> <elapsed> <nodes> <principle variation> m = re.match(r'^\s+(\d+)\s+(\d+)
\s+(\d+)\s+(\d+)\s+(.*)$', line) if m: (i_depth, score, elapsed, nodes, line) = m.group(1,2,3,4,5) if int(score) > bestScore: bestScore = int(score) bestLine = line # m = re.match(r'^\s*(.*#)\s*$', bestLine) if m: mateLine = m.group(1) return mateLine def searchPossibilitiesBug(time, bfen): answer = '' # split the bfen into array # form args cmdAndArgs = ['./sjengshim', 'bughouse', str(time), bfen] output = runGetOutput(cmdAndArgs) #print "it returned: %s" % output lines = string.split(output, '\n') for line in lines: m = re.match(r'^\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(.*)$', line) if m: answer += line answer += "\n" return answer ############################################################################### # main() ############################################################################### if __name__ == '__main__': #bfen = 'B3B2r/p6p/1pbp1p1N/1qbR4/2r1p3/4Pp1k/PP3P1P/n2Q1K1R/rbpP w - - 60 60' bfen = 'r2q1rk1/p1p1Bppp/2p5/5N2/3n4/5Q2/P1P2PPP/R4RK1/NbbBnPpPp w Qq - 0 0' mate = searchMate(8, bfen) if mate: print "MATE FOUND! ", mate
mora260/ie0117_III16
grupo5/videoStreamClient.py
Python
gpl-3.0
4,583
0.04195
#Librerías y módulos requeridos para el desarrollo del app from kivy.config import Config Config.set('graphics','resizable',0) from kivy.core.window import Window Window.size = (600, 500) from kivy.app import App from kivy.lang import Builder from kivy.uix.boxlayout import BoxLayout from kivy.uix.gridlayout import GridLayout from kivy.clock import Clock import socket from threading import * from kivy.uix.image import Image from kivy.cache import Cache import pygame from kivy.uix.popup import Popup from kivy.uix.label import Label from kivy.uix.textinput import TextInput from kivy.uix.button import Button kv = ''' main: BoxLayout: orientation: 'vertical' padding: root.width * 0.05, root.height * .05 spacing: '5dp' BoxLayout: size_hint: [1,.85] Image: id: image_source source: 'camara.jpg' BoxLayout: size_hint: [1,.15] GridLayout: cols: 3 spacing: '10dp' Button: id: status text:'Reproducir' font_size: 25 bold: True on_press: root.playPause() background_normal: "verde.jpg" Button: text: 'Configuraciones' font_size: 25 bold: True on_press: root.setting() background_normal: "rojo.jpg" ''' #String que contiene la información necesaria para la implementación de la interfaz principal del cliente class main(BoxLayout):#programa principal, que define distintas funciones del cliente ipAddress = None port = None def playPause(self):#Función q
ue define la reproducción o detención del stream if self.ipAddress == None or self.port == None: #Revisión de los valores de ip y puerto para determinar si se puede inciar el stream box = GridLayout(cols=1)#Creación de la venta con mensaje de error box.add_widget(Label(text="Ip o Pue
rto no establecido")) btn = Button(text="OK") btn.bind(on_press=self.closePopup) box.add_widget(btn) self.popup1 = Popup(title='Error',content=box,size_hint=(.8,.3)) self.popup1.open() else: if self.ids.status.text == "Detener":self.stop()#llamado a la función stop else: self.ids.status.text = "Detener"#Inicio de la recuperación de datos en intervalos de 0.05 segundos y cambio de la etiqueta a detener Clock.schedule_interval(self.recv, 0.05) def closePopup(self,btn): #Función que cierra una ventana self.popup1.dismiss() def stop(self):#Función que interrumpe el proceso de reloj para detener el stream self.ids.status.text = "Reproducir" #Cambio del texto de la etiqueta Clock.unschedule(self.recv)#Establecimiento de la interrupció al proceso del reloj def recv(self, dt):# Función que recibe los archivos enviaddos por el servidor clientsocket=socket.socket(socket.AF_INET, socket.SOCK_STREAM)#definición de un socket que recibe el valor de la iP clientsocket.connect((self.ipAddress, self.port))#inicio de la conexión received = []#arreglo para los datos recibidos while True: recvd_data = clientsocket.recv(230400) if not recvd_data: break else: received.append(recvd_data) dataset = ''.join(received) image = pygame.image.fromstring(dataset,(640, 480),"RGB") # convert received image from string try: pygame.image.save(image, "camara.jpg") self.ids.image_source.reload() except: pass def close(self):#función para la detención de todo proceso de la aplicación App.get_running_app().stop() def setting(self):#función que solicita los valores de IP y puerto box = GridLayout(cols = 2) #Creación de etiquetas, espacios de inserción de datos y botón de establecimiento de parámetros box.add_widget(Label(text="DireccionIP: ", bold = True)) self.st = TextInput(id= "serverText") box.add_widget(self.st) box.add_widget(Label(text="Puerto: ", bold = True)) self.pt = TextInput(id= "portText") box.add_widget(self.pt) btn = Button(text="Establecer", bold=True) btn.bind(on_press=self.settingProcess) box.add_widget(btn) self.popup = Popup(title='Configuraciones',content=box,size_hint=(.6,.4)) self.popup.open() def settingProcess(self, btn): #Función que asigna los valores recibidos a las variables ipAdress y port try: self.ipAddress = self.st.text self.port = int(self.pt.text) except: pass self.popup.dismiss() class videoStreamApp(App):#Construcción de la aplicación def build(self): return Builder.load_string(kv) if __name__ == '__main__': #Ejecución de la aplicación construida videoStreamApp().run()
pedroeml/t1-fcg
CrowdDataAnalysis/const.py
Python
mit
686
0.004373
import configparser def load_config_file(config_file_path): config = configparser.ConfigParser() config.read(config_file_path) input_folder_path = config['DEFAULT']['InputFolderPath'] too_far_distance = int(config['DEFAULT']['TooFarDistance']) grouping_max_distance = int(config['DEFAULT']['GroupingMaxDistance']) minimum_distance_change = int(config['DEFAULT']['MinimumDistanceChange']) fps = int(config['DEFAULT']['FPS']) return input_folder_pat
h, too_far_distance, grouping_max_distance, minimum_distance_change, fps INPUT_FOLDER_PATH, TOO_FAR_DISTANCE, GROUPING_MAX_DISTANCE, MINIMUM_DISTA
NCE_CHANGE, FPS = load_config_file('.\constants.conf')
nazavode/tracboat
tests/test_model.py
Python
gpl-3.0
598
0
# -*- coding: utf-8 -*- import pytest import peewee from tracboat.gitlab import model @pytest.mark.parametrize('version', [ '8.4', '8.5', '8.7', '8.13', '8.15', '8.16', '8.17', '9.0.0' ]) def test_
get_model_supported(version): M = model.get_model(version) assert M a
ssert M.database_proxy assert isinstance(M.database_proxy, peewee.Proxy) @pytest.mark.parametrize('version', [ '8.4.0', '9.0.1', '9.0.0.0', '8.7.0', ]) def test_get_model_unsupported(version): with pytest.raises(ImportError): model.get_model(version)
BitWriters/Zenith_project
zango/lib/python3.5/site-packages/django/utils/ipv6.py
Python
mit
7,971
0.000125
# This code was mostly based on ipaddr-py # Copyright 2007 Google Inc. http://code.google.com/p/ipaddr-py/ # Licensed under the Apache License, Version 2.0 (the "License"). from django.core.exceptions import ValidationError from django.utils.six.moves import range from django.utils.translation import ugettext_lazy as _ def clean_ipv6_address(ip_str, unpack_ipv4=False, error_message=_("This is not a valid IPv6 address.")): """ Cleans an IPv6 address string. Validity is checked by calling is_valid_ipv6_address() - if an invalid address is passed, ValidationError is raised. Replaces the longest continuous zero-sequence with "::" and removes leading zeroes and makes sure all hextets are lowercase. Args: ip_str: A valid IPv6 address. unpack_ipv4: if an IPv4-mapped address is found, return the plain IPv4 address (default=False). error_message: An error message used in the ValidationError. Returns: A compressed IPv6 address, or the same value """ best_doublecolon_start = -1 best_doublecolon_len = 0 doublecolon_start = -1 doublecolon_len = 0 if not is_valid_ipv6_address(ip_str): raise ValidationError(error_message, code='invalid') # This algorithm can only handle fully exploded # IP strings ip_str = _explode_shorthand_ip_string(ip_str) ip_str = _sanitize_ipv4_mapping(ip_str) # If needed, unpack the IPv4 and return straight away # - no need in running the rest of the algorithm if unpack_ipv4: ipv4_unpacked = _unpack_ipv4(ip_str) if ipv4_unpacked: return ipv4_unpacked hextets = ip_str.split(":") for index in range(len(hextets)): # Remove leading zeroes hextets[index] = hextets[index].lstrip('0') if not hextets[index]: hextets[index] = '0' # Determine best hextet to compress if hextets[index] == '0': doublecolon_len += 1 if doublecolon_start == -1: # Start of a sequence of zeros. doublecolon_start = index if doublecolon_len > best_doublecolon_len: # This is the longest sequence of zeros so far. best_doublecolon_len = doublecolon_len best_doublecolon_start = doublecolon_start else: doublecolon_len = 0 doublecolon_start = -1 # Compress the most suitable hextet if best_doublecolon_len > 1: best_doublecolon_end = (best_doublecolon_start + best_doublecolon_len) # For zeros at the end of the address. if best_doublecolon_end == len(hextets): hextets += [''] hextets[best_doublecolon_start:best_doublecolon_end] = [''] # For zeros at the beginning of the address. if best_doublecolon_start == 0: hextets = [''] + hextets result = ":".join(hextets) return result.lower() def _sanitize_ipv4_mapping(ip_str): """ Sanitize IPv4 mapping in an expanded IPv6 address. This converts ::ffff:0a0a:0a0a to ::ffff:10.10.10.10. If there is nothing to sanitize, returns an unchanged string. Args: ip_str: A string, the expanded IPv6 address. Returns: The sanitized output string, if applicable. """ if not ip_str.lower().startswith('0000:0000:0000:0000:0000:ffff:'): # not an ipv4 mapping return ip_str hextets = ip_str.split(':') if '.' in hextets[-1]: # already sanitized return ip_str ipv4_address = "%d.%d.%d.%d" % ( int(hextets[6][0:2], 16), int(hextets[6][2:4], 16), int(hextets[7][0:2], 16), int(hextets[7][2:4], 16), ) result = ':'.join(hextets[0:6]) result += ':' + ipv4_address return result def _unpack_ipv4(ip_str): """ Unpack an IPv4 address that was mapped in a compressed IPv6 address. This converts 0000:0000:0000:0000:0000:ffff:10.10.10.10 to 10.10.10.10. If there is nothing to sanitize, returns None. Args: ip_str: A string, the expanded IPv6 address. Returns: The unpacked IPv4 address, or None if there was nothing to unpack. """ if not ip_str.lower().startswith('0000:0000:0000:0000:0000:ffff:'): return None return ip_str.rsplit(':', 1)[1] def is_valid_ipv6_address(ip_st
r): """ Ensure we have a valid IPv6 address. Args: ip_str: A string, the IPv6 address. Returns: A boolean, True if this is a valid IPv6 address. """ from django.core.validators import validate_ipv4_address # We need to have at least one ':'. if ':' not in ip_str: return False
# We can only have one '::' shortener. if ip_str.count('::') > 1: return False # '::' should be encompassed by start, digits or end. if ':::' in ip_str: return False # A single colon can neither start nor end an address. if ((ip_str.startswith(':') and not ip_str.startswith('::')) or (ip_str.endswith(':') and not ip_str.endswith('::'))): return False # We can never have more than 7 ':' (1::2:3:4:5:6:7:8 is invalid) if ip_str.count(':') > 7: return False # If we have no concatenation, we need to have 8 fields with 7 ':'. if '::' not in ip_str and ip_str.count(':') != 7: # We might have an IPv4 mapped address. if ip_str.count('.') != 3: return False ip_str = _explode_shorthand_ip_string(ip_str) # Now that we have that all squared away, let's check that each of the # hextets are between 0x0 and 0xFFFF. for hextet in ip_str.split(':'): if hextet.count('.') == 3: # If we have an IPv4 mapped address, the IPv4 portion has to # be at the end of the IPv6 portion. if not ip_str.split(':')[-1] == hextet: return False try: validate_ipv4_address(hextet) except ValidationError: return False else: try: # a value error here means that we got a bad hextet, # something like 0xzzzz if int(hextet, 16) < 0x0 or int(hextet, 16) > 0xFFFF: return False except ValueError: return False return True def _explode_shorthand_ip_string(ip_str): """ Expand a shortened IPv6 address. Args: ip_str: A string, the IPv6 address. Returns: A string, the expanded IPv6 address. """ if not _is_shorthand_ip(ip_str): # We've already got a longhand ip_str. return ip_str new_ip = [] hextet = ip_str.split('::') # If there is a ::, we need to expand it with zeroes # to get to 8 hextets - unless there is a dot in the last hextet, # meaning we're doing v4-mapping if '.' in ip_str.split(':')[-1]: fill_to = 7 else: fill_to = 8 if len(hextet) > 1: sep = len(hextet[0].split(':')) + len(hextet[1].split(':')) new_ip = hextet[0].split(':') for __ in range(fill_to - sep): new_ip.append('0000') new_ip += hextet[1].split(':') else: new_ip = ip_str.split(':') # Now need to make sure every hextet is 4 lower case characters. # If a hextet is < 4 characters, we've got missing leading 0's. ret_ip = [] for hextet in new_ip: ret_ip.append(('0' * (4 - len(hextet)) + hextet).lower()) return ':'.join(ret_ip) def _is_shorthand_ip(ip_str): """Determine if the address is shortened. Args: ip_str: A string, the IPv6 address. Returns: A boolean, True if the address is shortened. """ if ip_str.count('::') == 1: return True if any(len(x) < 4 for x in ip_str.split(':')): return True return False
e-loue/pyke
examples/web_framework/profile_server.py
Python
mit
442
0.006787
# profil
e_server.py import cProfile import simple_server def run(port=8080, logging=False, trace_sql=False, db_engine='sqlite3'): cProfile.runctx( 'simple_server.run(port=%d, logging=%s, trace_sql=%s, db_engine=%r)' % (port, logging, trace_sql, db_engine), globals(), locals(), 'profile.out')
def stats(): import pstats p = pstats.Stats('profile.out') p.sort_stats('time') p.print_stats(20)
saltstack/salt
salt/modules/btrfs.py
Python
apache-2.0
34,445
0.001045
# # Copyright 2014 SUSE LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # 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. """ Module for managing BTRFS file systems. """ import itertools import os import re import subprocess import uuid import salt.utils.fsutils import salt.utils.platform from salt.exceptions import CommandExecutionError def __virtual__(): """ Only work on POSIX-like systems """ return not salt.utils.platform.is_windows() and __grains__.get("kernel") == "Linux" def version(): """ Return BTRFS version. CLI Example: .. code-block:: bash salt '*' btrfs.version """ out = __salt__["cmd.run_all"]("btrfs --version") if out.get("stderr"): raise CommandExecutionError(out["stderr"]) return {"version": out["stdout"].split(" ", 1)[-1]} def _parse_btrfs_info(data): """ Parse BTRFS device info data. """ ret = {} for line in [line for line in data.split("\n") if line][:-1]: if line.startswith("Label:"): line = re.sub(r"Label:\s+", "", line) label, uuid_ = (tkn.strip() for tkn in line.split("uuid:")) ret["label"] = label != "none" and label or None ret["uuid"] = uuid_ continue if line.startswith("\tdevid"): dev_data = re.split(r"\s+", line.strip()) dev_id = dev_data[-1] ret[dev_id] = { "device_id": dev_data[1], "size": dev_data[3], "used": dev_data[5], } return ret def info(device): """ Get BTRFS filesystem information. CLI Example: .. code-block:: bash salt '*' btrfs.info /dev/sda1 """ out = __salt__["cmd.run_all"]("btrfs filesystem show {}".format(device)) salt.utils.fsutils._verify_run(out) return _parse_btrfs_info(out["stdout"]) def devices(): """ Get known BTRFS formatted devices on the system. CLI Example: .. code-block:: bash salt '*' btrfs.devices """ out = __salt__["cmd.run_all"]("blkid -o export") salt.utils.fsutils._verify_run(out) return salt.utils.fsutils._blkid_output(out["stdout"], fs_type="btrfs") def _defragment_mountpoint(mountpoint): """ Defragment only one BTRFS mountpoint. """ out = __salt__["cmd.run_all"]( "btrfs filesystem defragment -f {}".format(mountpoint) ) return { "mount_point": mountpoint, "passed": not out["stderr"], "log": out["stderr"] or False, "range": False, } def defragment(path): """ Defragment mounted BTRFS filesystem. In order to defragment a filesystem, device should be properly mounted and writable. If passed a device name, then defragmented whole filesystem, mounted on in. If passed a moun tpoint of the filesystem, then only this mount point is defragmented. CLI Example: .. code-block:: bash salt '*' btrfs.defragment /dev/sda1 salt '*' btrfs.defragment /path/on/filesystem """ is_device = salt.utils.fsutils._is_device(path) mounts = salt.utils.fsutils._get_mounts("btrfs") if is_device and not mounts.get(path): raise CommandExecutionError('Device "{}" is not mounted'.format(path)) result = [] if is_device: for mount_point in mounts[path]: result.append(_defragment_mountpoint(mount_point["mount_point"])) else: is_mountpoint = False for mountpoints in mounts.values(): for mpnt in mountpoints: if path == mpnt["mount_point"]: is_mountpoint = True break d_res = _defragment_mountpoint(path) if ( not is_mountpoint and not d_res["passed"] and "range ioctl not supported" in d_res["log"] ): d_res[ "log" ] = "Range ioctl defragmentation is not supported in this kernel." if not is_mountpoint: d_res["mount_point"] = False d_res["range"] = os.path.exists(path) and path or False result.append(d_res) return result def features(): """ List currently available BTRFS features. CLI Example: .. code-block:: bash salt '*' btrfs.mkfs_features """ out = __salt__["cmd.run_all"]("mkfs.btrfs -O list-all") salt.utils.fsutils._verify_run(out) ret = {} for line in [ re.sub(r"\s+", " ", line) for line in out["stderr"].split("\n") if " - " in line ]: option, description = line.split(" - ", 1) ret[option] = description return ret def _usage_overall(raw): """ Parse usage/overall. """ data = {} for line in raw.split("\n")[1:]: keyset = [ item.strip() for item in re.sub(r"\s+", " ", line).split(":", 1) if item.strip() ] if len(keyset) == 2: key = re.sub(r"[()]", "", keyset[0]).replace(" ", "_").lower() if key in ["free_estimated", "global_reserve"]: # An extra field subk = keyset[1].split("(") data[key] = subk[0].strip() subk = subk[1].replace(")", "").split(": ") data["{}_{}".format(key, subk[0])] = subk[1] else: data[key] = keyset[1] return data def _usage_specific(raw): """ Parse usage/specific. """ get_key = lambda val: dict([tuple(val.split(":"))]) raw = raw.split("\n") section, size, used = raw[0].split(" ") section = section.replace(",", "_").replace(":", "").lower() data = {} data[section] = {} for val in [size, used]: data[section].update(get_key(val.replace(",", ""))) for devices in raw[1:]: data[section].update(get_key(re.sub(r"\s+", ":", devices.strip()))) return data def _usage_unallocated(raw): """ Parse usage/unallocated. """ ret = {} for line in raw.split("\n")[1:]: keyset = re.sub(r"\s+", " ", line.strip()).split(" ") if len(keyset) == 2: ret[keyset[0]] = keyset[1] return ret def usage(path): """ Show in which disk the chunks are allocated. CLI Example: .. code-block:: bash salt '*' btrfs.usage /your/mountpoint """ out = __salt__["cmd.run_all"]("btrfs filesystem usage {}".format(path)) salt.utils.fsutils._verify_run(out) ret = {} for section in out["stdout"].split("\n\n"): if section.startswith("Overall:\n"): ret["overall"] = _usage_overall(section) elif section.startswith("Unallocated:\n"): ret["unallocated"] = _usage_unallocated(section) else: ret.update(_usage_specific(section)) return ret def mkfs(*devices, **kwargs): """ Create a file system on the specified device. By default wipes out with force. General options: * **allocsize**: Specify the BTRFS offset from the start of the device. * **bytecount**: Specify the size of the resultant filesystem. * **nodesize**: Node size. * **leafsize**: Specify the nodesize, the tree block size in which btrfs stores data. * **noforce**: Prevent force overwrite when an existing filesystem is detected on the device. * **sectorsize**: Specify the sectorsize, the minimum data block allocation unit. * **nodiscard**: Do not perform whole device TRIM op
eration by defa
ult. * **uuid**: Pass UUID or pass True to generate one. Options: * **dto**: (raid0|raid1|raid5|raid6|raid10|single|dup) Specify how the data must be spanned across the devices specified. * **mto**: (raid0|raid1|ra
onajafi/Cookie_Sharing_Bot
readDatas.py
Python
gpl-3.0
2,844
0.009845
import sqlite3 as lite import sys from datetime import datetime #con = lite.connect('zthb.sqlite') # with con: # cur = con.cursor() # # cur.execute("UPDATE user_comment SET u_comment=? WHERE u_comment=?", ("__DOLLFACE__","OMG")) # con.commit() # # print "Number of rows updated: %d" % cur.rowcount # with con: # cur = con.cursor() # cur.execute("SELECT * FROM user_comment") # # rows = cur.fetchall() # # for row in rows: # print row # def test1(): # cn = lite.connect("zthb.sqlite") # cn.execute("PRAGMA ENCODING = 'utf8';") # cn.text_factory = str # cn.execute("CREATE TABLE IF NOT EXISTS cookie_giver(u_id MEDIUMINT, u_name VARCHAR(100), u_first_name VARCHAR(100), u_last_name VARCHAR(100), u_comment TEXT, u_time DATETIME,u_likes MEDIUMINT);") # cn.execute("INSERT INTO cookie_giver VALUES (?, ?, ?, ?, ?, ?,?);", (userId, userName, userFirstName, userLastName, userMessage, datetime.now(),userLikes)) # cn.commit() # cn.close() def test2(): userId=123 userName='Tester' userFirstName='POP' userLastName='COMPUTER' userMessage='THE MSG' cn = lite.connect("zthb.sqlite") cn.execute("PRAGMA ENCODING = 'utf8';") cn.text_factory = str cn.execute("CREATE TABLE IF NOT EXISTS user_comment(u_id MEDIUMINT, u_name VARCHAR(100), u_first_name VARCHAR(100), u_last_name VARCHAR(100), u_comment TEXT, u_time DATETIME);") cn.execute("INSERT INTO user_comment VALUES (?, ?, ?, ?, ?, ?);",(userId, userName, userFirstName, userLastName, userMessage, datetime.now())) cn.commit() cn.close() def readDATA(): con = lite.connect('zthb.sqlite') cur = con.cursor() cur.execute("SELECT * FROM cookie_giver") rows = cur.fetchall() for row in rows: print row def fetchingDATA(): userId = 124 userName = 'Tester' userFirstName = 'POP' userL
astName = 'COMPUTE
R' userMessage = 'THE MSG' cn = lite.connect("zthb.sqlite") cur = cn.cursor() cur.execute("SELECT * FROM cookie_giver WHERE u_id={0}".format(userId)) cn.execute("PRAGMA ENCODING = 'utf8';") #cur.row_factory = lite.Row cn.text_factory = str row = cur.fetchone() if row != None: userLikes=row[6]+1 cur.execute("UPDATE cookie_giver SET u_likes=? WHERE u_id=?", (userLikes, userId)) cn.commit() else: userLikes=1 cn.execute("CREATE TABLE IF NOT EXISTS cookie_giver(u_id MEDIUMINT, u_name VARCHAR(100), u_first_name VARCHAR(100), u_last_name VARCHAR(100), u_comment TEXT, u_time DATETIME,u_likes MEDIUMINT);") cn.execute("INSERT INTO cookie_giver VALUES (?, ?, ?, ?, ?, ?,?);", (userId, userName, userFirstName, userLastName, userMessage, datetime.now(),userLikes)) cn.commit() cn.close(); #test2() readDATA() fetchingDATA() readDATA()
Fresnoy/kart
common/migrations/0001_initial.py
Python
agpl-3.0
1,169
0.002566
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='BTBeacon', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, a
uto_created=True, primary_key=True)), ('label', models.CharField(max_length=255)), ('uuid', models.UUIDField(unique=True, max_length=32)), ('rssi_in', models.IntegerField()), ('rssi_out', models.IntegerField()), ], ), migrations.CreateModel( name='Website', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=Fals
e, auto_created=True, primary_key=True)), ('title_fr', models.CharField(max_length=255)), ('title_en', models.CharField(max_length=255)), ('language', models.CharField(max_length=2, choices=[(b'FR', b'French'), (b'EN', b'English')])), ('url', models.URLField()), ], ), ]
pferreir/indico-backup
indico/MaKaC/webinterface/common/slotDataWrapper.py
Python
gpl-3.0
9,205
0.023031
# -*- coding: utf-8 -*- ## ## ## This file is part of Indico. ## Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN). ## ## Indico 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. ## ## Indico 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 Indico;if not, see <http://www.gnu.org/licenses/>. from datetime import timedelta,datetime from MaKaC.i18n import _ from MaKaC.errors import MaKaCError, NoReportError from pytz import timezone class Convener: def __init__(self,id,data={}): self._id=id self.setValues(data) def setValues(self, data): self._title=data.get("conv_title","") self._firstName=data.get("conv_first_name","") self._familyName=data.get("conv_family_name","") self._affiliation=data.get("conv_affiliation","") self._email=data.get("conv_email","") def mapConvener(self,conv): self._title=conv.getTitle() self._firstName=conv.getFirstName() self._familyName=conv.getSurName() self._affiliation=conv.getAffiliation() self._email=conv.getEmail() def getTitle(self): return self._title def getId(self): return self._id def setId(self, id): self._id = id def getFirstName(self): return self._firstName def getFamilyName(self): return self._familyName def getAffiliation(self): return self._affiliation def getEmail(self): return self._email class Slot: def __init__(self, data={}): self.setValues(data) def setValues(self, data): self._id=data.get("id","") self._session=data.get("session",None) self._title=data.get("title", "") if data.get("locationAction","") == "inherit": data["locationName"] = "" if data.get("roomAction","") == "inherit": data["roomName"] = "" self._locationName=data.get("locationName","") self._locationAddress=data.get("locationAddress","") self._roomName=data.get("roomName","") self._startDate=None self._endDate=None if data: tz = self._session.getConference().getTimezone() if data.has_key("sDate"): self._startDate=data["sDate"] elif data.get("sYear","")!="" and data.get("sMonth","")!="" and \ data.get("sDay","")!="" and data.get("sHour","")!="" and \ data.get("sMinute","")!="": self._startDate=timezone(tz).localize(datetime( int( data["sYear"] ), \ int( data["sMonth"] ), \ int( data["sDay"] ), \ int( data["sHour"] ), \ int( data["sMinute"] ) ) ) if data.has_key("eDate"): self._endDate=data["eDate"] elif data.get("eYear","")!="" and data.get("eMonth","")!="" and \ data.get("eDay","")!="" and data.get("eHour","")!="" and \ data.get("eMinute","")!="": self._endDate=timezone(tz).localize(datetime( int( data["eYear"] ), \ int( data["eMonth"] ), \ int( data["eDay"] ), \ int( data["eHour"] ), \ int( data["eMinute"] ) ) ) self._duration=None if data.get("durHours","")!="" and data.get("durMins","")!="": self._duration = timedelta(hours=int(data["durHours"]),minutes=int(data["durMins"])) self._contribDuration=None if data.get("contribDurHours","")!="" and data.get("contribDurMins","")!="": self._contribDuration=timedelta(hours=int(data["contribDurHours"]),minutes=int(data["contribDurMins"])) elif data.get("contribDuration","")!="": self._contribDuration= data.get("contribDuration") self._conveners=[] for i in range(len(data.get("conv_id",[]))): val={ "conv_title":data["conv_title"][i], "conv_first_name":data["conv_first_name"][i], "
conv_family_name":data["conv_family_name"][i], "conv_affiliation":data["conv_affiliation"][i], "conv_email":data["conv_email"][i] } id=len(self._conveners) self._conveners.append(Convener(id,val)) def mapSlot(self, slot): self._id=slot.getId() self._session=slot.getSession()
self._title=slot.getTitle() self._locationName="" self._locationAddress="" location = slot.getOwnLocation() if location is not None: self._locationName=location.getName() self._locationAddress=location.getAddress() self._roomName="" room = slot.getOwnRoom() if room is not None: self._roomName=room.getName() self._startDate=slot.getStartDate() self._endDate=slot.getEndDate() self._duration=slot.getDuration() self._contribDuration=slot.getContribDuration() self._conveners=[] for conv in slot.getOwnConvenerList(): val={ "conv_title":conv.getTitle(), "conv_first_name":conv.getFirstName(), "conv_family_name":conv.getFamilyName(), "conv_affiliation":conv.getAffiliation(), "conv_email":conv.getEmail() } id=len(self._conveners) self._conveners.append(Convener(id,val)) def getId(self): return self._id def getSession(self): return self._session def getTitle(self): return self._title def getLocationName(self): return self._locationName def getLocationAddress(self): return self._locationAddress def getRoomName(self): return self._roomName def getStartDate(self): return self._startDate def getAdjustedStartDate(self): return self._startDate.astimezone(timezone(self.getSession().getTimezone())) def getEndDate(self): return self._endDate def getAdjustedEndDate(self): return self._endDate.astimezone(timezone(self.getSession().getTimezone())) def getDuration(self): return self._duration def getContribDuration(self): return self._contribDuration def getConvenerList(self): return self._conveners def hasErrors(self): return False def checkErrors(self): for conv in self.getConvenerList(): if conv.getFirstName().strip() == "": raise NoReportError( _("FIRST NAME has not been specified for convener #%s")%idx ) if conv.getFamilyName().strip() == "": raise NoReportError( _("SURNAME has not been specified for convener #%s")%idx ) if conv.getAffiliation().strip() == "": raise NoReportError( _("AFFILIATION has not been specified for convener #%s")%idx ) if conv.getEmail().strip() == "": raise NoReportError( _("EMAIL has not been specified for convener #%s")%idx ) def updateSlot(self,slot): slot.setTitle(self.getTitle()) slot.setself._locationName="" self._locationAddress="" location = slot.getOwnLocation() if location is not None: self._locationName=location.getName() self._locationAddress=location.getAddress() self._roomName="" room = slot.getOwnRoom() if room is not None: self._roomName=room.getName() self._startDate=slot.getStartDate() self._endD
hasgeek/hasjob
migrations/versions/470c8feb73cc_jobapplication_repli.py
Python
agpl-3.0
469
0.006397
"""JobApplication.replied_by Revision ID: 470c8feb73cc Revises: 449914911f93 Create Date: 2013-12-14 22
:32:49.982184 """ # revision identifiers, used by Alembic. revision = '470c8feb73cc' down_revision = '449914911f93' from alembic import op import sqlalchemy as sa def upgrade(): op.add_column( 'job_application', sa.Column('replied_by_
id', sa.Integer(), nullable=True) ) def downgrade(): op.drop_column('job_application', 'replied_by_id')
houqp/iris-api
src/iris/applications/dummy_app.py
Python
bsd-2-clause
143
0
class dummy_app(object):
name = 'dummy app' def __i
nit__(self, vendor): vendor.time_taken = 2 self.send = vendor.send
test-organization-tmp/test-repo
examples/pipelines/multiple_subjects.py
Python
bsd-3-clause
4,182
0
""" =============================== Multiple subjects pipeline demo =============================== A basic multiple subjects pipeline. CBF maps are normalized to the reference MNI template. """ import matplotlib.pylab as plt import nipype.interfaces.spm as
spm from nipype.caching import Memory from nilearn import plotting from procasl import preprocessing, quantification, datasets, _utils # Load the dataset heroes = datasets.load_heroes_dataset( subjects_parent_directory='/tmp/procasl_data/heroes', dataset_pattern={'anat': 't1mri/acquisition1/anat*.nii', 'basal ASL': 'fMRI
/acquisition1/basal_rawASL*.nii'}) # Create a memory context mem = Memory('/tmp') # Loop over subjects for (func_file, anat_file) in zip( heroes['basal ASL'], heroes['anat']): # Get Tag/Control sequence get_tag_ctl = mem.cache(preprocessing.GetTagControl) out_get_tag_ctl = get_tag_ctl(in_file=func_file) # Rescale rescale = mem.cache(preprocessing.Rescale) out_rescale = rescale(in_file=out_get_tag_ctl.outputs.tag_ctl_file, ss_tr=35.4, t_i_1=800., t_i_2=1800.) # Realign to first scan realign = mem.cache(preprocessing.Realign) out_realign = realign( in_file=out_rescale.outputs.rescaled_file, register_to_mean=False, correct_tagging=True) # Compute mean ASL average = mem.cache(preprocessing.Average) out_average = average(in_file=out_realign.outputs.realigned_files) # Segment anat segment = mem.cache(spm.Segment) out_segment = segment( data=anat_file, gm_output_type=[True, False, True], wm_output_type=[True, False, True], csf_output_type=[True, False, True], save_bias_corrected=True) # Coregister anat to mean ASL coregister_anat = mem.cache(spm.Coregister) out_coregister_anat = coregister_anat( target=out_average.outputs.mean_file, source=anat_file, apply_to_files=[out_segment.outputs.native_gm_image, out_segment.outputs.native_wm_image], write_interp=3, jobtype='estwrite') # Get M0 get_m0 = mem.cache(preprocessing.GetM0) out_get_m0 = get_m0(in_file=func_file) # Coregister M0 to mean ASL coregister_m0 = mem.cache(spm.Coregister) out_coregister_m0 = coregister_m0( target=out_average.outputs.mean_file, source=out_get_m0.outputs.m0_file, write_interp=3, jobtype='estwrite') # Smooth M0 smooth_m0 = mem.cache(spm.Smooth) out_smooth_m0 = smooth_m0( in_files=out_coregister_m0.outputs.coregistered_source, fwhm=[5., 5., 5.]) # Compute perfusion n_scans = preprocessing.get_scans_number( out_realign.outputs.realigned_files) ctl_scans = range(1, n_scans, 2) tag_scans = range(0, n_scans, 2) perfusion_file = quantification.compute_perfusion( out_realign.outputs.realigned_files, ctl_scans=ctl_scans, tag_scans=tag_scans) # Compute CBF quantify = mem.cache(quantification.QuantifyCBF) out_quantify = quantify( perfusion_file=perfusion_file, m0_file=out_smooth_m0.outputs.smoothed_files, tr=2500., t1_gm=1331.) # Compute brain mask brain_mask_file = preprocessing.compute_brain_mask( out_coregister_anat.outputs.coregistered_source, frac=.2) # Normalize CBF normalize = mem.cache(spm.Normalize) out_normalize = normalize( parameter_file=out_segment.outputs.transformation_mat, apply_to_files=[out_quantify.outputs.cbf_file, brain_mask_file], write_voxel_sizes=_utils.get_vox_dims(func_file), write_interp=2, jobtype='write') # Mask CBF map with brain mask cbf_map = preprocessing.apply_mask( out_normalize.outputs.normalized_files[0], out_normalize.outputs.normalized_files[1]) # Plot CBF map on top of MNI template plotting.plot_stat_map( cbf_map, bg_img='/usr/share/fsl/5.0/data/standard/MNI152_T1_2mm.nii.gz', threshold=.1, vmax=150., display_mode='z') plt.show()
ychen820/microblog
y/google-cloud-sdk/platform/google_appengine/lib/django-1.4/django/contrib/auth/hashers.py
Python
bsd-3-clause
14,277
0.00007
import hashlib from django.conf import settings from django.utils import importlib from django.utils.datastructures import SortedDict from django.utils.encoding import smart_str from django.core.exceptions import ImproperlyConfigured from django.utils.crypto import ( pbkdf2, constant_time_compare, get_random_string) from django.utils.translation import ugettext_noop as _ UNUSABLE_PASSWORD = '!' # This will never be a valid encoded hash HASHERS = None # lazily loaded from PASSWORD_HASHERS PREFERRED_HASHER = None # defaults to first item in PASSWORD_HASHERS def is_password_usable(encoded): return (encoded is not None and encoded != UNUSABLE_PASSWORD) def check_password(password, encoded, setter=None, preferred='default'): """ Returns a boolean of whether the raw password matches the three part encoded digest. If setter is specified, it'll be called when you need to regenerate the password. """ if not password or not is_password_usable(encoded): return False preferred = get_hasher(preferred) raw_password = password password = smart_str(password) encoded = smart_str(encoded) # Ancient versions of Django created plain MD5 passwords and accepted # MD5 passwords with an empty salt. if ((len(encoded) == 32 and '$' not in encoded) or (len(encoded) == 37 and encoded.startswith('md5$$'))): hasher = get_hasher('unsalted_md5') # Ancient versions of Django accepted SHA1 passwords with an empty salt. elif len(encoded) == 46 and encoded.startswith('sha1$$'): hasher = get_hasher('unsalted_sha1') else: algorithm = encoded.split('$', 1)[0] hasher = get_hasher(algorithm) must_update = hasher.algorithm != preferred.algorithm is_correct = hasher.verify(password, encoded) if setter and is_correct and must_update: setter(raw_password) return is_correct def make_password(password, salt=None, hasher='default'): """ Turn a plain-text password into a hash for database storage Same as encode() but generates a new random salt. If password is None or blank then UNUSABLE_PASSWORD will be returned which disallows logins. """ if not password: return UNUSABLE_PASSWORD hasher = get_hasher(hasher) password = smart_str(password) if not salt: salt = hasher.salt() salt = smart_str(salt) return hasher.encode(password, salt) def load_hashers(password_hashers=None): global HASHERS global PREFERRED_HASHER hashers = [] if not password_hashers: password_hashers = settings.PASSWORD_HASHERS for backend in password_hashers: try: mod_path, cls_name = backend.rsplit('.', 1) mod = importlib.import_module(mod_path) hasher_cls = getattr(mod, cls_name) except (AttributeError, ImportError, ValueError): raise ImproperlyConfigured("hasher not found: %s" % backend) hasher = hasher_cls() if not getattr(hasher, 'algorithm'): raise ImproperlyConfigured("hasher doesn't specify an " "algorithm name: %s" % backend) hashers.append(hasher) HASHERS = dict([(hasher.algorithm, hasher) for hasher in hashers]) PREFERRED_HASHER = hashers[0] def get_hasher(algorithm='default'): """ Returns an instance of a loaded password hasher. If algorithm is 'default', the default hasher will be returned. This function will also lazy import hashers specified in your settings file if needed. """ if hasattr(algorithm, 'algorithm'): return algorithm elif algorithm == 'default': if PREFERRED_HASHER is None: load_hashers() return PREFERRED_HASHER else: if HASHERS is None: load_hashers() if algorithm not in HASHERS: raise ValueError("Unknown password hashing algorithm '%s'. " "Did you specify it in the PASSWORD_HASHERS " "setting?" % algorithm) return HASHERS[algorithm] def mask_hash(hash, show=6, char="*"): """ Returns the given hash, with only the first ``show`` number shown. The rest are masked with ``char`` for security reasons. """ masked = hash[:show] masked += char * len(hash[show:]) return masked class BasePasswordHasher(object): """ Abstract base class for password hashers When creating your own hasher, you need to override algorithm, verify(), encode() and safe_summary(). PasswordHasher objects are immutable. """ algorithm = None library = None def _load_library(self): if self.library is not None: if isinstance(self.library, (tuple, list)): name, mod_path = self.library else: name = mod_path = self.library try: module = importlib.import_module(mod_path) except ImportError: raise ValueError("Couldn't load %s password algorithm " "library" % name) return module raise ValueError("Hasher '%s' doesn't specify a library attribute" % self.__class__) def salt(self): """ Generates a cryptographically secure nonce salt in ascii """ return get_random_string() def verify(self, password, encoded): """ Checks if the given password is correct """ raise NotImplementedError() def encode(self, password, salt): """ Creates an encoded database value The result is normally formatted as "algorithm$salt$hash" and must be fewer than 128 characters. """ raise NotImplementedError() def safe_summary(self, encoded): """ Returns a summary of safe values The result is a dictionary and will be used where the password field must be displayed to construct a safe representation of the password.
""" raise NotImplementedError() class PBKDF2PasswordHasher(BasePasswordHasher): """ Secure password hashing using the PBKDF2 algorithm (recommended) Configured to use PBKDF2 + HMAC + SHA256 with 10000 iterations. The result is a 64 byte binary string. Iterations may be changed safely but you must rename the algorithm if you change SHA256. """ algorithm = "pbkdf2_sha256" i
terations = 10000 digest = hashlib.sha256 def encode(self, password, salt, iterations=None): assert password assert salt and '$' not in salt if not iterations: iterations = self.iterations hash = pbkdf2(password, salt, iterations, digest=self.digest) hash = hash.encode('base64').strip() return "%s$%d$%s$%s" % (self.algorithm, iterations, salt, hash) def verify(self, password, encoded): algorithm, iterations, salt, hash = encoded.split('$', 3) assert algorithm == self.algorithm encoded_2 = self.encode(password, salt, int(iterations)) return constant_time_compare(encoded, encoded_2) def safe_summary(self, encoded): algorithm, iterations, salt, hash = encoded.split('$', 3) assert algorithm == self.algorithm return SortedDict([ (_('algorithm'), algorithm), (_('iterations'), iterations), (_('salt'), mask_hash(salt)), (_('hash'), mask_hash(hash)), ]) class PBKDF2SHA1PasswordHasher(PBKDF2PasswordHasher): """ Alternate PBKDF2 hasher which uses SHA1, the default PRF recommended by PKCS #5. This is compatible with other implementations of PBKDF2, such as openssl's PKCS5_PBKDF2_HMAC_SHA1(). """ algorithm = "pbkdf2_sha1" digest = hashlib.sha1 class BCryptPasswordHasher(BasePasswordHasher): """ Secure password hashing using the bcrypt algorithm (recommended) This is considered by many to be the most secure algorithm but you must first install the py-bcrypt library. Please be warned that th
mldbai/mldb
testing/MLDB-963-when-in-WHEN.py
Python
apache-2.0
4,955
0.001615
# # MLDB-963-when-in-WHEN.py # mldb.ai inc, 2015 # This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved. # import unittest import datetime from mldb import mldb now = datetime.datetime.now() - datetime.timedelta(seconds=1) class WhenInWhen(unittest.TestCase): @classmethod def setUpClass(cls): same_time_tomorrow = now + datetime.timedelta(days=1) ds1 = mldb.create_dataset({ 'type': 'sparse.mutable', 'id': 'dataset1'}) row_count = 10 for i in range(row_count - 1): # row name is x's value ds1.record_row(str(i), [['x', str(i), same_time_tomorrow], ['y', str(i), now]]) ds1.record_row(str(row_count - 1), [['x', "9", same_time_tomorrow], ['y', "9", same_time_tomorrow]]) ds1.commit() def test_1(self): def validate1(result): mldb.log(result) for row in result.json(): if row['rowName'] != '9': self.assertEqual(len(row["columns"]), 1, 'expected x to be filtered out') else: self.assertTrue('columns ' not in row, 'expected x and y to be filtered out') validate1(mldb.get( '/v1/query', q="SELECT * FROM dataset1 WHEN value_timestamp() < latest_timestamp(x)")) def test_2(self): def validate2(result): mldb.log(result) rows = result.json() msg = 'expected where clause to filter all but row 9' self.assertEqual(len(rows), 1, msg) self.assertEqual(rows[0]['rowName'], '9', msg) self.assertEqual( len(rows[0]['columns']), 2, 'expected the two tuples to be preserved by WHEN clause') validate2(mldb.get( '/v1/query', q="SELECT * FROM dataset1 WHEN value_timestamp() = latest_timestamp(x) WHERE x = '9'")) def test_3(self): def validate3(result): mldb.log(result) rows = result.json() for row in rows: if row['rowName'] != '9': self.assertEqual(len(row["columns"]), 1, 'expected y to be filtered out') else: self.assertEqual(len(row["columns"]), 2, 'expected x and y to be preserved') validate3(mldb.get( '/v1/query', q="SELECT * FROM dataset1 WHEN value_timestamp() > now()")) def test_4(self): def validate4(result): mldb.log(result) rows = result.json() for row in rows: if row['rowName'] != '9': self.assertEqual(len(row["columns"]), 1, 'expected y to be filtered out') else: self.assertEqual(len(row["columns"]), 2, 'expected x and y to be preserved') validate4(mldb.get( '/v1/query', q="SELECT * FROM dataset1 WHEN value_timestamp() BETWEEN now() AND " "now() + INTERVAL '1W'")) def test_5(self): def validate5(result): mldb.log(result) rows = result.json() for row in rows: self.assertEqual(len(row["columns"]), 2, 'expected x and y to be preserved') validate5(mldb.get( '/v1/query', q="SELECT * FROM dataset1 WHEN value_timestamp() " "BETWEEN now() - INTERVAL '1d' AND latest_timestamp({*})")) def test_6(self): def validate6(result): mldb.log(result) rows = result.json() for row in rows: self.assertTrue('columns' not in row, 'expected all values to be filtered out') validate6(mldb.get( '/v1/query', q="SELECT * FROM dataset1 WHEN value_timestamp() " "BETWEEN latest_timestamp({*}) + INTERVAL '1s' AND '2026-01-01'")) def test_7(self): def validate7(result): mldb.log(result) rows = result.json() for row in rows: if row['rowName'] != '9': self.assertTrue('columns' not in row, 'expected x and y to be filtered out') else: self.assertEqual(len(row["columns"]), 2, 'expected x and y to be preserved') validate7(mldb.get( '/v1/query', q="SELECT * FROM dataset1 WHEN latest_timestamp(y) > to_timestamp('%s') + INTERVAL '2s'
" % now)) if __name__ == '__main__': mldb.run_t
ests()
dahool/vertaal
appfeeds/feeds.py
Python
gpl-3.0
6,268
0.00702
from django.contrib.syndication.feeds import Feed from django.core.exceptions import ObjectDoesNotExist from django.utils.translation import ugettext as _ from django.shortcuts import get_object_or_404 from django.conf import settings from django.core.urlresolvers import reverse from django.contrib.auth.models import User from files.models import POFileLog, POFileSubmit, POFile, SUBMIT_STATUS_ENUM from projects.models import Project from releases.models import Release from languages.models import Language #site_name = getattr(settings, 'PROJECT_NAME','') class ReleaseUpdates(Feed): total_feeds = 50 def get_object(self, bits): ''' bits[0] => release slug bits[1] => lang code ''' if len(bits) == 0: raise ObjectDoesNotExist release_slug = bits[0] release = Release.objects.get(slug=release_slug) if not release.enabled or not release.project.enabled: raise ObjectDoesNotExist try: lang_code = bits[1] self.language = get_object_or_404(Language, code=lang_code) except IndexError: self.language = None if "user" in self.request.GET: self.user = User.objects.get(username=self.request.GET['user']) else: self.user = None return release def title(self, release): if self.language: return _("%(project)s: Release %(release)s :: %(language)s") % { 'project': release.project.name, 'language': self.language.name, 'release': release.name,} else: return _("%(project)s: Release %(release)s") % { 'project': release.project.name, 'release': release.name,} def description(self, release): if self.language: return _("Latest actions for %(language)s language in " "release %(release)s.") % { 'language': self.language.name, 'release': release.name,} else: return _("Latest actions in release %(release)s.") % { 'release': release.name,} def link(self, release): if not release: raise FeedDoesNotExist if self.language: return reverse('list_files', kwargs={ 'release': release.slug, 'language': self.language.code}) else: return release.get_absolute_url() def items(self, release): retur
n POFileLog.objects.last_actions(user=self.user, release=rele
ase, limit=self.total_feeds, language=self.language) def item_pubdate(self, item): return item.created def item_link(self, item): link = '%s?%s#%s' % (reverse('list_files', kwargs={ 'release': item.pofile.release.slug, 'language': item.pofile.language.code}), item.id, item.pofile.slug) return link class CommitQueue(Feed): def get_object(self, bits): ''' bits[0] => project slug bits[1] => lang code ''' if len(bits) == 0: raise ObjectDoesNotExist project_slug = bits[0] project = Project.objects.get(slug=project_slug) if not project.enabled: raise ObjectDoesNotExist try: lang_code = bits[1] self.language = get_object_or_404(Language, code=lang_code) except IndexError: self.language = None return project def title(self, project): if self.language: return _("Submission queue status for %(project)s :: %(language)s") % { 'project': project.name, 'language': self.language.name,} else: return _("Submission queue status for %(project)s") % { 'project': project.name,} def description(self, project): return _("Files in the submission queue.") def link(self, project): if not project: raise FeedDoesNotExist return reverse('commit_queue') def items(self, project): if self.language: return POFileSubmit.objects.by_project_and_language(project, self.language) else: return POFileSubmit.objects.filter(project=project, enabled=True, status=SUBMIT_STATUS_ENUM.PENDING) def item_pubdate(self, item): return item.created def item_link(self, item): link = '%s?%s' % (reverse('commit_queue'), item.id) return link class FileFeed(Feed): def get_object(self, bits): ''' bits[0] => slug ''' if len(bits) == 0: raise ObjectDoesNotExist slug = bits[0] pofile = get_object_or_404(POFile, slug=slug) return pofile def title(self, pofile): return _("%(file)s :: %(project)s %(release)s") % { 'file': pofile.filename, 'release': pofile.release.name, 'project': pofile.release.project.name} def description(self, pofile): return _("Latest actions for %(file)s in %(project)s %(release)s") % { 'file': pofile.filename, 'release': pofile.release.name, 'project': pofile.release.project.name} def link(self, pofile): if not pofile: raise FeedDoesNotExist return reverse('file_detail', kwargs={'slug': pofile.slug}) def items(self, pofile): return pofile.log.all() def item_pubdate(self, item): return item.created def item_link(self, item): return reverse('file_detail', kwargs={'slug': item.pofile.slug})
tanderegg/ansible-modules-core
network/cumulus/cl_bridge.py
Python
gpl-3.0
13,081
0.000382
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2016, Cumulus Networks <ce-ceng@cumulusnetworks.com> # # This file is part of Ansible # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. DOCUMENTATION = ''' --- module: cl_bridge version_added: "2.1" author: "Cumulus Networks (@CumulusNetworks)" short_description: Configures a bridge port on Cumulus Linux description: - Configures a bridge interface on Cumulus Linux To configure a bond port use the cl_bond module. To configure any other type of interface use the cl_interface module. Follow the guidelines for bridging found in the Cumulus User Guide at http://docs.cumulusnetworks.com options: name: description: - name of the interface required: true alias_name: description: - add a port description ipv4: description: - list of IPv4 addresses to configure on the interface. use X.X.X.X/YY syntax. ipv6: description: - list of IPv6 addresses to configure on the interface. use X:X:X::X/YYY syntax addr_method: description: - configures the port to use DHCP. To enable this feature use the option 'dhcp' choices: ['dhcp'] mtu: description: - set MTU. Configure Jumbo Frame by setting MTU to 9000. virtual_ip: description: - define IPv4 virtual IP used by the Cumulus Linux VRR feature virtual_mac: description: - define Ethernet mac associated with Cumulus Linux VRR feature vids: description: - in vlan aware mode, lists vlans defined under the interface pvid: description: - in vlan aware mode, defines vlan that is the untagged vlan stp: description: - e
nables spanning tree. As of Cumulus Linux 2.5 the default bridging mode, only per vlan RSTP or 802.1d is supported. For the
vlan aware mode, only common instance STP is supported default: 'yes' ports: description: - list of bridge members required: True vlan_aware: description: - enables vlan aware mode. mstpctl_treeprio: description: - set spanning tree root priority. Must be a multiple of 4096 location: description: - interface directory location default: - /etc/network/interfaces.d requirements: [ Alternate Debian network interface manager ifupdown2 @ github.com/CumulusNetworks/ifupdown2 ] notes: - because the module writes the interface directory location. Ensure that ``/etc/network/interfaces`` has a 'source /etc/network/interfaces.d/*' or whatever path is mentioned in the ``location`` attribute. - For the config to be activated, i.e installed in the kernel, "service networking reload" needs be be executed. See EXAMPLES section. ''' EXAMPLES = ''' # Options ['virtual_mac', 'virtual_ip'] are required together # configure a bridge vlan aware bridge. cl_bridge: name=br0 ports='swp1-12' vlan_aware='yes' notify: reload networking # configure bridge interface to define a default set of vlans cl_bridge: name=bridge ports='swp1-12' vlan_aware='yes' vids='1-100' notify: reload networking # define cl_bridge once in tasks file # then write inteface config in variables file # with just the options you want. cl_bridge: name: "{{ item.key }}" ports: "{{ item.value.ports }}" vlan_aware: "{{ item.value.vlan_aware|default(omit) }}" ipv4: "{{ item.value.ipv4|default(omit) }}" ipv6: "{{ item.value.ipv6|default(omit) }}" alias_name: "{{ item.value.alias_name|default(omit) }}" addr_method: "{{ item.value.addr_method|default(omit) }}" mtu: "{{ item.value.mtu|default(omit) }}" vids: "{{ item.value.vids|default(omit) }}" virtual_ip: "{{ item.value.virtual_ip|default(omit) }}" virtual_mac: "{{ item.value.virtual_mac|default(omit) }}" mstpctl_treeprio: "{{ item.value.mstpctl_treeprio|default(omit) }}" with_dict: cl_bridges notify: reload networking # In vars file # ============ cl_bridge: br0: alias_name: 'vlan aware bridge' ports: ['swp1', 'swp3'] vlan_aware: true vids: ['1-100'] ''' RETURN = ''' changed: description: whether the interface was changed returned: changed type: bool sample: True msg: description: human-readable report of success or failure returned: always type: string sample: "interface bond0 config updated" ''' # handy helper for calling system calls. # calls AnsibleModule.run_command and prints a more appropriate message # exec_path - path to file to execute, with all its arguments. # E.g "/sbin/ip -o link show" # failure_msg - what message to print on failure def run_cmd(module, exec_path): (_rc, out, _err) = module.run_command(exec_path) if _rc > 0: if re.search('cannot find interface', _err): return '[{}]' failure_msg = "Failed; %s Error: %s" % (exec_path, _err) module.fail_json(msg=failure_msg) else: return out def current_iface_config(module): # due to a bug in ifquery, have to check for presence of interface file # and not rely solely on ifquery. when bug is fixed, this check can be # removed _ifacename = module.params.get('name') _int_dir = module.params.get('location') module.custom_current_config = {} if os.path.exists(_int_dir + '/' + _ifacename): _cmd = "/sbin/ifquery -o json %s" % (module.params.get('name')) module.custom_current_config = module.from_json( run_cmd(module, _cmd))[0] def build_address(module): # if addr_method == 'dhcp', dont add IP address if module.params.get('addr_method') == 'dhcp': return _ipv4 = module.params.get('ipv4') _ipv6 = module.params.get('ipv6') _addresslist = [] if _ipv4 and len(_ipv4) > 0: _addresslist += _ipv4 if _ipv6 and len(_ipv6) > 0: _addresslist += _ipv6 if len(_addresslist) > 0: module.custom_desired_config['config']['address'] = ' '.join( _addresslist) def build_vids(module): _vids = module.params.get('vids') if _vids and len(_vids) > 0: module.custom_desired_config['config']['bridge-vids'] = ' '.join(_vids) def build_pvid(module): _pvid = module.params.get('pvid') if _pvid: module.custom_desired_config['config']['bridge-pvid'] = str(_pvid) def conv_bool_to_str(_value): if isinstance(_value, bool): if _value is True: return 'yes' else: return 'no' return _value def build_generic_attr(module, _attr): _value = module.params.get(_attr) _value = conv_bool_to_str(_value) if _value: module.custom_desired_config['config'][ re.sub('_', '-', _attr)] = str(_value) def build_alias_name(module): alias_name = module.params.get('alias_name') if alias_name: module.custom_desired_config['config']['alias'] = alias_name def build_addr_method(module): _addr_method = module.params.get('addr_method') if _addr_method: module.custom_desired_config['addr_family'] = 'inet' module.custom_desired_config['addr_method'] = _addr_method def build_vrr(module): _virtual_ip = module.params.get('virtual_ip') _virtual_mac = module.params.get('virtual_mac') vrr_config = [] if _virtual_ip: vrr_config.append(_virtual_mac) vrr_config.append(_virtual_ip) module.cust
jeditekunum/Cosa
build/miniterm.py
Python
lgpl-2.1
23,810
0.012264
#!/usr/bin/env python # Very simple serial terminal # (C)2002-2009 Chris Liechti <cliechti@gmx.net> # Input characters are sent directly (only LF -> CR/LF/CRLF translation is # done), received characters are displayed as is (or escaped trough pythons # repr, useful for debug purposes). import sys, os, serial, threading, time EXITCHARCTER = '\x1d' # GS/CTRL+] MENUCHARACTER = '\x14' # Menu: CTRL+T def key_description(character): """generate a readable description for a key""" ascii_code = ord(character) if ascii_code < 32: return 'Ctrl+%c' % (ord('@') + ascii_code) else: return repr(character) # help text, starts with blank line! it's a function so that the current values # for the shortcut keys is used and not the value at program start def get_help_text(): return """ --- pySerial (%(version)s) - miniterm - help --- --- %(exit)-8s Exit program --- %(menu)-8s Menu escape key, followed by: --- Menu keys: --- %(itself)-8s Send the menu character itself to remote --- %(exchar)-8s Send the exit character to remote --- %(info)-8s Show info --- %(upload)-8s Upload file (prompt will be shown) --- Toggles: --- %(rts)s RTS %(echo)s local echo --- %(dtr)s DTR %(break)s BREAK --- %(lfm)s line feed %(repr)s Cycle repr mode --- --- Port settings (%(menu)s followed by the following): --- 7 8 set data bits --- n e o s m change parity (None, Even, Odd, Space, Mark) --- 1 2 3 set stop bits (1, 2, 1.5) --- b change baud rate --- x X disable/enable software flow control --- r R disable/enable hardware flow control """ % { 'version': getattr(serial, 'VERSION', 'unkown'), 'exit': key_description(EXITCHARCTER), 'menu': key_description(MENUCHARACTER), 'rts': key_description('\x12'), 'repr': key_description('\x01'), 'dtr': key_description('\x04'), 'lfm': key_description('\x0c'), 'break': key_description('\x02'), 'echo': key_description('\x05'), 'info': key_description('\x09'), 'upload': key_description('\x15'), 'itself': key_description(MENUCHARACTER), 'exchar': key_description(EXITCHARCTER), } # first choose a platform dependant way to read single characters from the console global console if os.name == 'nt': import msvcrt class Console: def __init__(self): pass def setup(self): pass # Do nothing for 'nt' def cleanup(self): pass # Do nothing for 'nt' def getkey(self): while 1: z = msvcrt.getch() if z == '\0' or z == '\xe0': # functions keys msvcrt.getch() else: if z == '\r': return '\n' return z console = Console() elif os.name == 'posix': import termios, sys, os class Console: def __init__(self): self.fd = sys.stdin.fileno() def setup(self): self.old = termios.tcgetattr(self.fd) new = termios.tcgetattr(self.fd) new[3] = new[3] & ~termios.ICANON & ~termios.ECHO & ~termios.ISIG new[6][termios.VMIN] = 1 new[6][termios.VTIME] = 0 termios.tcsetattr(self.fd, termios.TCSANOW, new) def getkey(self): c = os.read(self.fd, 1) return c def cleanup(self): termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old) console = Console() def cleanup_console(): console.cleanup() console.setup() sys.exitfunc = cleanup_console #terminal modes have to be restored on exit... else: raise NotImplementedError("Sorry no implementation for your platform (%s) available." % sys.platform) CONVERT_CRLF = 2 CONVERT_CR = 1 CONVERT_LF = 0 NEWLINE_CONVERISON_MAP = ('\n', '\r', '\r\n') LF_MODES = ('LF', 'CR', 'CR/LF') REPR_MODES = ('raw', 'some control', 'all control', 'hex') class Miniterm: def __init__(self, port, baudrate, parity, rtscts, xonxoff, echo=False, convert_outgoing=CONVERT_CRLF, repr_mode=0): try: self.serial = serial.serial_for_url(port, baudrate, parity=parity, rtscts=rtscts, xonxoff=xonxoff, timeout=1, stopbits=2) except AttributeError: # happens when the installed pyserial is older than 2.5. use the # Serial class directly then. self.serial = serial.Serial(port, baudrate, parity=parity, rtscts=rtscts, xonxoff=xonxoff, timeout=1, stopbits=2) self.echo = echo self.repr_mode = repr_mode self.convert_outgoing = convert_outgoing self.newline = NEWLINE_CONVERISON_MAP[self.convert_outgoing] self.dtr_state = True self.rts_state = True self.break_state = False def start(self): self.alive = True # start serial->console thread self.receiver_thread = threading.Thread(target=self.reader) self.receiver_thread.setDaemon(1) self.receiver_thread.start() # enter console->serial loop self.transmitter_thread = threading.Thread(target=self.writer) self.transmitter_thread.setDaemon(1) self.transmitter_thread.start() def stop(self): self.alive = False def join(self, transmit_only=False): if not transmit_only: self.receiver_thread.join() # self.transmitter_thread.join() def dump_port_settings(self): sys.stderr.write("\n--- Settings: %s %s,%s,%s,%s
\n" % ( self.serial.portstr, self.serial.baudrate, self.serial.bytesize, self.serial.parity, self.serial.stopbits, )) sys.stderr.write('--- RTS %s\n' % (self.rts_state and 'active' or 'inactive')) sys.stderr.write('--- DTR %s\n' % (self.dtr_state and 'active' or 'inactive')) sys.stderr.write('--- BREAK %s\n' % (self.break_state and 'active' or 'inactive
')) sys.stderr.write('--- software flow control %s\n' % (self.serial.xonxoff and 'active' or 'inactive')) sys.stderr.write('--- hardware flow control %s\n' % (self.serial.rtscts and 'active' or 'inactive')) sys.stderr.write('--- data escaping: %s\n' % (REPR_MODES[self.repr_mode],)) sys.stderr.write('--- linefeed: %s\n' % (LF_MODES[self.convert_outgoing],)) try: sys.stderr.write('--- CTS: %s DSR: %s RI: %s CD: %s\n' % ( (self.serial.getCTS() and 'active' or 'inactive'), (self.serial.getDSR() and 'active' or 'inactive'), (self.serial.getRI() and 'active' or 'inactive'), (self.serial.getCD() and 'active' or 'inactive'), )) except serial.SerialException: # on RFC 2217 ports it can happen to no modem state notification was # yet received. ignore this error. pass def reader(self): """loop and copy serial->console""" while self.alive: try: data = self.serial.read(1) # data = self.read() # check for exit from device if data == EXITCHARCTER: self.stop() break if self.repr_mode == 0: # direct output, just have to care about newline setting if data == '\r' and self.convert_outgoing == CONVERT_CR: sys.stdout.write('\n') else: sys.stdout.write(data) elif self.repr_mode == 1: # escape non-printable, let pass newlines if self.convert_outgoing == CONVERT_CRLF and data in '\r\n': if data == '\n': sys.stdout.write('\n') elif data == '\r': pass elif data == '\n' and self.convert_outgoing == CONVERT_LF: sys.stdout.write('\n') elif data == '\r' and self.conve
Julian/txjsonrpc-tcp
txjsonrpc/tests/test_jsonrpc.py
Python
mit
8,101
0.009258
from __future__ import absolute_import import json from twisted.internet import defer, error from twisted.python import failure from twisted.test import proto_helpers from twisted.trial import unittest from txjsonrpc import jsonrpc, jsonrpclib class TestJSONRPC(unittest.TestCase): def setUp(self): self.deferred = defer.Deferred() exposed = { "foo" : lambda : setattr(self, "fooFired", True), "bar" : lambda p : setattr(self, "barResult", p ** 2), "baz" : lambda p, q : (q, p), "late" : lambda p : self.deferred, } self.factory = jsonrpc.JSONRPCFactory(exposed.get) self.proto = self.factory.buildProtocol(("127.0.0.1", 0)) self.tr = proto_helpers.StringTransportWithDisconnection() self.proto.makeConnection(self.tr) def assertSent(self, expected): expected["jsonrpc"] = "2.0" self.assertEqual(json.loads(self.tr.value()[2:]), expected) def test_notify(self): """ notify() sends a valid JSON RPC notification. """ self.proto.notify("foo") self.assertSent({"method" : "foo", "params" : []}) self.tr.clear() self.proto.notify("bar", [3]) self.assertSent({"method" : "bar", u"params" : [3]}) def test_request(self): """ request() sends a valid JSON RPC request and returns a deferred. """ d = self.proto.request("foo") self.assertSent({"id" : "1", "method" : "foo", "params" : []}) d.addCallback(lambda r : self.assertEqual(r, [2, 3, "bar"])) receive = {"jsonrpc" : "2.0", "id" : "1", "result" : [2, 3, "bar"]} self.proto.stringReceived(json.dumps(receive)) return d def test_unhandledError(self): """ An unhandled error gets logged and disconnects the transport. """ v = failure.Failure(ValueError("Hey a value error")) self.proto.unhandledError(v) errors = self.flushLoggedErrors(ValueError) self.assertEqual(errors, [v]) def test_invalid_json(self): """ Invalid JSON causes a JSON RPC ParseError and disconnects. """ self.proto.stringReceived("[1,2,") err = {"id" : None, "error" : jsonrpclib.ParseError().toResponse()} self.assertSent(err) errors = self.flushLoggedErrors(jsonrpclib.ParseError) self.assertEqual(len(errors), 1) def test_invalid_request(self): """ An invalid request causes a JSON RPC InvalidRequest and disconnects. """ self.proto.stringReceived(json.dumps({"id" : 12})) err = jsonrpclib.InvalidRequest({"reason" : "jsonrpc"}) self.assertSent({"
id" : None, "error
" : err.toResponse()}) errors = self.flushLoggedErrors(jsonrpclib.InvalidRequest) self.assertEqual(len(errors), 1) def test_unsolicited_result(self): """ An incoming result for an id that does not exist raises an error. """ receive = {"jsonrpc" : "2.0", "id" : "1", "result" : [2, 3, "bar"]} self.proto.stringReceived(json.dumps(receive)) err = jsonrpclib.InternalError({ "exception" : "KeyError", "message" : "u'1'", }) expect = {"jsonrpc" : "2.0", "id" : None, "error" : err.toResponse()} sent = json.loads(self.tr.value()[2:]) tb = sent["error"]["data"].pop("traceback") self.assertEqual(sent, expect) self.assertTrue(tb) # TODO: Raises original exception. Do we want InternalError instead? errors = self.flushLoggedErrors(KeyError) self.assertEqual(len(errors), 1) def _errorTest(self, err): d = self.proto.request("foo").addErrback(lambda f : self.assertEqual( f.value.toResponse(), err.toResponse() )) receive = {"jsonrpc" : "2.0", "id" : "1", "error" : {}} receive["error"] = {"code" : err.code, "message" : err.message} self.proto.stringReceived(json.dumps(receive)) return d def test_parse_error(self): self._errorTest(jsonrpclib.ParseError()) def test_invalid_request(self): self._errorTest(jsonrpclib.InvalidRequest()) def test_method_not_found(self): self._errorTest(jsonrpclib.MethodNotFound()) def test_invalid_params(self): self._errorTest(jsonrpclib.InvalidParams()) def test_internal_error(self): self._errorTest(jsonrpclib.InternalError()) def test_application_error(self): self._errorTest(jsonrpclib.ApplicationError(code=2400, message="Go.")) def test_server_error(self): self._errorTest(jsonrpclib.ServerError(code=-32020)) def test_received_notify(self): receive = {"jsonrpc" : "2.0", "method" : "foo"} self.proto.stringReceived(json.dumps(receive)) self.assertTrue(self.fooFired) receive = {"jsonrpc" : "2.0", "method" : "bar", "params" : [2]} self.proto.stringReceived(json.dumps(receive)) self.assertEqual(self.barResult, 4) def test_received_notify_no_method(self): receive = {"jsonrpc" : "2.0", "method" : "quux"} self.proto.stringReceived(json.dumps(receive)) errors = self.flushLoggedErrors(jsonrpclib.MethodNotFound) self.assertEqual(len(errors), 1) def test_received_notify_wrong_param_type(self): receive = {"jsonrpc" : "2.0", "method" : "foo", "params" : [1, 2]} self.proto.stringReceived(json.dumps(receive)) receive = {"jsonrpc" : "2.0", "method" : "bar", "params" : "foo"} self.proto.stringReceived(json.dumps(receive)) errors = self.flushLoggedErrors(TypeError) self.assertEqual(len(errors), 2) def test_received_request(self): receive = { "jsonrpc" : "2.0", "id" : "1", "method" : "baz", "params" : [1, 2] } self.proto.stringReceived(json.dumps(receive)) self.assertSent({"jsonrpc" : "2.0", "id" : "1", "result" : [2, 1]}) def test_received_request_deferred(self): receive = { "jsonrpc" : "2.0", "id" : "3", "method" : "late", "params" : {"p" : 3} } self.proto.stringReceived(json.dumps(receive)) self.deferred.callback(27) self.assertSent({"jsonrpc" : "2.0", "id" : "3", "result" : 27}) def test_received_request_no_method(self): receive = {"jsonrpc" : "2.0", "id" : "3", "method" : "quux"} self.proto.stringReceived(json.dumps(receive)) errors = self.flushLoggedErrors(jsonrpclib.MethodNotFound) self.assertEqual(len(errors), 1) sent = json.loads(self.tr.value()[2:]) self.assertIn("error", sent) self.assertEqual(sent["error"]["code"], jsonrpclib.MethodNotFound.code) def test_received_request_error(self): receive = { "jsonrpc" : "2.0", "id" : "1", "method" : "foo", "params" : [1, 2] } self.proto.stringReceived(json.dumps(receive)) response = json.loads(self.tr.value()[2:]) self.assertNotIn("result", response) self.assertEqual(response["id"], "1") self.assertEqual(response["error"]["data"]["exception"], "TypeError") self.assertTrue(response["error"]["data"]["traceback"]) errors = self.flushLoggedErrors(TypeError) self.assertEqual(len(errors), 1) errors = self.flushLoggedErrors(error.ConnectionLost) self.assertEqual(len(errors), 1) def test_fail_all(self): d1, d2 = self.proto.request("foo"), self.proto.request("bar", [1, 2]) exc = failure.Failure(ValueError("A ValueError")) self.proto.failAll(exc) d3 = self.proto.request("baz", "foo") for d in d1, d2, d3: d.addErrback(lambda reason: self.assertIs(reason, exc)) def test_connection_lost(self): self.proto.connectionLost(failure.Failure(error.ConnectionLost("Bye"))) return self.proto.request("foo").addErrback( lambda f : self.assertIs(f.type, error.ConnectionLost) )
AzamYahya/shogun
examples/undocumented/python_modular/features_dense_longint_modular.py
Python
gpl-3.0
606
0.062706
#!/usr/bin/env p
ython from modshogun import LongIntFeatures from numpy import array, int64, all # create dense matrix A matrix=array([[1,2,3]
,[4,0,0],[0,0,0],[0,5,0],[0,0,6],[9,9,9]], dtype=int64) parameter_list = [[matrix]] # ... of type LongInt def features_dense_longint_modular (A=matrix): a=LongIntFeatures(A) # get first feature vector and set it a.set_feature_vector(array([1,4,0,0,0,9], dtype=int64), 0) # get matrix a_out = a.get_feature_matrix() assert(all(a_out==A)) return a_out if __name__=='__main__': print('dense_longint') features_dense_longint_modular(*parameter_list[0])
cypsun/FreeCAD
src/Mod/Fem/ccxInpWriter.py
Python
lgpl-2.1
18,324
0.00382
import FemGui import FreeCAD import os import time import sys class inp_writer: def __init__(self, analysis_obj, mesh_obj, mat_obj, fixed_obj, force_obj, pressure_obj, dir_name=None): self.dir_name = dir_name s
elf.mesh_object = mesh_obj self.material_objects = mat_obj self.fixed_objects = fixed_obj self.force_objects = force_obj self.pressure_objects = pressure_obj if not dir_name: self.dir_name = FreeCAD.ActiveDocument.TransientDir.replace('\\', '/') + '/FemAnl_' + analysis_obj.Uid[-4:] if not os.path.isdir(self.dir_name): os.mkdir(self.dir_name) self.ba
se_name = self.dir_name + '/' + self.mesh_object.Name self.file_name = self.base_name + '.inp' def write_calculix_input_file(self): self.mesh_object.FemMesh.writeABAQUS(self.file_name) # reopen file with "append" and add the analysis definition inpfile = open(self.file_name, 'a') inpfile.write('\n\n') self.write_material_element_sets(inpfile) self.write_fixed_node_sets(inpfile) self.write_load_node_sets(inpfile) self.write_materials(inpfile) self.write_step_begin(inpfile) self.write_constraints_fixed(inpfile) self.write_constraints_force(inpfile) self.write_face_load(inpfile) self.write_outputs_types(inpfile) self.write_step_end(inpfile) self.write_footer(inpfile) inpfile.close() return self.base_name def write_material_element_sets(self, f): f.write('\n***********************************************************\n') f.write('** Element sets for materials\n') f.write('** written by {} function\n'.format(sys._getframe().f_code.co_name)) for m in self.material_objects: mat_obj = m['Object'] mat_obj_name = mat_obj.Name mat_name = mat_obj.Material['Name'][:80] f.write('*ELSET,ELSET=' + mat_obj_name + '\n') if len(self.material_objects) == 1: f.write('Eall\n') else: if mat_obj_name == 'MechanicalMaterial': f.write('Eall\n') def write_fixed_node_sets(self, f): f.write('\n***********************************************************\n') f.write('** Node set for fixed constraint\n') f.write('** written by {} function\n'.format(sys._getframe().f_code.co_name)) for fobj in self.fixed_objects: fix_obj = fobj['Object'] f.write('*NSET,NSET=' + fix_obj.Name + '\n') for o, elem in fix_obj.References: fo = o.Shape.getElement(elem) n = [] if fo.ShapeType == 'Face': n = self.mesh_object.FemMesh.getNodesByFace(fo) elif fo.ShapeType == 'Edge': n = self.mesh_object.FemMesh.getNodesByEdge(fo) elif fo.ShapeType == 'Vertex': n = self.mesh_object.FemMesh.getNodesByVertex(fo) for i in n: f.write(str(i) + ',\n') def write_load_node_sets(self, f): f.write('\n***********************************************************\n') f.write('** Node sets for loads\n') f.write('** written by {} function\n'.format(sys._getframe().f_code.co_name)) for fobj in self.force_objects: frc_obj = fobj['Object'] print frc_obj.Name f.write('*NSET,NSET=' + frc_obj.Name + '\n') NbrForceNodes = 0 for o, elem in frc_obj.References: fo = o.Shape.getElement(elem) n = [] if fo.ShapeType == 'Edge': print ' Line Load (edge load) on: ', elem n = self.mesh_object.FemMesh.getNodesByEdge(fo) elif fo.ShapeType == 'Vertex': print ' Point Load (vertex load) on: ', elem n = self.mesh_object.FemMesh.getNodesByVertex(fo) for i in n: f.write(str(i) + ',\n') NbrForceNodes = NbrForceNodes + 1 # NodeSum of mesh-nodes of ALL reference shapes from force_object # calculate node load if NbrForceNodes == 0: print 'No Line Loads or Point Loads in the model' else: fobj['NodeLoad'] = (frc_obj.Force) / NbrForceNodes # FIXME this method is incorrect, but we don't have anything else right now # Please refer to thread "CLOAD and DLOAD for the detailed description # http://forum.freecadweb.org/viewtopic.php?f=18&t=10692 f.write('** concentrated load [N] distributed on all mesh nodes of the given shapes\n') f.write('** ' + str(frc_obj.Force) + ' N / ' + str(NbrForceNodes) + ' Nodes = ' + str(fobj['NodeLoad']) + ' N on each node\n') if frc_obj.Force == 0: print ' Warning --> Force = 0' def write_materials(self, f): f.write('\n***********************************************************\n') f.write('** Materials\n') f.write('** written by {} function\n'.format(sys._getframe().f_code.co_name)) f.write('** Young\'s modulus unit is MPa = N/mm2\n') for m in self.material_objects: mat_obj = m['Object'] # get material properties YM = FreeCAD.Units.Quantity(mat_obj.Material['YoungsModulus']) YM_in_MPa = YM.getValueAs('MPa') PR = float(mat_obj.Material['PoissonRatio']) mat_obj_name = mat_obj.Name mat_name = mat_obj.Material['Name'][:80] # write material properties f.write('*MATERIAL, NAME=' + mat_name + '\n') f.write('*ELASTIC \n') f.write('{}, '.format(YM_in_MPa)) f.write('{0:.3f}\n'.format(PR)) # write element properties if len(self.material_objects) == 1: f.write('*SOLID SECTION, ELSET=' + mat_obj_name + ', MATERIAL=' + mat_name + '\n') else: if mat_obj_name == 'MechanicalMaterial': f.write('*SOLID SECTION, ELSET=' + mat_obj_name + ', MATERIAL=' + mat_name + '\n') def write_step_begin(self, f): f.write('\n***********************************************************\n') f.write('** One step is needed to calculate the mechanical analysis of FreeCAD\n') f.write('** loads are applied quasi-static, means without involving the time dimension\n') f.write('** written by {} function\n'.format(sys._getframe().f_code.co_name)) f.write('*STEP\n') f.write('*STATIC\n') def write_constraints_fixed(self, f): f.write('\n***********************************************************\n') f.write('** Constaints\n') f.write('** written by {} function\n'.format(sys._getframe().f_code.co_name)) for fixed_object in self.fixed_objects: fix_obj_name = fixed_object['Object'].Name f.write('*BOUNDARY\n') f.write(fix_obj_name + ',1\n') f.write(fix_obj_name + ',2\n') f.write(fix_obj_name + ',3\n\n') def write_constraints_force(self, f): def getTriangleArea(P1, P2, P3): vec1 = P2 - P1 vec2 = P3 - P1 vec3 = vec1.cross(vec2) return 0.5 * vec3.Length f.write('\n***********************************************************\n') f.write('** Node loads\n') f.write('** written by {} function\n'.format(sys._getframe().f_code.co_name)) for fobj in self.force_objects: frc_obj = fobj['Object'] if 'NodeLoad' in fobj: node_load = fobj['NodeLoad'] frc_obj_name = frc_obj.Name vec = frc_obj.DirectionVector f.write('*CLOAD\n') f.write('** force: ' + str(node_load) + ' N, direction: ' + str(vec) + '\n') v1 = "{:.13E}".format(vec.x * node_load) v2 = "{:.13E}".for
evazyin/Capstoneproject
stemcorpus.py
Python
agpl-3.0
1,104
0.021739
#version1 4/14/2014 for data lemma import codecs import sys sys.path.append("D:/uw course/capstone/nltk-3.0a3/")#necessary?? from nltk.stem.lancaster import LancasterStemmer st=LancasterStemmer() from nltk import word_tokenize #file = codecs.open('D:/uw course/capstone/mypersonality/status_b.csv',errors='ignore') file = codecs.open('C:/
Downloads/fb_status_a.csv',errors='ignore') file1 = open('D:/uw course/capstone/mypersonality/status_a_stem.txt','w') while 1: line = file.readline() if not line: break lineStr = str( line, encoding='latin-1' ) lineStr = lineStr.lower() #for my personality data only linelist = lineStr.split(",") lineStr1=','.join(linelist[2:])#in case the post part
is also split #print(lineStr1) tokens = word_tokenize(lineStr1) lineStr2 = ' '.join(st.stem(w) for w in tokens) #similar for stem usage #print(lineStr2) #print(lineStr.find('is very')) file1.write(str(lineStr2.encode('latin-1'))) file1.write('\n') del line del lineStr del lineStr1 del lineStr2 file.close() file1.close()
cnu/sorkandu
sorkandu/manage.py
Python
apache-2.0
251
0
#!/usr/bin/env p
ython import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sorkandu.settings") from django.core.management import
execute_from_command_line execute_from_command_line(sys.argv)
TieWei/nova
nova/tests/virt/hyperv/test_vhdutils.py
Python
apache-2.0
3,634
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 Cloudbase Solutions Srl # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import mock from nova import test from nova.virt.hyperv import constants from nova.virt.hyperv import vhdutils from nova.virt.hyperv import vmutils class VHDUtilsTestCase(test.NoDBTestCase): """Unit tests for the Hyper-V VHDUtils class.""" _FAKE_VHD_PATH = "C:\\fake_path.vhdx" _FAKE_FORMAT = 3 _FAKE_MAK_INTERNAL_SIZE = 1000 _FAKE_JOB_PATH = 'fake_job_path' _FAKE_RET_VAL = 0 def setUp(self): self._vhdutils = vhdutils.VHDUtils() self._vhdutils._conn = mock.MagicMock() self._vhdutils._vmutils = mock.MagicMock() super(VHDUtilsTestCase, self).setUp() def test_create_dynamic_vhd(self): self._vhdutils.get_vhd_info = mock.MagicMock( return_value={'Format': self._FAKE_FORMAT}) mock_img_svc = self._vhdutils._conn.Msvm_ImageManagementService()[0] mock_img_svc.CreateDynamicVirtualHardDisk.return_value = ( self._FAKE_JOB_PATH, self._FAKE_RET_VAL) self._vhdutils.create_dynamic_vhd(self._FAKE_VHD_PATH, self._FAKE_MAK_INTERNAL_SIZE, constants.DISK_FORMAT_VHD) mock_img_svc.CreateDynamicVirtualHardDisk.assert_called_once_with( Path=self._FAKE_VHD_PATH, MaxInternalSize=self._FAKE_MAK_INTERNAL_SIZE) def test_get_internal_vhd_size_by_file_size_fixed(self): vhdutil = vhdutils.VHDUtils() root_vhd_size = 1 * 1024 ** 3 vhdutil.get_vhd_info = mock.MagicMock() vhdutil.get_vhd_info.return_value = {'Type': constants.VHD_TYPE_FIXED} real_size = vhdutil.get_internal_vhd_size_by_file_size(None, root_vhd_size) expect
ed_vhd_size = 1 * 1024 ** 3 - 512 self.assertEqual(expected_vhd_size, real_size) def test_get_internal_vhd_size_by_file_s
ize_dynamic(self): vhdutil = vhdutils.VHDUtils() root_vhd_size = 20 * 1024 ** 3 vhdutil.get_vhd_info = mock.MagicMock() vhdutil.get_vhd_info.return_value = {'Type': constants.VHD_TYPE_DYNAMIC} vhdutil._get_vhd_dynamic_blk_size = mock.MagicMock() vhdutil._get_vhd_dynamic_blk_size.return_value = 2097152 real_size = vhdutil.get_internal_vhd_size_by_file_size(None, root_vhd_size) expected_vhd_size = 20 * 1024 ** 3 - 43008 self.assertEqual(expected_vhd_size, real_size) def test_get_internal_vhd_size_by_file_size_unsupported(self): vhdutil = vhdutils.VHDUtils() root_vhd_size = 20 * 1024 ** 3 vhdutil.get_vhd_info = mock.MagicMock() vhdutil.get_vhd_info.return_value = {'Type': 5} self.assertRaises(vmutils.HyperVException, vhdutil.get_internal_vhd_size_by_file_size, None, root_vhd_size)
justinslee/Wai-Not-Makahiki
makahiki/apps/widgets/group_prizes/views.py
Python
mit
632
0.011076
"""Prepares the views for point scoreboard widget.""" import datetime from ap
ps.managers.score_mgr import score_mgr from apps.managers.challenge_mgr import challenge_mgr from apps.managers.resource_mgr import resource_mgr from apps.widgets.resource_goal import resource_goal from apps.managers.team_mgr.models import Team, Group def supply(request, page_name): """Supply view_objects contents, which are the player name, team and points.""" """Supply the view_objects
content.""" _ = request group_winner = score_mgr.group_points_leader() return { 'group_winner':group_winner} #view_objects
hinshun/smile
please/utils.py
Python
mit
849
0.011779
from conf import paths import scipy.io import numpy as np def load_train(): """ Loads all training data.
""" tr_set = scipy.io.loadmat(file_name = paths.TR_SET) tr_identity = tr_set['tr_identity'] tr_labels = tr_set['tr_labels'] tr_images = tr_set['tr_images'] return tr_identity, tr_labels, tr_images def load_unlabeled(): """ Loads all unlabeled data.""" unlabeled_set = scipy.io.loadmat(file_name = paths.UNLABELED_SET) unlabeled_images = unlabeled_set['unlabeled_images'] return
unlabeled_images def load_test(): """ Loads training data. """ test_set = scipy.io.loadmat(file_name = paths.TEST_SET) test_images = test_set['public_test_images'] # hidden_set = scipy.io.loadmat(file_name = paths.HIDDEN_SET) # hidden_images = hidden_set['hidden_test_images'] return test_images
z-uo/pixeditor
dock_timeline.py
Python
gpl-3.0
24,676
0.005025
#!/usr/bin/env python3 #-*- coding: utf-8 -*- from PyQt4 import QtGui from PyQt4 import QtCore from dialogs import RenameLayerDialog from widget import Button, Viewer class LayersCanvas(QtGui.QWidget): """ Widget containing the canvas list """ def __init__(self, parent): QtGui.QWidget.__init__(self) self.parent = parent self.setFixedWidth(100) self.white = QtGui.QBrush(QtGui.QColor(255, 255, 255)) self.black = QtGui.QBrush(QtGui.QColor(0, 0, 0)) self.grey = QtGui.QBrush(QtGui.QColor(0, 0, 0, 30)) self.font = QtGui.QFont('SansSerif', 8, QtGui.QFont.Normal) self.layerH = 20 self.margeH = 22 self.visibleList = [] def paintEvent(self, ev=''): lH, mH = self.layerH, self.margeH p = QtGui.QPainter(self) p.setBrush(QtGui.QBrush(self.white)) p.setFont(self.font) self.visibleList = [] # background p.fillRect (0, 0, self.width(), self.height(), self.grey) p.fillRect (0, 0, self.width(), mH-2, self.white) p.drawLine (0, mH-2, self.width(), mH-2) p.drawPixmap(82, 2, QtGui.QPixmap("icons/layer_eye.png")) # curLayer p.fillRect(0, (self.parent.project.curLayer * lH) + mH-1, self.width(), lH, self.white) # layer's names y = mH for i, layer in enumerate(self.parent.project.timeline, 1): y += lH p.drawText(4, y-6, layer.name) p.drawLine (0, y-1, self.width(), y-1) rect = QtCore.QRect(82, y-19, 15, 15) self.visibleList.append(rect) p.drawRect(rect) if layer.visible: p.fillRect(84, y-17, 12, 12, self.black) def event(self, event): if (event.type() == QtCore.QEvent.MouseButtonPress and event.button()==QtCore.Qt.LeftButton): item = self.layerAt(event.y()) if item is not None: self.parent.project.curLayer = item if self.visibleList[item].contains(event.pos()): if self.parent.project.timeline[item].visible: self.parent.project.timeline[item].visible = False else: self.parent.project.timeline[item].visible = True self.parent.project.updateViewSign.emit() self.update() self.parent.project.updateViewSign.emit() elif (event.type() == QtCore.QEvent.MouseButtonDblClick and event.button()==QtCore.Qt.LeftButton): item = self.layerAt(event.y()) if item is not None: self.parent.renameLayer(item) self.update() return QtGui.QWidget.event(self, event) def layerAt(self, y): l = (y - 23) // 20 if 0 <= l < len(self.parent.project.timeline): return l class TimelineCanvas(QtGui.QWidget): """ widget containing the timeline """ def __init__(self, parent): QtGui.QWidget.__init__(self, parent) self.parent = parent self.grey = QtGui.QBrush(QtGui.QColor(0, 0, 0, 30)) self.white = QtGui.QBrush(QtGui.QColor(255, 255, 255)) self.whitea = QtGui.QBrush(QtGui.QColor(255, 255, 255, 127)) self.black = QtGui.QBrush(QtGui.QColor(0, 0, 0)) self.frameWidth = 13 self.frameHeight = 20 self.margeX = 1 self.margeY = 22 self.str
echFrame = False self.setMinimumSize(self.getMiniSize()[0], self.getMiniSize()[1])
def paintEvent(self, ev=''): fW, fH = self.frameWidth, self.frameHeight mX, mY = self.margeX, self.margeY p = QtGui.QPainter(self) fontLight = QtGui.QFont('SansSerif', 7, QtGui.QFont.Light) fontBold = QtGui.QFont('SansSerif', 8, QtGui.QFont.Normal) p.setBrush(self.whitea) # background p.fillRect (0, 0, self.width(), self.height(), self.grey) p.fillRect (0, 0, self.width(), 21, self.white) p.drawLine (0, 21, self.width(), 21) for j, i in enumerate(range(7, self.width(), fW), 1): p.drawLine (i-7, 19, i-7, 21) if j % 5 == 0: p.setFont(fontLight) metrics = p.fontMetrics() fw = metrics.width(str(j)) p.drawText(i-fw/2, 17, str(j)) if j % self.parent.project.fps == 0: p.setFont(fontBold) metrics = p.fontMetrics() s = str(j//self.parent.project.fps) fw = metrics.width(s) p.drawText(i-fw/2, 10, s) if self.parent.selection: l = self.parent.selection[0] f1, f2 = self.parent.selection[1], self.parent.selection[2] # remet a l'endroit if f2 < f1: f1, f2, = f2, f1 p.fillRect((f1 * fW) + mX, (l * fH) + mY, (f2 - f1 + 1) * fW, fH, self.white) # current frame p.drawLine(self.parent.project.curFrame*fW, 0, self.parent.project.curFrame*fW, self.height()) p.drawLine(self.parent.project.curFrame*fW + fW , 0, self.parent.project.curFrame*fW + fW , self.height()) framesRects = [] strechRects = [] self.strechBoxList = [] for y, layer in enumerate(self.parent.project.timeline): self.strechBoxList.append([]) for x, frame in enumerate(layer): if frame: w, h = 9, 17 s = x while s+1 < len(layer) and not layer[s+1]: s += 1 w += 13 nx = x * fW + mX + 1 ny = y * fH + mY + 1 framesRects.append(QtCore.QRect(nx, ny, w, h)) strechrect = QtCore.QRect(nx+w-9, ny+h-9, 9, 9) strechRects.append(strechrect) self.strechBoxList[y].append(strechrect) else: self.strechBoxList[y].append(False) p.drawRects(framesRects) p.setBrush(self.white) p.drawRects(strechRects) def getMiniSize(self): """ return the minimum size of the widget to display all frames and layers """ minH = (len(self.parent.project.timeline)*self.frameHeight) + self.margeY maxF = self.parent.project.timeline.frameCount() minW = (maxF * self.frameWidth) + self.margeX return (minW, minH) def event(self, event): if (event.type() == QtCore.QEvent.MouseButtonPress and event.button()==QtCore.Qt.LeftButton): frame = self.frameAt(event.x()) layer = self.layerAt(event.y()) if frame is not None and layer is not None: strech = self.isInStrechBox(event.pos()) if strech is not None: self.strechFrame = (strech[1], frame, False) self.parent.selection = False else: self.parent.selection = [layer, frame, frame] self.strechFrame = False else: self.strechFrame = False self.parent.selection = False if layer is not None: self.parent.project.curLayer = layer self.parent.layersCanvas.update() if frame is not None: self.parent.project.curFrame = frame self.update() if frame is not None or layer is not None: self.parent.project.updateViewSign.emit() return True elif (event.type() == QtCore.QEvent.MouseMove and event.buttons() == QtCore.Qt.LeftButton): frame = self.frameAt(event.x()) if frame is not None: if self.parent.selection: self.parent.selection[2] = frame self.strech(
usakhelo/FreeCAD
src/Mod/Fem/PyGui/_CommandFemMaterialMechanicalNonlinear.py
Python
lgpl-2.1
4,731
0.002959
# *************************************************************************** # * * # * Copyright (c) 2016 - Bernd Hahnebach <bernd@bimstatik.org> * # * * # * 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 * # * * # *************************************************************************** __title__ = "Command nonlinear mechanical material" __author__ = "Bernd Hahnebach" __url__ = "http://www.freecadweb.org" ## @package CommandFemMaterialMechanicalNonLinear # \ingroup FEM import FreeCAD from FemCommands import FemCommands import FreeCADGui import FemGui from PySide import QtCore class _CommandFemMaterialMechanicalNonlinear(FemCommands): "The FEM_MaterialMechanicalNonlinear command definition" def __init__(self): super(_CommandFemMaterialMechanicalNonlinear, self).__init__() self.resources = {'Pixmap': 'fem-material-nonlinear', 'MenuText': QtCore.QT_TRANSLATE_NOOP("FEM_MaterialMechanicalNonlinear", "Nonlinear mechanical material"), 'Accel': "C, W", 'ToolTip': QtCore.QT_TRANSLATE_NOOP("FEM_MaterialMechanicalNonlinear", "Creates a nonlinear mechanical material")} self.is_active = 'with_material' def Activated(self): sel = FreeCADGui.Selection.getSelection() if len(sel) == 1 and sel[0].isDerivedFrom("App::MaterialObjectPython"): lin_mat_obj = sel[0] # check if an nonlinear material exists which is based on the selected material already allow_nonlinear_material = True for o in FreeCAD.ActiveDocument.Objects: if
hasattr(o, "Proxy") and o.Proxy is not None and o.Proxy.Type == "FemMaterialMechanicalNonlinear" and o.LinearBaseMaterial == lin_mat_obj: FreeCAD.Console.PrintError(o.Name + ' is based on the selected
material: ' + lin_mat_obj.Name + '. Only one nonlinear object for each material allowed.\n') allow_nonlinear_material = False break if allow_nonlinear_material: string_lin_mat_obj = "App.ActiveDocument.getObject('" + lin_mat_obj.Name + "')" command_to_run = "FemGui.getActiveAnalysis().Member = FemGui.getActiveAnalysis().Member + [ObjectsFem.makeMaterialMechanicalNonlinear(" + string_lin_mat_obj + ")]" FreeCAD.ActiveDocument.openTransaction("Create FemMaterialMechanicalNonlinear") FreeCADGui.addModule("ObjectsFem") FreeCADGui.doCommand(command_to_run) # set the material nonlinear property of the solver to nonlinear if only one solver is available and if this solver is a CalculiX solver solver_object = None for m in FemGui.getActiveAnalysis().Member: if m.isDerivedFrom('Fem::FemSolverObjectPython'): if not solver_object: solver_object = m else: # we do not change the material nonlinear attribut if we have more than one solver solver_object = None break if solver_object and solver_object.SolverType == 'FemSolverCalculix': solver_object.MaterialNonlinearity = "nonlinear" FreeCADGui.addCommand('FEM_MaterialMechanicalNonlinear', _CommandFemMaterialMechanicalNonlinear())
shucommon/little-routine
python/python-crash-course/matplot/surface3d.py
Python
gpl-3.0
842
0
# This import registers the 3D projection
, but is otherwise unused. from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter import numpy as np fig = plt.figure() ax =
fig.gca(projection='3d') # Make data. X = np.arange(-5, 5, 0.25) Y = np.arange(-5, 5, 0.25) X, Y = np.meshgrid(X, Y) R = np.sqrt(X**2 + Y**2) Z = np.sin(R) # Plot the surface. surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm, linewidth=0, antialiased=False) # Customize the z axis. ax.set_zlim(-1.01, 1.01) ax.zaxis.set_major_locator(LinearLocator(10)) ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f')) # Add a color bar which maps values to colors. fig.colorbar(surf, shrink=0.5, aspect=5) plt.show()
tzpBingo/github-trending
codespace/python/tmp/example19.py
Python
mit
2,905
0.001334
""" 扩展性系统性能 - 垂直扩展 - 增加单节点处理能力 - 水平扩展 - 将单节点变成多节点(读写分离/分布式集群) 并发编程 - 加速程序执行 / 改善用户体验 耗时间的任务都尽可能独立的执行,不要阻塞代码的其他部分 - 多线程 1. 创建Thread对象指定target和args属性并通过start方法启动线程 2. 继承Thread类并重写run方法来定义线程执行的任务 3. 创建线程池对象ThreadPoolExecutor并通过submit来提交要执行的任务 第3种方式可以通过Future对象的result方法在将来获得线程的执行结果 也可以通过done方法判定线程是否执行结束 - 多进程 - 异步I/O """ import glob import os import time from concurrent.futures import ThreadPoolExecutor from threading import Thread from PIL import Image # class ThumbnailThread(Thread): # def __init__(self, infile): # self.infile = infile # super().__init__() # def run(self): # file, ext = os.path.splitext(self.infile) # filename = file[file.rfind('/') + 1:] # for size in (32, 64, 128): # outfile = f'thumbnails/{filename}_{size}_{size}.png' # image = Image.open(self.infile) # image.thumbnail((size, size)) # image.save(outfile, format='PNG') def gen_thumbnail(infile): file, ext = os.path.splitext(infile) filename = file[file.rfind('/') + 1:] for size in (32, 64, 128): outfile = f'thumbnails/{filename}_{size}_{size}.png' image = Image.open(infile) image.thumbnail((size, size)) image.save(outfile, format='PNG') # def main(): # start = time.time() # threads = [] # for infile in glob.glob('images/*'): # # t = Thread(target=gen_thumbnail, args=(infile, )) # t = ThumbnailThread(infile) # t.start() # threads.append(t) #
for t in threads: # t.join() # end = time.time() # print(f'耗时: {end - start}秒') def main(): pool = ThreadPoolExecutor(max_workers=30) futures = [] start = time.ti
me() for infile in glob.glob('images/*'): # submit方法是非阻塞式的方法 # 即便工作线程数已经用完,submit方法也会接受提交的任务 future = pool.submit(gen_thumbnail, infile) futures.append(future) for future in futures: # result方法是一个阻塞式的方法 如果线程还没有结束 # 暂时取不到线程的执行结果 代码就会在此处阻塞 future.result() end = time.time() print(f'耗时: {end - start}秒') # shutdown也是非阻塞式的方法 但是如果已经提交的任务还没有执行完 # 线程池是不会停止工作的 shutdown之后再提交任务就不会执行而且会产生异常 pool.shutdown() if __name__ == '__main__': main()
kumarrus/voltdb
lib/python/voltcli/voltdb.d/rejoin.py
Python
agpl-3.0
1,838
0.002176
# This file is part of VoltDB. # Copyright (C) 2008-2015 VoltDB Inc. # # This file contains original code and/or modifications of original code. # Any modifications made by VoltDB Inc. are licensed under the following # terms and conditions: # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHAL
L THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. @VOLT.Command( bundles = VOLT.ServerBundle('rejoin', needs_catalog=False, supports_live=True, de
fault_host=False, safemode_available=False, supports_daemon=True, supports_multiple_daemons=True, check_environment_config=True), description = 'Rejoin the current node to a VoltDB cluster.' ) def rejoin(runner): runner.go()
anhstudios/swganh
data/scripts/templates/object/draft_schematic/clothing/shared_clothing_boots_casual_12.py
Python
mit
462
0.047619
#### NOTICE: THIS F
ILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Intangible() result
.template = "object/draft_schematic/clothing/shared_clothing_boots_casual_12.iff" result.attribute_template_id = -1 result.stfName("string_id_table","") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
kubernetes-client/python
kubernetes/client/models/v1beta1_flow_schema_spec.py
Python
apache-2.0
8,042
0.000124
# coding: utf-8 """ Kubernetes No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: release-1.23 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from kubernetes.client.configuration import Configuration class V1beta1FlowSchemaSpec(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'distinguisher_method': 'V1beta1FlowDistinguisherMethod', 'matching_precedence': 'int', 'priority_level_configuration': 'V1beta1PriorityLevelConfigurationReference', 'rules': 'list[V1beta1PolicyRulesWithSubjects]' } attribute_map = { 'distinguisher_method': 'distinguisherMethod', 'matching_precedence': 'matchingPrecedence', 'priority_level_configuration': 'priorityLevelConfiguration', 'rules': 'rules' } def __init__(self, distinguisher_method=None, matching_precedence=None, priority_level_configuration=None, rules=None, local_vars_configuration=None): # noqa: E501 """V1beta1FlowSchemaSpec - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_
configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._distinguisher_method = None self._matching_precedence = None self._priority_level_configuration = None self._rules = None self.discriminator = None if distinguisher_meth
od is not None: self.distinguisher_method = distinguisher_method if matching_precedence is not None: self.matching_precedence = matching_precedence self.priority_level_configuration = priority_level_configuration if rules is not None: self.rules = rules @property def distinguisher_method(self): """Gets the distinguisher_method of this V1beta1FlowSchemaSpec. # noqa: E501 :return: The distinguisher_method of this V1beta1FlowSchemaSpec. # noqa: E501 :rtype: V1beta1FlowDistinguisherMethod """ return self._distinguisher_method @distinguisher_method.setter def distinguisher_method(self, distinguisher_method): """Sets the distinguisher_method of this V1beta1FlowSchemaSpec. :param distinguisher_method: The distinguisher_method of this V1beta1FlowSchemaSpec. # noqa: E501 :type: V1beta1FlowDistinguisherMethod """ self._distinguisher_method = distinguisher_method @property def matching_precedence(self): """Gets the matching_precedence of this V1beta1FlowSchemaSpec. # noqa: E501 `matchingPrecedence` is used to choose among the FlowSchemas that match a given request. The chosen FlowSchema is among those with the numerically lowest (which we take to be logically highest) MatchingPrecedence. Each MatchingPrecedence value must be ranged in [1,10000]. Note that if the precedence is not specified, it will be set to 1000 as default. # noqa: E501 :return: The matching_precedence of this V1beta1FlowSchemaSpec. # noqa: E501 :rtype: int """ return self._matching_precedence @matching_precedence.setter def matching_precedence(self, matching_precedence): """Sets the matching_precedence of this V1beta1FlowSchemaSpec. `matchingPrecedence` is used to choose among the FlowSchemas that match a given request. The chosen FlowSchema is among those with the numerically lowest (which we take to be logically highest) MatchingPrecedence. Each MatchingPrecedence value must be ranged in [1,10000]. Note that if the precedence is not specified, it will be set to 1000 as default. # noqa: E501 :param matching_precedence: The matching_precedence of this V1beta1FlowSchemaSpec. # noqa: E501 :type: int """ self._matching_precedence = matching_precedence @property def priority_level_configuration(self): """Gets the priority_level_configuration of this V1beta1FlowSchemaSpec. # noqa: E501 :return: The priority_level_configuration of this V1beta1FlowSchemaSpec. # noqa: E501 :rtype: V1beta1PriorityLevelConfigurationReference """ return self._priority_level_configuration @priority_level_configuration.setter def priority_level_configuration(self, priority_level_configuration): """Sets the priority_level_configuration of this V1beta1FlowSchemaSpec. :param priority_level_configuration: The priority_level_configuration of this V1beta1FlowSchemaSpec. # noqa: E501 :type: V1beta1PriorityLevelConfigurationReference """ if self.local_vars_configuration.client_side_validation and priority_level_configuration is None: # noqa: E501 raise ValueError("Invalid value for `priority_level_configuration`, must not be `None`") # noqa: E501 self._priority_level_configuration = priority_level_configuration @property def rules(self): """Gets the rules of this V1beta1FlowSchemaSpec. # noqa: E501 `rules` describes which requests will match this flow schema. This FlowSchema matches a request if and only if at least one member of rules matches the request. if it is an empty slice, there will be no requests matching the FlowSchema. # noqa: E501 :return: The rules of this V1beta1FlowSchemaSpec. # noqa: E501 :rtype: list[V1beta1PolicyRulesWithSubjects] """ return self._rules @rules.setter def rules(self, rules): """Sets the rules of this V1beta1FlowSchemaSpec. `rules` describes which requests will match this flow schema. This FlowSchema matches a request if and only if at least one member of rules matches the request. if it is an empty slice, there will be no requests matching the FlowSchema. # noqa: E501 :param rules: The rules of this V1beta1FlowSchemaSpec. # noqa: E501 :type: list[V1beta1PolicyRulesWithSubjects] """ self._rules = rules def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, V1beta1FlowSchemaSpec): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, V1beta1FlowSchemaSpec): return True return self.to_dict() != other.to_dict()
shaggytwodope/rtv
rtv/submission_page.py
Python
mit
11,574
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals import time import curses from . import docs from .content import SubmissionContent, SubredditContent from .page import Page, PageController, logged_in from .objects import Navigator, Color, Command from .exceptions import TemporaryFileError class SubmissionController(PageController): character_map = {} class SubmissionPage(Page): FOOTER = docs.FOOTER_SUBMISSION def __init__(self, reddit, term, config, oauth, url=None, submission=None): super(SubmissionPage, self).__init__(reddit, term, config, oauth) self.controller = SubmissionController(self, keymap=config.keymap) if url: self.content = SubmissionContent.from_url( reddit, url, term.loader, max_comment_cols=config['max_comment_cols']) else: self.content = SubmissionContent( submission, term.loader, max_comment_cols=config['max_comment_cols']) # Start at the submission post, which is indexed as -1 self.nav = Navigator(self.content.get, page_index=-1) self.selected_subreddit = None @SubmissionController.register(Command('SUBMISSION_TOGGLE_COMMENT')) def toggle_comment(self): "Toggle the selected comment tree between visible and hidden" current_index = self.nav.absolute_index self.content.toggle(current_index) # This logic handles a display edge case after a comment toggle. We # want to make sure that when we re-draw the page, the cursor stays at # its current absolute position on the screen. In order to do this, # apply a fixed offset if, while inverted, we either try to hide the # bottom comment or toggle any of the middle comments. if self.nav.inverted: data = self.content.get(current_index) if data['hidden'] or self.nav.cursor_index != 0: window = self._subwindows[-1][0] n_rows, _ = window.getmaxyx() self.nav.flip(len(self._subwindows) - 1) self.nav.top_item_height = n_rows @SubmissionController.register(Command('SUBMISSION_EXIT')) def exit_submission(self): "Close the submission and return to the subreddit page" self.active = False @SubmissionController.register(Command('REFRESH')) def refresh_content(self, order=None, name=None): "Re-download comments and reset the page index" order = order or self.content.order url = name or self.content.name with self.term.loader('Refreshing page'): self.content = SubmissionContent.from_url( self.reddit, url, self.term.loader, order=order, max_comment_cols=self.config['max_comment_cols']) if not self.term.loader.exception: self.nav = Navigator(self.content.get, page_index=-1) @SubmissionController.register(Command('PROMPT')) def prompt_subreddit(self): "Open a prompt to navigate to a different subreddit" name = self.term.prompt_input('Enter page: /') if name is not None: with self.term.loader('Loading page'): content = SubredditContent.from_name( self.reddit, name, self.term.loader) if not self.term.loader.exception: self.selected_subreddit = content self.active = False @SubmissionController.register(Command('SUBMISSION_OPEN_IN_BROWSER')) def open_link(self): "Open the selected item with the webbrowser" data = self.get_selected_item() url = data.get('permalink') if url: self.term.open_browser(url) else: self.term.flash() @SubmissionController.register(Command('SUBMISSION_OPEN_IN_PAGER')) def open_p
ager(self): "Open the selected item with the system's pager" data = self.get_selected_item() if data['type'] == 'Submission': text = '\n\n'.join((data['permalink'], da
ta['text'])) self.term.open_pager(text) elif data['type'] == 'Comment': text = '\n\n'.join((data['permalink'], data['body'])) self.term.open_pager(text) else: self.term.flash() @SubmissionController.register(Command('SUBMISSION_POST')) @logged_in def add_comment(self): """ Submit a reply to the selected item. Selected item: Submission - add a top level comment Comment - add a comment reply """ data = self.get_selected_item() if data['type'] == 'Submission': body = data['text'] reply = data['object'].add_comment elif data['type'] == 'Comment': body = data['body'] reply = data['object'].reply else: self.term.flash() return # Construct the text that will be displayed in the editor file. # The post body will be commented out and added for reference lines = ['# |' + line for line in body.split('\n')] content = '\n'.join(lines) comment_info = docs.COMMENT_FILE.format( author=data['author'], type=data['type'].lower(), content=content) with self.term.open_editor(comment_info) as comment: if not comment: self.term.show_notification('Canceled') return with self.term.loader('Posting', delay=0): reply(comment) # Give reddit time to process the submission time.sleep(2.0) if self.term.loader.exception is None: self.refresh_content() else: raise TemporaryFileError() @SubmissionController.register(Command('DELETE')) @logged_in def delete_comment(self): "Delete the selected comment" if self.get_selected_item()['type'] == 'Comment': self.delete_item() else: self.term.flash() @SubmissionController.register(Command('SUBMISSION_OPEN_IN_URLVIEWER')) def comment_urlview(self): data = self.get_selected_item() comment = data.get('body') or data.get('text') or data.get('url_full') if comment: self.term.open_urlview(comment) else: self.term.flash() def _draw_item(self, win, data, inverted): if data['type'] == 'MoreComments': return self._draw_more_comments(win, data) elif data['type'] == 'HiddenComment': return self._draw_more_comments(win, data) elif data['type'] == 'Comment': return self._draw_comment(win, data, inverted) else: return self._draw_submission(win, data) def _draw_comment(self, win, data, inverted): n_rows, n_cols = win.getmaxyx() n_cols -= 1 # Handle the case where the window is not large enough to fit the text. valid_rows = range(0, n_rows) offset = 0 if not inverted else -(data['n_rows'] - n_rows) # If there isn't enough space to fit the comment body on the screen, # replace the last line with a notification. split_body = data['split_body'] if data['n_rows'] > n_rows: # Only when there is a single comment on the page and not inverted if not inverted and len(self._subwindows) == 0: cutoff = data['n_rows'] - n_rows + 1 split_body = split_body[:-cutoff] split_body.append('(Not enough space to display)') row = offset if row in valid_rows: attr = curses.A_BOLD attr |= (Color.BLUE if not data['is_author'] else Color.GREEN) self.term.add_line(win, '{author} '.format(**data), row, 1, attr) if data['flair']: attr = curses.A_BOLD | Color.YELLOW self.term.add_line(win, '{flair} '.format(**data), attr=attr) text, attr = self.term.get_arrow(data['likes']) self.term.add_line(win
formencode/formencode
src/formencode/htmlfill_schemabuilder.py
Python
mit
3,632
0.000275
""" Extension to ``htmlfill`` that can parse out schema-defining statements. You can either pass ``SchemaBuilder`` to ``htmlfill.render`` (the ``listen`` argument), or call ``parse_schema`` to just parse out a ``Schema`` object. """ from __future__ import absolute_import from . import validators from . import schema from . import compound from . import htmlfill __all__ = ['parse_schema', 'SchemaBuilder'] def parse_schema(form): """ Given an HTML form, parse out the schema defined in it and return that schema. """ listener = SchemaBuilder() p = htmlfill.FillingParser( defaults={}, listener=listener) p.feed(form) p.close() return listener.schema() default_validators = dict( [(name.lower(), getattr(validators, name)) for name in dir(validators)]) def get_messages(cls, message): if not message: return {} else: return dict([(k, message) for k in cls._messages]) def to_bool(value): value = value.strip().lower() if value in ('true', 't', 'yes', 'y', 'on', '1'): return True elif value in ('false', 'f', 'no', 'n', 'off', '0'): return False else: raise ValueError("Not a boolean value: %r (use 'true'/'false')") def force_list(v): """ Force single items into a list. This is useful for checkboxes. """ if isinstance(v, list): return v elif isinstance(v, tuple): return list(v) else: return [v] class SchemaBuilder(object): def __init__(self, validators=default_validators): self.validators = validators self._schema = None def reset(self): self._schema = schema.Schema() def schema(self): return self._schema def listen_input(self, parser, tag, attrs): get_attr = parser.get_attr name = get_attr(attrs, 'name') if not
name: # @@: should warn if you try to validate unnamed fields return v = compound.All(validators.Identity()) add_to_end = None # for checkboxes, we must set if_missing = False if tag.lower() == "input": type_attr = get_attr(attrs, "type").lower().strip() if type_attr == "submit": v.validators.append(validators.Bool())
elif type_attr == "checkbox": v.validators.append(validators.Wrapper(to_python=force_list)) elif type_attr == "file": add_to_end = validators.FieldStorageUploadConverter() message = get_attr(attrs, 'form:message') required = to_bool(get_attr(attrs, 'form:required', 'false')) if required: v.validators.append( validators.NotEmpty( messages=get_messages(validators.NotEmpty, message))) else: v.validators[0].if_missing = False if add_to_end: v.validators.append(add_to_end) v_type = get_attr(attrs, 'form:validate', None) if v_type: pos = v_type.find(':') if pos != -1: # @@: should parse args args = (v_type[pos + 1:],) v_type = v_type[:pos] else: args = () v_type = v_type.lower() v_class = self.validators.get(v_type) if not v_class: raise ValueError("Invalid validation type: %r" % v_type) kw_args = {'messages': get_messages(v_class, message)} v_inst = v_class( *args, **kw_args) v.validators.append(v_inst) self._schema.add_field(name, v)
jawilson/home-assistant
homeassistant/components/ezviz/camera.py
Python
apache-2.0
11,868
0.000927
"""Support ezviz camera devices.""" from __future__ import annotations import logging from pyezviz.exceptions import HTTPError, InvalidHost, PyEzvizError import voluptuous as vol from homeassistant.components import ffmpeg from homeassistant.components.camera import PLATFORM_SCHEMA, SUPPORT_STREAM, Camera from homeassistant.components.ffmpeg import DATA_FFMPEG from homeassistant.config_entries import ( SOURCE_DISCOVERY, SOURCE_IGNORE, SOURCE_IMPORT, ConfigEntry, ) from homeassistant.const import CONF_IP_ADDRESS, CONF_PASSWORD, CONF_USERNAME from homeassistant.core import HomeAssistant from homeassistant.helpers import config_validation as cv, entity_platform from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from .const import ( ATTR_DIRECTION, ATTR_ENABLE, ATTR_LEVEL, ATTR_SERIAL, ATTR_SPEED, ATTR_TYPE, CONF_CAMERAS, CONF_FFMPEG_ARGUMENTS, DATA_COORDINATOR, DEFAULT_CAMERA_USERNAME, DEFAULT_FFMPEG_ARGUMENTS, DEFAULT_RTSP_PORT, DIR_DOWN, DIR_LEFT, DIR_RIGHT, DIR_UP, DOMAIN, SERVICE_ALARM_SOUND, SERVICE_ALARM_TRIGER, SERVICE_DETECTION_SENSITIVITY, SERVICE_PTZ, SERVICE_WAKE_DEVICE, ) from .coordinator import EzvizDataUpdateCoordinator from .entity import EzvizEntity CAMERA_SCHEMA = vol.Schema( {vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string} ) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_CAMERAS, default={}): {cv.string: CAMERA_SCHEMA}, } ) _LOGGER = logging.getLogger(__name__) async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: entity_platform.AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up a Ezviz IP Camera from platform config.""" _LOGGER.warning( "Loading ezviz via platform config is deprecated, it will be automatically imported. Please remove it afterwards" ) # Check if entry config exists and skips import if it does. if hass.config_entries.async_entries(DOMAIN): return # Check if
importing camera account. if CONF_CAMERAS in config: cameras_conf = config[CONF_CAMERAS] for serial, camera in cameras
_conf.items(): hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ ATTR_SERIAL: serial, CONF_USERNAME: camera[CONF_USERNAME], CONF_PASSWORD: camera[CONF_PASSWORD], }, ) ) # Check if importing main ezviz cloud account. hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data=config, ) ) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: entity_platform.AddEntitiesCallback, ) -> None: """Set up Ezviz cameras based on a config entry.""" coordinator: EzvizDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id][ DATA_COORDINATOR ] camera_entities = [] for camera, value in coordinator.data.items(): camera_rtsp_entry = [ item for item in hass.config_entries.async_entries(DOMAIN) if item.unique_id == camera and item.source != SOURCE_IGNORE ] # There seem to be a bug related to localRtspPort in Ezviz API. local_rtsp_port = ( value["local_rtsp_port"] if value["local_rtsp_port"] != 0 else DEFAULT_RTSP_PORT ) if camera_rtsp_entry: ffmpeg_arguments = camera_rtsp_entry[0].options[CONF_FFMPEG_ARGUMENTS] camera_username = camera_rtsp_entry[0].data[CONF_USERNAME] camera_password = camera_rtsp_entry[0].data[CONF_PASSWORD] camera_rtsp_stream = f"rtsp://{camera_username}:{camera_password}@{value['local_ip']}:{local_rtsp_port}{ffmpeg_arguments}" _LOGGER.debug( "Configuring Camera %s with ip: %s rtsp port: %s ffmpeg arguments: %s", camera, value["local_ip"], local_rtsp_port, ffmpeg_arguments, ) else: hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_DISCOVERY}, data={ ATTR_SERIAL: camera, CONF_IP_ADDRESS: value["local_ip"], }, ) ) _LOGGER.warning( "Found camera with serial %s without configuration. Please go to integration to complete setup", camera, ) ffmpeg_arguments = DEFAULT_FFMPEG_ARGUMENTS camera_username = DEFAULT_CAMERA_USERNAME camera_password = None camera_rtsp_stream = "" camera_entities.append( EzvizCamera( hass, coordinator, camera, camera_username, camera_password, camera_rtsp_stream, local_rtsp_port, ffmpeg_arguments, ) ) async_add_entities(camera_entities) platform = entity_platform.async_get_current_platform() platform.async_register_entity_service( SERVICE_PTZ, { vol.Required(ATTR_DIRECTION): vol.In( [DIR_UP, DIR_DOWN, DIR_LEFT, DIR_RIGHT] ), vol.Required(ATTR_SPEED): cv.positive_int, }, "perform_ptz", ) platform.async_register_entity_service( SERVICE_ALARM_TRIGER, { vol.Required(ATTR_ENABLE): cv.positive_int, }, "perform_sound_alarm", ) platform.async_register_entity_service( SERVICE_WAKE_DEVICE, {}, "perform_wake_device" ) platform.async_register_entity_service( SERVICE_ALARM_SOUND, {vol.Required(ATTR_LEVEL): cv.positive_int}, "perform_alarm_sound", ) platform.async_register_entity_service( SERVICE_DETECTION_SENSITIVITY, { vol.Required(ATTR_LEVEL): cv.positive_int, vol.Required(ATTR_TYPE): cv.positive_int, }, "perform_set_alarm_detection_sensibility", ) class EzvizCamera(EzvizEntity, Camera): """An implementation of a Ezviz security camera.""" coordinator: EzvizDataUpdateCoordinator def __init__( self, hass: HomeAssistant, coordinator: EzvizDataUpdateCoordinator, serial: str, camera_username: str, camera_password: str | None, camera_rtsp_stream: str | None, local_rtsp_port: int, ffmpeg_arguments: str | None, ) -> None: """Initialize a Ezviz security camera.""" super().__init__(coordinator, serial) Camera.__init__(self) self._username = camera_username self._password = camera_password self._rtsp_stream = camera_rtsp_stream self._local_rtsp_port = local_rtsp_port self._ffmpeg_arguments = ffmpeg_arguments self._ffmpeg = hass.data[DATA_FFMPEG] self._attr_unique_id = serial self._attr_name = self.data["name"] @property def available(self) -> bool: """Return True if entity is available.""" return self.data["status"] != 2 @property def supported_features(self) -> int: """Return supported features.""" if self._password: return SUPPORT_STREAM return 0 @property def is_on(self) -> bool: """Return true if on.""" return bool(self.data["status"]) @property def is_recording(self) -> bool: """Return true if
mmerce/python
bigml/tests/create_script_steps.py
Python
apache-2.0
3,531
0.002266
# -*- coding: utf-8 -*- # # Copyright 2015-2020 BigML # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import time import json import os from datetime import datetime from .world import world, logged_wait, res_filename from nose.tools import eq_, assert_less from bigml.api import HTTP_CREATED from bigml.api
import HTTP_ACCEPTED from bigml.api import FINISHED from bigml.api import FAULTY from bigml.api import get_status from bigml.util import is_url
from .read_script_steps import i_get_the_script #@step(r'the script code is "(.*)" and the value of "(.*)" is "(.*)"') def the_script_code_and_attributes(step, source_code, param, param_value): res_param_value = world.script[param] eq_(res_param_value, param_value, ("The script %s is %s and the expected %s is %s" % (param, param_value, param, param_value))) #@step(r'I create a whizzml script from a excerpt of code "(.*)"$') def i_create_a_script(step, source_code): resource = world.api.create_script(source_code, {"project": world.project_id}) world.status = resource['code'] eq_(world.status, HTTP_CREATED) world.location = resource['location'] world.script = resource['object'] world.scripts.append(resource['resource']) #@step(r'I create a whizzml script from file "(.*)"$') def i_create_a_script_from_file_or_url(step, source_code): if not is_url(source_code): source_code = res_filename(source_code) resource = world.api.create_script(source_code, {"project": world.project_id}) world.status = resource['code'] eq_(world.status, HTTP_CREATED) world.location = resource['location'] world.script = resource['object'] world.scripts.append(resource['resource']) #@step(r'I update the script with "(.*)", "(.*)"$') def i_update_a_script(step, param, param_value): resource = world.api.update_script(world.script['resource'], {param: param_value}) world.status = resource['code'] eq_(world.status, HTTP_ACCEPTED) world.location = resource['location'] world.script = resource['object'] #@step(r'I wait until the script status code is either (\d) or (-\d) less than (\d+)') def wait_until_script_status_code_is(step, code1, code2, secs): start = datetime.utcnow() delta = int(secs) * world.delta script_id = world.script['resource'] i_get_the_script(step, script_id) status = get_status(world.script) count = 0 while (status['code'] != int(code1) and status['code'] != int(code2)): count += 1 logged_wait(start, delta, count, "script") assert_less((datetime.utcnow() - start).seconds, delta) i_get_the_script(step, script_id) status = get_status(world.script) eq_(status['code'], int(code1)) #@step(r'I wait until the script is ready less than (\d+)') def the_script_is_finished(step, secs): wait_until_script_status_code_is(step, FINISHED, FAULTY, secs)
lukas-hetzenecker/home-assistant
tests/components/zwave_js/test_siren.py
Python
apache-2.0
6,133
0
"""Test the Z-Wave JS siren platform.""" from zwave_js_server.event import Event from homeassistant.components.siren import ATTR_TONE, ATTR_VOLUME_LEVEL from homeassistant.components.siren.const import ATTR_AVAILABLE_TONES from homeassistant.const import STATE_OFF, STATE_ON SIREN_ENTITY = "siren.indoor_siren_6_2" TONE_ID_VALUE_ID = { "endpoint": 2, "commandClass": 121, "commandClassName": "Sound Switch", "property": "toneId", "propertyName": "toneId", "ccVersion": 1, "metadata": { "type": "number", "readable": True, "writeable": True, "label": "Play Tone", "min": 0, "max": 30, "states": { "0": "off", "1": "01DING~1 (5 sec)", "2": "02DING~1 (9 sec)", "3": "03TRAD~1 (11 sec)", "4": "04ELEC~1 (2 sec)", "5": "05WEST~1 (13 sec)", "6": "06CHIM~1 (7 sec)", "7": "07CUCK~1 (31 sec)", "8": "08TRAD~1 (6 sec)", "9": "09SMOK~1 (11 sec)", "10": "10SMOK~1 (6 sec)", "11": "11FIRE~1 (35 sec)", "12": "12COSE~1 (5 sec)", "13": "13KLAX~1 (38 sec)", "14": "14DEEP~1 (41 sec)", "15": "15WARN~1 (37 sec)", "16": "16TORN~1 (46 sec)", "17": "17ALAR~1 (35 sec)", "18": "18DEEP~1 (62 sec)", "19": "19ALAR~1 (15 sec)", "20": "20ALAR~1 (7 sec)", "21": "21DIGI~1 (8 sec)", "22": "22ALER~1 (64 sec)", "23": "23SHIP~1 (4 sec)", "25": "25CHRI~1 (4 sec)", "26": "26GONG~1 (12 sec)", "27": "27SING~1 (1 sec)", "28": "28TONA~1 (5 sec)", "29": "29UPWA~1 (2 sec)", "30": "30DOOR~1 (27 sec)", "255": "default", }, "valueChangeOptions": ["volume"], }, } async def test_siren(hass, client, aeotec_zw164_siren, integration): """Test the siren entity.""" node = aeotec_zw164_siren state = hass.states.get(SIREN_ENTITY) assert state assert state.state == STATE_OFF assert state.attributes.get(ATTR_AVAILABLE_TONES) == { 0: "off", 1: "01DING~1 (5 sec)", 2: "02DING~1 (9 sec)", 3: "03TRAD~1 (11 sec)", 4: "04ELEC~1 (2 sec)", 5: "05WEST~1 (13 sec)", 6: "06CHIM~1 (7 sec)", 7: "07CUCK~1 (31 sec)", 8: "08TRAD~1 (6 sec)", 9: "09SMOK~1 (11 sec)", 10: "10SMOK~1 (6 sec)", 11: "11FIRE~1 (35 sec)", 12: "12COSE~1 (5 sec)", 13: "13KLAX~1 (38 sec)", 14: "14DEEP~1 (41 sec)", 15: "15WARN~1 (37 sec)", 16: "16TORN~1 (46 sec)", 17: "17ALAR~1 (35 sec)", 18: "18DEEP~1 (62 sec)", 19: "19ALAR~1 (15 sec)", 20: "20ALAR~1 (7 sec)", 21: "21DIGI~1 (8 sec)", 22: "22ALER~1 (64 sec)", 23: "23SHIP~1 (4 sec)", 25: "25CHRI~1 (4 sec)", 26: "26GONG~1 (12 sec)", 27: "27SING~1 (1 sec)", 28: "28TONA~1 (5 sec)", 29: "29UPWA~1 (2 sec)", 30: "30DOOR~1 (27 sec)", 255: "default", } # Test turn on with default await hass.services.async_call( "siren", "turn_on", {"entity_id": SIREN_ENTITY}, blocking=True, ) assert len(client.async_send_command.call_args_list) == 1 args = client.async_send_command.call_args[0][0] assert args["command"] == "node.set_value" assert args["nodeId"] == node.node_id assert args["valueId"] == TONE_ID_VALUE_ID assert args["value"] == 255 client.async_send_command.reset_mock() # Test turn on with specific tone name and volume level await hass.services.async_call( "siren", "turn_on", { "entity_id": SIREN_ENTITY, ATTR_TONE: "01DING~1 (5 sec)", ATTR_VOLUME_LEVEL: 0.5, }, blocking=True, ) assert len(client.async_send_command.call_args_list) == 1 args = client.async_send_comman
d.call_args[0][0] assert args["command"] == "node.set_value" assert args["nodeId"] == node.node_id assert args["valueId"] == TONE_ID_VALUE_ID assert args["value
"] == 1 assert args["options"] == {"volume": 50} client.async_send_command.reset_mock() # Test turn on with specific tone ID and volume level await hass.services.async_call( "siren", "turn_on", { "entity_id": SIREN_ENTITY, ATTR_TONE: 1, ATTR_VOLUME_LEVEL: 0.5, }, blocking=True, ) assert len(client.async_send_command.call_args_list) == 1 args = client.async_send_command.call_args[0][0] assert args["command"] == "node.set_value" assert args["nodeId"] == node.node_id assert args["valueId"] == TONE_ID_VALUE_ID assert args["value"] == 1 assert args["options"] == {"volume": 50} client.async_send_command.reset_mock() # Test turn off await hass.services.async_call( "siren", "turn_off", {"entity_id": SIREN_ENTITY}, blocking=True, ) assert len(client.async_send_command.call_args_list) == 1 args = client.async_send_command.call_args[0][0] assert args["command"] == "node.set_value" assert args["nodeId"] == node.node_id assert args["valueId"] == TONE_ID_VALUE_ID assert args["value"] == 0 client.async_send_command.reset_mock() # Test value update from value updated event event = Event( type="value updated", data={ "source": "node", "event": "value updated", "nodeId": node.node_id, "args": { "commandClassName": "Sound Switch", "commandClass": 121, "endpoint": 2, "property": "toneId", "newValue": 255, "prevValue": 0, "propertyName": "toneId", }, }, ) node.receive_event(event) state = hass.states.get(SIREN_ENTITY) assert state.state == STATE_ON
smartczm/python-learn
Old-day01-10/s13-day5/get/day5/Atm/src/admin.py
Python
gpl-2.0
2,982
0.002172
#!/usr/bin/env python # -*- coding:utf-8 -*- import os import json from lib import commons from config import settings CURRENT_USER_INFO = {'is_authenticated': False, 'current_user': None} def init(): """ 初始化管理员信息 :return: """ dic = {'username': 'admin', 'password': commons.md5('123')} json.dump(dic, open(os.path.join(settings.ADMIN_DIR_FOLDER, dic['username']), 'w')) def create_user(): """ 创建账户 :return: """ card_num = input("Please input card_num: ") card_name = input("Please input card name: ") # 创建目录,6222020409028810 # record文件夹 # # basic_info.json文件 os.makedirs(os.path.join(settings.USER_DIR_FOLDER, card_num, 'record')) base_info = {'username': card_name, 'card': card_num, 'password': commons.md5('8888'), "credit": 15000, # 信用卡额度 "balance": 15000, # 本月可用额度 "saving": 0, # 储蓄金额 "enroll_date": "2016-01-01", 'expire_date': '2021-01-01', 'status': 0, # 0 = normal, 1 = locked, 2 = disabled "debt": [], # 欠款记录,如:[{'date': "2015_4_10", "total_debt":80000, "balance_debt": 5000},{'date': "2015_5_10", "total":80000, "balance": 5000} ] } json.dump(base_info, open(os.path.join(settings.USER_DIR_FOLDER, card_num, "basic_info.json"), 'w')) def remove_user(): """ 移除账户 :return: """ pass def locked_user(): """ 冻结账户 :return: """ pass def search(): """ 搜索账户 :return: """ pass def main(): menu = """ 1、创建账户; 2、删除账户; 3、冻结账户; 4、查询账户 """ print(menu) menu_dic = { '1': create_user, '2': remove_user, '3': locked_user, '4': search, } while True: user_option = input(">>:").strip() if user_option in menu_dic: menu_dic[user_option]() else: print("选项不存在") def login(): """ 用户登陆 :return: """ while True: username = input('请输入用户名:') password = input('请输入密码:') if not os.path.exists(os.path.join(settings.ADMIN_DIR_FOLDER, username)): print('用户名不存在') else: user_dict = json.load(ope
n(os.path.joi
n(settings.ADMIN_DIR_FOLDER, username), 'r')) if username == user_dict['username'] and commons.md5(password) == user_dict['password']: CURRENT_USER_INFO['is_authenticated'] = True CURRENT_USER_INFO['current_user'] = username return True else: print('密码错误') def run(): ret = login() if ret: main()
cloew/KaoJson
kao_json/conversion_context.py
Python
mit
559
0.008945
from
.providers import ProviderContext from kao_decorators import proxy_for @proxy_for('config', ['newConverter']) class ConversionContext: """ Represents the Configuration and Keyword Arguments provided to a Converter """ def __init__(self, config, **kwargs): """ Initialize with the config and keyword arguments """ self.config = config self.kwargs = kwargs def providerContext(self, name, obj): """
Return a Provider Context """ return ProviderContext(name, obj, self.kwargs)
clusterpy/clusterpy
clusterpy/core/data/createVariable.py
Python
bsd-3-clause
2,144
0.007933
# encoding: latin1 """createVariable """ __author__ = "Juan C. Duque, Alejandro Betancourt, Juan Sebastian Marín" __credits__ = "Copyright (c) 2010-11 Juan C. Duque" __license__ = "New BSD License" __version__ = "1.0.0" __maintainer__ = "RiSE Group" __email__ = "contacto@rise-group.org" __all__ = ['fieldOperation'] import re def fieldOperation(function, Y, fieldnames): """ This method receives a string which contains a function or formula written by the user. That function has operations between the variables of Y (a data dictionary) which names are contained in fieldnames (a list), the function is applied to the corresponding values in each element of Y. The return value is a list containing the results of the function. :param function: funct
ion defined by the user, written like a py
thon operation :type function: string :rtype: list (Y dictionary with the results) """ variables = [] positions = [] auxiliar1 = [] count = 0 results = [] newfunc = '' for i in fieldnames[0:]: if re.search(i,function): if not (function[function.index(i) - 2: function.index(i)].isalpha()): variables.append(i) positions.append(fieldnames.index(i)) for j in Y: auxiliar1 = [] count = 0 newfunc = function for k in positions: auxiliar1.append(Y[j][k]) for l in variables: if len(re.findall(l,newfunc)) == 1: newfunc = re.compile(l).sub(str(auxiliar1[variables.index(l)]), newfunc) else: if newfunc.index(re.findall(l, newfunc)[0]) != newfunc.index(re.findall('(\D)' + l, newfunc)[1]): newfunc = re.compile('(\W)-[+,-]' + l).sub(str(auxiliar1[variables.index(l)]), newfunc) for l in variables: newfunc = re.compile(l).sub(str(auxiliar1[variables.index(l)]), newfunc) try: n = eval(newfunc) except ZeroDivisionError: raise ZeroDivisionError("Division by zero was detected") results.append(n) return results
RedHatQE/python-moncov
moncov/monkey.py
Python
gpl-3.0
2,050
0.003902
'''monkey patch hacks''' import conf import os def _iter_filename_over_mountpoints(self, filename): '''iterate absolute filename over self.mountpoints and self.root''' for mountpoint in self.mountpoints + [self.root]: _drivename, _filename = os.path.splitdrive(filename) _filename = _filename.lstrip(os.path.sep) yield os.path.join(_drivename + mountpoint, _filename) def patch_coveragepy(dbhost=conf.DBHOST, dbport=conf.DBPORT, dbname=conf.DBNAME, root=os.path.sep, mountpoints=[]): '''monkey patch coveragepy in order to fetch stats from our data store''' from coverage.data import CoverageData CoverageData.root = root CoverageData.mountpoints = mountpoints CoverageData.iter_filename_over_mountpoints = _iter_filename_over_mountpoints def raw_data(self, arg_ignored): '''moncov patched raw data method to fetch stats from moncov data store''' import moncov db = moncov.conf.get_db(dbhost=dbhost, dbport=dbport, dbname=dbname) if hasattr(self, '_moncov_data_cache'): return self._moncov_data_cache data = { 'arcs': {}, 'lines': {} } for filename in moncov.data.filenames(db): data['arcs'][filename] = list() data['lines'][filename] = list() for arc in moncov.data.filename_arcs(db, filename): data['arcs'][filename].append(monc
ov.data.arc2tuple(arc)) data['lines'][filename].append(moncov.data.arc2line(arc)) # duplicate with various mountpoints try: for mount_filename in self.iter_filename_over_mountpoints(filename): data['arcs'][mount_filename] = data['a
rcs'][filename] data['lines'][mount_filename] = data['lines'][filename] except Exception as e: import sys print sys.exc_info() self._moncov_data_cache = data return self._moncov_data_cache CoverageData.raw_data = raw_data
juanfont/hls-proxy
m3u8.py
Python
gpl-2.0
7,177
0.004319
# -*- Mode: Python -*- # vi:si:et:sw=4:sts=4:ts=4 # # Copyright (C) 2009-2010 Fluendo, S.L. (www.fluendo.com). # Copyright (C) 2009-2010 Marc-Andre Lureau <marcandre.lureau@gmail.com> # Copyright (C) 2014 Juan Font Alonso <juanfontalonso@gmail.com> # This file may be distributed and/or modified under the terms of # the GNU General Public License version 2 as published by # the Free Software Foundation. # This file is distributed without any warranty; without even the implied # warranty of merchantability or fitness for a particular purpose. # See "LICENSE" in the source distribution for more information. import logging import re import urllib2 class M3U8(object): def __init__(self, url=None): self.url = url self._programs = [] # main list of programs & bandwidth self._files = {} # the current program playlist self._first_sequence = None # the first sequence to start fetching self._last_sequence = None # the last sequence, to compute reload delay self._reload_delay = None # the initial reload delay self._update_tries = None # the number consecutive reload tries self._last_content = None self._endlist = False # wether the list ended and should not be refreshed self._encryption_method = None self._key_url = None self._key = None def endlist(self): return self._endlist def has_programs(self): return len(self._programs) != 0 def get_program_playlist(self, program_id=None, bitrate=None): # return the (uri, dict) of the best matching playlist if not self.has_programs(): raise _, best = min((abs(int(x['BANDWIDTH']) - bitrate), x) for x in self._programs) return best['uri'], best def reload_delay(self): # return the time between request updates, in seconds if self._endlist or not self._last_sequence: raise if self._update_tries == 0: ld = self._files[self._last_sequence]['duration'] self._reload_delay = min(self.target_duration * 3, ld) d = self._reload_delay elif self._update_tries == 1: d = self._reload_delay * 0.5 elif self._update_tries == 2: d = self._reload_delay * 1.5 else: d = self._reload_delay * 3.0 logging.debug('Reload delay is %r' % d) return int(d) def has_files(self): return len(self._files) != 0 def iter_files(self): # return an iter on the playlist media files if not self.has_files(): return if not self._endlist: current = max(self._first_sequence, self._last_sequence - 3) else: # treat differently on-demand playlists? current = self._first_sequence while True: try: f = self._files[current] current += 1 yield f if (f.has_key('endlist')): break except: yield None def update(self, content): # update this "constructed" playlist, # return wether it has actually been updated if self._last_content and content == self._last_content: logging.info("Content didn't change") self._update_tries += 1 return False self._update_tries = 0 self._last_content = content def get_lines_iter(c): c = c.decode("utf-8-sig") for l in c.split('\n'): if l.startswith('#EXT'): yield l elif l.startswith('#'): pass else: yield l self._lines = get_lines_iter(content) first_line = self._lines.next() if not first_line.startswith('#EXTM3U'): logging.error('Invalid first line: %r' % first_line) raise self.target_duration = None discontinuity = False allow_cache = None i = 0 new_files = [] for l in self._lines: if l.startswith('#EXT-X-STREAM-INF'): def to_dict(l): i = re.findall('(?:[\w-]*="[\w\.\,]*")|(?:[\w-]*=[\w]*)', l) d = {v.split('=')[0]: v.split('=')[1].replace('"','') for v in i} return d d = to_dict(l[18:])
print "stream info: " + str(d) d['uri'] = self._lines.next() self._add_playlist(d) elif l.startswith('#EXT-X-TARGETDURATION'): self.target_duration = int(l[22:]) elif l.startswith('#EXT-X-MEDIA-SEQUENCE'): self.media_sequence = int(l[22:]) i = self.media_sequence elif l.startswith('#EXT-X-DISCONTIN
UITY'): discontinuity = True elif l.startswith('#EXT-X-PROGRAM-DATE-TIME'): print l elif l.startswith('#EXT-X-ALLOW-CACHE'): allow_cache = l[19:] elif l.startswith('#EXT-X-KEY'): self._encryption_method = l.split(',')[0][18:] self._key_url = l.split(',')[1][5:-1] response = urllib2.urlopen(self._key_url) self._key = response.read() response.close() elif l.startswith('#EXTINF'): v = l[8:].split(',') d = dict(file=self._lines.next().strip(), title=v[1].strip(), duration=float(v[0]), sequence=i, discontinuity=discontinuity, allow_cache=allow_cache) discontinuity = False i += 1 new = self._set_file(i, d) if i > self._last_sequence: self._last_sequence = i if new: new_files.append(d) elif l.startswith('#EXT-X-ENDLIST'): if i > 0: self._files[i]['endlist'] = True self._endlist = True elif l.startswith('#EXT-X-VERSION'): pass elif len(l.strip()) != 0: print l if not self.has_programs() and not self.target_duration: logging.error("Invalid HLS stream: no programs & no duration") raise if len(new_files): logging.debug("got new files in playlist: %r", new_files) return True def _add_playlist(self, d): self._programs.append(d) def _set_file(self, sequence, d): new = False if not self._files.has_key(sequence): new = True if not self._first_sequence: self._first_sequence = sequence elif sequence < self._first_sequence: self._first_sequence = sequence self._files[sequence] = d return new def __repr__(self): return "M3U8 %r %r" % (self._programs, self._files)
YaoQ/zigbee-on-pcduino
zigbee.py
Python
mit
8,403
0.041652
#!/usr/bin/env python # -*- coding:UTF-8 -*- import urllib import urllib2 import json import serial import time import gpio import re import binascii import threading import datetime import sys # use your deviceID and apikey deviceID="xxxxxxxxxx" apikey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx" key_pin = "gpio12" s = "" door = "" PIR = "" Leak = "" Smoke = "" Remote = "" Door_mac = "" PIR_mac = "" Leak_mac = "" Smoke_mac = "" Remote_mac = "" # use USB UART or UART on pcDuino to communicate with zigbee gateway try: ser = serial.Serial("/dev/ttyUSB0", 115200,timeout = 0.1) except serial.serialutil.SerialException: try: ser = serial.Serial("/dev/ttyS1", 115200,timeout = 0.1) with open("/sys/devices/virtual/misc/gpio/mode/gpio0",'w') as UART_RX: UART_RX.write('3') with open("/sys/devices/virtual/misc/gpio/mode/gpio1",'w') as UART_TX: UART_TX.write('3') except serial.serialutil.SerialException: print "serial failed!" exit() def setup(): gpio.pinMode(key_pin,gpio.INPUT) def key_interrupt(): val=gpio.digitalRead(key_pin) if val==0: time.sleep(0.010) if val==0: return '1' return '0' def http_post(data): try: url = 'http://www.linksprite.io/api/http' jdata = json.dumps(data) req = urllib2.Request(url, jdata) req.add_header('Content-Type','application/json') response = urllib2.urlopen(req) return response.read() except urllib2.URLError: print "connect failed" return "connect failed" pass def hexShow(argv): result = '' hLen = len(argv) for i in xrange(hLen): hvol = ord(argv[i]) hhex = '%02x'%hvol result += hhex+' ' return result def register(): while True: ser.write('\x02') ser.write('\x75') ser.write('\x1e') data = ser.readline() val=hexShow(data) leng = len(val) if leng > 45: a = val.find("0e fc 02 e1",1) if a != -1: print "add equipment ok" b=a+12 mac = val[b:b+29] return mac break time.sleep(0.2) def set_target(short_mac): send = "0c fc 02 01 04 01 01 01 02"+short_mac+"02 0a" s = send.replace(' ','') a=binascii.a2b_hex(s) while True: ser.write(a) recv=ser.readline() rec=hexShow(recv) a = rec.find("04 fd 02 01",0) if a != -1: print "set target ok" break time.sleep(0.2) def gateway_mac(): while True: ser.write('\x02') ser.write('\x14') ser.write('\x6f') data = ser.readline() dat = hexShow(data) leng = len(dat) if leng > 30: a = dat.find("0c 15 00 6f",0) if a != -1: dt = dat[15:38] return dt break time.sleep(1) def bind(eq_mac,gat_mac): send = "16 d8"+eq_mac+"01 01 00 03"+gat_mac+"01" s = send.replace(' ','') a=binascii.a2b_hex(s) start = datetime.datetime.now() while True: ser.write(a) recv=ser.readline() rec=hexShow(recv) b = rec.find("02 d9 00") if b != -1: print "bind ok" break time.sleep(0.2) def cluster(): send = "08 FC 00 00 05 00 01 01 00" s = send.replace(' ','') a=binascii.a2b_hex(s) start = datetime.datetime.now() while True: ser.write(a) recv=ser.readline() rec=hexShow(recv) leng = len(rec) finsh = datetime.datetime.now() tim = (finsh-start).seconds if tim > 5: print "failure! please add again" return "xxxx" break if leng > 30: b = rec.find("0b fe 03") c = rec.find("00 01 07 fe 03 00") if b != -1: return rec[b+30:b+35] break elif c != -1: return "11 00" time.sleep(0.2) def report(): send = "11 FC 00 01 00 06 01 00 21 00 20 f0 00 f0 00 01 00 00" s = send.replace(' ','') a=binascii.a2b_hex(s) while True: ser.write(a) recv=ser.readline() rec=hexShow(recv) leng = len(rec) if leng > 15: b = rec.find("06 fd 00") if b != -1: print "send report ok" break time.sleep(0.2) def alarm(): line = ser.readline() val = hexShow(line) leng = len(val) if leng >= 56: #print val po = val.find("fe 01") if po != -1: aa = val[po+21:po+26] sta = val[po+46] s = aa+sta return s return -1 def open_socket(): send = "05 FC 01 06 00 01" s = send.replace(' ','') a=binascii.a2b_hex(s) def close_socket(): send = "05 FC 01 06 00 00" s = send.replace(' ','') a=binascii.a2b_hex(s) def recovery(): global s global PIR s = '0' PIR = '0' values ={ "action":"update", "apikey":apikey, "deviceid":deviceID, "params": { "PIR":PIR, "SOS":s }} http_post(values) def update(mac,sta): global Door_mac global PIR_mac global Leak_mac global Smoke_mac global Remote_mac global s global door global PIR global Leak global Smoke global Remote try: f = open('door.txt','r') Door_mac=f.read() f.close() except IOError: pass try: f = open('pir.txt','r') PIR_mac=f.read() f.close() except IOError: pass try: f = open('leak.txt','r') Leak_mac=f.read() f.close() except IOError: pass try: f = open('smoke.txt','r') Smoke_mac=f.read() f.close() except IOError: pass try: f = open('remote.txt','r') Remote_mac=f.read() f.close() except IOError: pass if mac == Door_mac: door = sta elif mac == PIR_mac: PIR = sta elif mac == Leak_mac: Leak = sta elif mac == Smoke_mac: Smoke = sta elif mac == Remote_mac: Remote = sta if sta == '1': s = sta else: print "You should add the equipment first" values ={ "action":"update", "apikey":apikey, "deviceid":deviceID, "params": { "Door":door, "PIR":PIR, "Leak":Leak, "Smoke":Smoke, "Remote":Remote, "SOS":s }} http_post(values) if s == '1'or PIR == '1': timer = threading.Timer(2,recovery) timer.start() def main(): global Door_mac global PIR_mac global Leak_mac global Smoke_mac global Remote_mac setup() if ser.isOpen() == True: print "serial open succeed!" else: print "serial open failure!" while True: # If check the GPIO12's status, if it is high, excuete commands to # add new zigbee device into zigbee gateway a = key_interrupt() if a == '1': print "Add equipment!" # Set gateway to allow adding device val=register() short = val[0:5] print "short:"+short mac = val[6:29] print "mac:"+mac # Get the gateway MAC address gatmac=gateway_mac() print "gatewaymac:"+gatmac # Configure the communication with zigbee device set_target(short) # Bind the zigbee device bind(mac,gatmac) # Read the zone type to check the type of zigbee device # which can identify the alarm information from different zigbee sensor. zone_type=cluster() print "zone_type:"+zone_type if zone_type == "15 00": Door_mac = short f = open('door.txt','w') f.write(short) f.close() report() elif zone_type == "0d 00": PIR_mac = short f=open('pir.txt','w') f.write(short) f.close() report() elif zone_type == "2a 00": Leak_mac = short f=open('leak.txt','w') f.write(short) f.close() report() elif
zone_type == "28 00": Smoke_mac = short f=open('smoke.txt','w') f.write(short) f.close() report() elif zone_type == "11 00": Remote_mac = short f=open('remote.txt','w') f.write(short) f.close() report() # Check the alarm informati
on from zigbee sensor node data=alarm() if data != -1: short_mac = data[0:5] print"short mac:"+short_mac status = data[5] p
jbadigital/django-openid-auth
django_openid_auth/models.py
Python
bsd-2-clause
2,456
0
# django-openid-auth - OpenID integration for django.contrib.auth # # Copyright (C) 2007 Simon Willison # Copyright (C) 2008-2013 Canonical Ltd. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. from django.contrib.auth.models import User from django.db import models class Nonce(models.Model): server_url = models.CharField(max_length=2047) timestamp = models.IntegerField() salt = models.CharField(max_length=40) def __unicode__(self): return u"Nonce: %s, %s" % (self.server_url, self.salt) class Association(models.Model): server_url =
models.TextField(max_length=2047) handle = models.CharField(max_length=255) secr
et = models.TextField(max_length=255) # Stored base64 encoded issued = models.IntegerField() lifetime = models.IntegerField() assoc_type = models.TextField(max_length=64) def __unicode__(self): return u"Association: %s, %s" % (self.server_url, self.handle) class UserOpenID(models.Model): user = models.ForeignKey(User) # removed unique on claimed_id due to # https://bugs.launchpad.net/django-openid-auth/+bug/524796 claimed_id = models.TextField(max_length=2047) display_id = models.TextField(max_length=2047)
alexander-95/client_python
tests/test_client.py
Python
apache-2.0
22,394
0.004599
from __future__ import unicode_literals import os import threading import time import unittest from prometheus_client import Gauge, Counter, Summary, Histogram, Metric from prometheus_client import CollectorRegistry, generate_latest, ProcessCollector from prometheus_client import push_to_gateway, pushadd_to_gateway, delete_from_gateway from prometheus_client import CONTENT_TYPE_LATEST, instance_ip_grouping_key try: from BaseHTTPServer import BaseHTTPRequestHandler from BaseHTTPServer import HTTPServer except ImportError: # Python 3 from http.server import BaseHTTPRequestHandler from http.server import HTTPServer class TestCounter(unittest.TestCase): def setUp(self): self.registry = CollectorRegistry() self.counter = Counter('c', 'help', registry=self.registry) def test_increment(self): self.assertEqual(0, self.registry.get_sample_value('c')) self.counter.inc() self.assertEqual(1, self.registry.get_sample_value('c')) self.counter.inc(7) self.assertEqual(8, self.registry.get_sample_value('c')) def test_negative_increment_raises(self): self.assertRaises(ValueError, self.counter.inc, -1) def test_function_decorator(self): @self.counter.count_exceptions(ValueError) def f(r): if r: raise ValueError else: raise TypeError try: f(False) except TypeError: pass self.assertEqual(0, self.registry.get_sample_value('c')) try: f(True) except ValueError: raised = True self.assertEqual(1, self.registry.get_sample_value('c')) def test_block_decorator(self): with self.counter.count_exceptions(): pass self.assertEqual(0, self.registry.get_sample_value('c')) raised = False try: with self.counter.count_exceptions(): raise ValueError except: raised = True self.assertTrue(raised) self.assertEqual(1, self.registry.get_sample_value('c')) class TestGauge(unittest.TestCase): def setUp(self): self.registry = CollectorRegistry() self.gauge = Gauge('g', 'help', registry=self.registry) def test_gauge(self): self.assertEqual(0, self.registry.get_sample_value('g')) self.gauge.inc() self.assertEqual(1, self.registry.get_sample_value('g')) self.gauge.dec(3) self.assertEqual(-2, self.registry.get_sample_value('g')) self.gauge.set(9) self.assertEqual(9, self.registry.get_sample_value('g')) def test_function_decorator(self): self.assertEqual(0, self.registry.get_sample_value('g')) @self.gauge.track_inprogress() def f(): self.assertEqual(1, self.registry.get_sample_value('g')) f() self.assertEqual(0, self.registry.get_sample_value('g')) def test_block_decorator(self): self.assertEqual(0, self.registry.get_sample_value('g')) with self.gauge.track_inprogress(): self.assertEqual(1, self.registry.get_sample_value('g')) self.assertEqual(0, self.registry.get_sample_value('g')) def test_gauge_function(self): x = {} self.gauge.set_function(lambda: len(x)) self.assertEqual(0, self.registry.get_sample_value('g')) self.gauge.inc() self.assertEqual(0, self.registry.get_sample_value('g')) x['a'] = None self.assertEqual(1, self.registry.get_sample_value('g')) def test_function_decorator(self): self.assertEqual(0, self.registry.get_sample_value('g')) @self.gauge.time() def f(): time.sleep(.001) f() self.assertNotEqual(0, self.registry.get_sample_value('g')) def test_block_decorator(self): self.assertEqual(0, self.registry.get_sam
ple_value('g')) with self.gauge.time(): time.sleep(.001) self.assertNotEqual(0, self.registry.get_sample_value('g')) class TestSummary(unittest.TestCase): def setUp(self): self.registry = CollectorRegistry() self.summary = Summary('s', 'help', registry=sel
f.registry) def test_summary(self): self.assertEqual(0, self.registry.get_sample_value('s_count')) self.assertEqual(0, self.registry.get_sample_value('s_sum')) self.summary.observe(10) self.assertEqual(1, self.registry.get_sample_value('s_count')) self.assertEqual(10, self.registry.get_sample_value('s_sum')) def test_function_decorator(self): self.assertEqual(0, self.registry.get_sample_value('s_count')) @self.summary.time() def f(): pass f() self.assertEqual(1, self.registry.get_sample_value('s_count')) def test_block_decorator(self): self.assertEqual(0, self.registry.get_sample_value('s_count')) with self.summary.time(): pass self.assertEqual(1, self.registry.get_sample_value('s_count')) class TestHistogram(unittest.TestCase): def setUp(self): self.registry = CollectorRegistry() self.histogram = Histogram('h', 'help', registry=self.registry) self.labels = Histogram('hl', 'help', ['l'], registry=self.registry) def test_histogram(self): self.assertEqual(0, self.registry.get_sample_value('h_bucket', {'le': '1.0'})) self.assertEqual(0, self.registry.get_sample_value('h_bucket', {'le': '2.5'})) self.assertEqual(0, self.registry.get_sample_value('h_bucket', {'le': '5.0'})) self.assertEqual(0, self.registry.get_sample_value('h_bucket', {'le': '+Inf'})) self.assertEqual(0, self.registry.get_sample_value('h_count')) self.assertEqual(0, self.registry.get_sample_value('h_sum')) self.histogram.observe(2) self.assertEqual(0, self.registry.get_sample_value('h_bucket', {'le': '1.0'})) self.assertEqual(1, self.registry.get_sample_value('h_bucket', {'le': '2.5'})) self.assertEqual(1, self.registry.get_sample_value('h_bucket', {'le': '5.0'})) self.assertEqual(1, self.registry.get_sample_value('h_bucket', {'le': '+Inf'})) self.assertEqual(1, self.registry.get_sample_value('h_count')) self.assertEqual(2, self.registry.get_sample_value('h_sum')) self.histogram.observe(2.5) self.assertEqual(0, self.registry.get_sample_value('h_bucket', {'le': '1.0'})) self.assertEqual(2, self.registry.get_sample_value('h_bucket', {'le': '2.5'})) self.assertEqual(2, self.registry.get_sample_value('h_bucket', {'le': '5.0'})) self.assertEqual(2, self.registry.get_sample_value('h_bucket', {'le': '+Inf'})) self.assertEqual(2, self.registry.get_sample_value('h_count')) self.assertEqual(4.5, self.registry.get_sample_value('h_sum')) self.histogram.observe(float("inf")) self.assertEqual(0, self.registry.get_sample_value('h_bucket', {'le': '1.0'})) self.assertEqual(2, self.registry.get_sample_value('h_bucket', {'le': '2.5'})) self.assertEqual(2, self.registry.get_sample_value('h_bucket', {'le': '5.0'})) self.assertEqual(3, self.registry.get_sample_value('h_bucket', {'le': '+Inf'})) self.assertEqual(3, self.registry.get_sample_value('h_count')) self.assertEqual(float("inf"), self.registry.get_sample_value('h_sum')) def test_setting_buckets(self): h = Histogram('h', 'help', registry=None, buckets=[0, 1, 2]) self.assertEqual([0.0, 1.0, 2.0, float("inf")], h._upper_bounds) h = Histogram('h', 'help', registry=None, buckets=[0, 1, 2, float("inf")]) self.assertEqual([0.0, 1.0, 2.0, float("inf")], h._upper_bounds) self.assertRaises(ValueError, Histogram, 'h', 'help', registry=None, buckets=[]) self.assertRaises(ValueError, Histogram, 'h', 'help', registry=None, buckets=[float("inf")]) self.assertRaises(ValueError, Histogram, 'h', 'help', registry=None, buckets=[3, 1]) def test_labels(self): self.labels.labels('a').observe(2) self.assertEqua
kamiseko/factor-test
idiVol IN.py
Python
mit
17,571
0.005826
#!/Tsan/bin/python # -*- coding: utf-8 -*- # Libraries To Use from __future__ import division from CloudQuant import MiniSimulator import numpy as np import pandas as pd import pdb import cvxopt as cv from cvxopt import solvers from datetime import datetime, date, time import barraRiskModel as brm import factorFilterFunctions as ff # define path path = ff.data_path filenameHS300 = 'LZ_GPA_INDXQUOTE_CLOSE.csv' filenameICWeight = 'ICfactorWeight8factorsPB.csv' filenameOwnVol = 'Own_Factor_Volatility_90d.csv' # 90天收益波动率 filenameDDA20 = 'Own_Factor_DDA-20d.csv' # 股票每日成交额(前复权) filenameOWNILLIQ ='Own_Factor_ILLQ-1d.csv' # 非流动性因子(自算) filenameIDIVOL = 'Own_Factor_Idiosyncratic_Volatility.csv' # 特异常波动率 # Variables and Constants Init_Cap = 50000000 Start_Date = '20120101' End_Date = '20161231' ShortMA = 12 LongMA = 15 Period = 60 Position_Max = 200 rowsNum = 21 timeStampNum = 2000 thresholdNum = 0.2 indexPool = ['000300', '000905'] # Use own library to get the last day of each month benchMarkData = pd.read_csv(path+filenameHS300, infer_datetime_format=True, parse_dates=[0], index_col=0)[-timeStampNum:] startOfMonth, endOfMonth = ff.getLastDayOfMonth(benchMarkData.index) DDA20df = pd.read_csv(path+filenameDDA20, infer_datetime_format=True, parse_dates=[0], index_col=0)[-timeStampNum:] Volatilitydf = pd.read_csv(path+filenameOwnVol, infer_datetime_format=True, parse_dates=[0], index_col=0)[-timeStampNum:] # factor weight OwnILLQdf = pd.read_csv(path+filenameOWNILLIQ, infer_datetime_format=True, parse_dates=[0], index_col=0)[-timeStampNum:] IDIVOLdf = pd.read_csv(path+filenameIDIVOL, infer_datetime_format=True, parse_dates=[0], index_col=0) factorWeight = pd.read_csv(path+filenameICWeight, infer_datetime_format=True, parse_dates=[0], index_col=0) def getNewMatrix(inputArray, t, m): newMatrix = [] n = t-m+1 for i in range(n): newdata
= list(inputArray[i:m+i]) newMatrix.append(newdata) #newMatrix = np.array(newMatrix).reshape(n,m) return np.array(newMatrix) def recreateArray(newMatrix,t,m): ret = [] n = t - m + 1 for p in range(1, t+1): if p < m: alpha = p elif p > t-m+1: alpha = t-p+1 else: alpha = m sigma = 0 for j in range(1, m+1):
i = p - j + 1 if i > 0 and i < n+1: sigma += newMatrix[i-1][j-1] ret.append(sigma/alpha) return np.array(ret) def getSVD(inputArray,t,m): inputmatrix = getNewMatrix(inputArray, t, m) u, s, v = np.linalg.svd(inputmatrix) eviNum = 1 if s[0]/s.sum() > 0.99 else 2 sNew = np.zeros((eviNum, eviNum)) np.fill_diagonal(sNew, s[:eviNum]) matrixForts = np.dot(np.dot(u[:, :eviNum].reshape(u.shape[0], eviNum), sNew), v[:eviNum]) newts = recreateArray(matrixForts, t, m) return newts def initial(sdk): sdk.prepareData(['LZ_GPA_INDEX_CSI500WEIGHT', 'LZ_GPA_VAL_PB', 'LZ_GPA_FIN_IND_OCFTODEBT', 'LZ_GPA_FIN_IND_QFA_YOYGR', 'LZ_GPA_DERI_Momentum_1M', 'LZ_GPA_CMFTR_CUM_FACTOR', 'LZ_GPA_QUOTE_TCLOSE', 'LZ_GPA_INDXQUOTE_CLOSE']) dateList = map(lambda x: x.date().strftime("%Y%m%d"), endOfMonth) # change time stamp to string sdk.setGlobal('dateList', dateList) sdk.setGlobal('sellSignal', [True]) DDA20df.columns = sdk.getStockList() Volatilitydf.columns = sdk.getStockList() OwnILLQdf.columns = sdk.getStockList() IDIVOLdf.columns = sdk.getStockList() #print DDA20df.head().iloc[:, :5] print len(sdk.getStockList()) def initPerDay(sdk): today = sdk.getNowDate() dateList = sdk.getGlobal('dateList') if today in dateList: # judge whether today is the last day of the month today = datetime.strptime(today, '%Y%m%d') stockPool = pd.DataFrame(np.array(sdk.getFieldData('LZ_GPA_INDEX_CSI500WEIGHT')[-20:]), columns=sdk.getStockList()) stockPool = stockPool.iloc[-1].dropna(how='any').index.tolist() # get today's ZX500 stock pool # PBData PBDF = pd.DataFrame(np.array(sdk.getFieldData('LZ_GPA_VAL_PB')[-20:]), columns=sdk.getStockList()) PBDF = PBDF[stockPool].fillna(method='ffill').fillna(method='bfill').iloc[-1] PBSlice = (PBDF - PBDF.mean())/PBDF.std() # normalize # OCFTODEBT Data OCFTODEBT = pd.DataFrame(np.array(sdk.getFieldData('LZ_GPA_FIN_IND_OCFTODEBT')[-20:]), columns=sdk.getStockList()) OCFTODEBT = OCFTODEBT[stockPool].fillna(method='ffill').fillna(method='bfill').iloc[-1] OCFTODEBTSlice = (OCFTODEBT - OCFTODEBT.mean())/OCFTODEBT.std() # MOM1MData MOM1MDF = pd.DataFrame(np.array(sdk.getFieldData('LZ_GPA_DERI_Momentum_1M')[-20:]), columns=sdk.getStockList()) MOM1MDF = MOM1MDF[stockPool].fillna(method='ffill').fillna(method='bfill').iloc[-1] MOM1MSlice = (MOM1MDF - MOM1MDF.mean())/MOM1MDF.std() # YOYGRData YOYGRDF = pd.DataFrame(np.array(sdk.getFieldData('LZ_GPA_FIN_IND_QFA_YOYGR')[-20:]), columns=sdk.getStockList()) YOYGRDF = YOYGRDF[stockPool].fillna(method='ffill').fillna(method='bfill').iloc[-1] YOYGRSlice = (YOYGRDF-YOYGRDF.mean())/YOYGRDF.std() # ILLIQData #ILLIQDF = pd.DataFrame(np.array(sdk.getFieldData('LZ_GPA_DERI_ILLIQ')[-20:]), columns=sdk.getStockList()) DDA20 = DDA20df.loc[:today] DDA20 = DDA20.iloc[-20:] DDA20 = DDA20[stockPool].fillna(method='ffill').fillna(method='bfill').iloc[-1] DDA20Slice = (DDA20 - DDA20.mean())/DDA20.std() # Volatility VOL = Volatilitydf.loc[:today] VOL = VOL.iloc[-20:] VOL = VOL[stockPool].fillna(method='ffill').fillna(method='bfill').iloc[-1] VOLSlice = (VOL -VOL.mean())/VOL.std() # OwnILLQData OwnILLQ = OwnILLQdf.loc[:today] OwnILLQ = OwnILLQ.iloc[-20:] OwnILLQ = OwnILLQ[stockPool].fillna(method='ffill').fillna(method='bfill').iloc[-1] OwnILLQSlice = (OwnILLQ - OwnILLQ.mean()) / OwnILLQ.std() # Idiosyncratic Volatility IDIVOL = IDIVOLdf.loc[:today] IDIVOL = IDIVOL.iloc[-20:] IDIVOL = IDIVOL[stockPool].fillna(method='ffill').fillna(method='bfill').iloc[-1] IDIVOLSlice = (IDIVOL - IDIVOL.mean()) / IDIVOL.std() # Select the corresponding factor weight WeightSlice = factorWeight.loc[today] finalIndictor = WeightSlice['PB'] * PBSlice + WeightSlice['OCFTODEBT'] * OCFTODEBTSlice + \ WeightSlice['MOM_1M'] * MOM1MSlice + WeightSlice['YOYGR'] * YOYGRSlice + \ WeightSlice['VOLATILITY'] * VOLSlice + WeightSlice['DDA20'] * DDA20Slice \ + WeightSlice['OWNILLIQ'] * OwnILLQSlice + WeightSlice['IDIVOL'] * IDIVOLSlice stocksTobuy = finalIndictor.sort_values(ascending=False).index.tolist()[50:50+Position_Max] sdk.setGlobal('buyList', stocksTobuy) # To calculate the realized volatility matrix CPData = np.array(sdk.getFieldData('LZ_GPA_QUOTE_TCLOSE')[-121:]) ClosePriceDF = pd.DataFrame(CPData, columns=sdk.getStockList())[stocksTobuy] ADfactor = np.array(sdk.getFieldData('LZ_GPA_CMFTR_CUM_FACTOR')[-121:]) ADfactorDF = pd.DataFrame(ADfactor, columns=sdk.getStockList())[stocksTobuy] AdForward = ADfactorDF / ADfactorDF.max() adjustedPrice = (AdForward * ClosePriceDF) adjustedPrice = adjustedPrice.loc[:, adjustedPrice.isnull().sum() < (len(adjustedPrice) * thresholdNum)] adjustedPrice = adjustedPrice.fillna(method='ffill').fillna(method='bfill') print adjustedPrice.shape[1] #covMatrix = adjustedPrice.ewm(ignore_na=True, min_periods=0, com=10).cov(pairwise = True)[-60:].iloc[-1] adjustedPrice = np.log(adjustedPrice/adjustedPrice.shift(1))[-120:] # calculate daily log return of each stock #covMatrix = brm.calEWMcovariance(adjustedPrice) covMatrix = adjustedPrice.cov(1) pr
GreatLakesEnergy/sesh-dash-beta
seshdash/api/enphase.py
Python
mit
6,147
0.020823
import requests, json, logging from lxml import html from datetime import datetime logger = logging.getLogger(__name__) class EnphaseAPI: API_BASE_URL = "https://api.enphaseenergy.com/api/v2/systems/{system_id}/{function}?key={key}&user_id={user_id}" API_BASE_URL_INDEX = "https://api.enphaseenergy.com/api/v2/systems/?key={key}&user_id={user_id}" FORMAT = "json" """ Provide API key and User Key to get started more info here:https://developer.enphase.com/docs/quickstart.html """ def __init__(self , key, user_id, format_type=json): self.IS_INITIALIZED = False self.SYSTEMS_IDS = {} self.SYSTEMS_INFO = {} self.KEY = key self.FORMAT = format_type self.USER_ID = user_id self._initialize()
if self.IS_INITIALIZED: print "system initialized" logger.info("System Initialized with %s systems"%len(self.SYSTEMS_IDS)) else: logger.error("unable to initialize the api") """ Initialization functio
n This will talk to enphase and get aall system ids """ def _initialize(self): formatedURL = self.API_BASE_URL_INDEX.format( key = self.KEY, user_id = self.USER_ID, ) response = requests.get(formatedURL) #check that everything is good with the request here if response.status_code == 401: logger.error("Access denied unable to initialize \nresponse: %s:" %response) self.IS_INITIALIZED = False if response.status_code== 200: response_parsed = response.json() if response_parsed.has_key("systems"): for system in response_parsed['systems']: #extract the system id, we'll need this later self.SYSTEMS_IDS[system["system_id"]] = system['system_name'] #Get System summary for each site so we can get critical system stats: sys_sum = self.get_summary(system["system_id"]) self.SYSTEMS_INFO[system["system_id"]] = sys_sum self.IS_INITIALIZED = True else: logger.warning("No systems registerd") self.SYSTEMS_IDS = [] self.IS_INITIALIZED = False """ clean up results before returning them """ def parse_response(self,response_json): parsed = json.loads(response_json) return parsed """ Utility function to prepare our requests before sending them """ def make_request(self,function_name,system_id,**kwargs): #format string with our paramters can do this with requests as well formatedURL = self.API_BASE_URL.format( system_id = system_id, key = self.KEY, user_id = self.USER_ID, function = function_name ) r = requests.get(formatedURL,params=kwargs) print r.url return r.json() """ Get system summary @param: summary_date: Get summary for this date (optional) """ def get_summary(self,system_id,summary_date=None): if summary_date: return self.make_request("summary",system_id,summary_date=summary_date) return self.make_request("summary",system_id) """ Get system stats for provided system_id optional start end endtime times (isoformat) will give stats within that interval @params: system_id start_date (optional) end_date (mandatory if start_date provided) """ def get_stats(self,system_id,start=0,end=0,datetime_format='epoch'): if start and end: print "#systemid %s start %s end %s"%(system_id,start,end) return self.make_request(function_name="stats", system_id=system_id, start_at=start, end_at=end, datetime_format=datetime_format) if start: print "#systemid %s start %s end %s"%(system_id,start,end) return self.make_request(function_name="stats", system_id=system_id, start_at=start,datetime_format=datetime_format) return self.make_request("stats",system_id,datetime_format=datetime_format) """ return monthly production from start date @params: start_data """ def get_monthly_production(self,system_id,start_date): return self.make_request("monthly_production",system_id,start_date=start_date) <<<<<<< Updated upstream class EnphaseLocalAPI: _ENVOY_IP = '0.0.0.0' _IS_INTIALIZED = False _ENVOY_URL = 'http://{ip}/{path}?locale=en' _CURRENT_DATA = {} _XPATH_DICT = { 'current_production':'/html/body/div[1]/table/tr[2]/td[2]/text()', 'today_production':'/html/body/div[1]/table/tr[3]/td[2]/text()', 'past_week_production':'/html/body/div[1]/table/tr[4]/td[2]/text()', 'since_installation_production':'/html/body/div[1]/table/tr[5]/td[2]/text()' } def __init__(self, ip ): self._ENVOY_IP = ip self._initialize() if self._IS_INTIALIZED: logger.info('ENHPASE LOCAL API initialised') def _initialize(self): formated_url = self._ENVOY_URL.format(ip = self._ENVOY_IP,path = 'production') envoy_page = requests.get(formated_url) page_html = html.fromstring(envoy_page.text) if envoy_page.status_code == 200: print "API initialized getting data" self._CURRENT_DATA = self._parse_production_data(page_html) self._IS_INTIALIZED = True else: logger.error("unable to initialize API error: %s"%envoy_page.status_code) self._IS_INTIALIZED = False def _parse_production_data(self,page_html): parsed_result = {'':datetime.now()} for key in self._XPATH_DICT.keys(): value = page_html.xpath(self._XPATH_DICT[key]) parsed_result[key] = value[0].strip() return parsed_result def get_current_prod_data(self): return self._CURRENT_DATA ======= >>>>>>> Stashed changes
PiJoules/translation
__init__.py
Python
apache-2.0
847
0.022432
# Call vendor to add the dependencies to the classpath import vendor vend
or.add('lib') # Import the Flask Framework from flask import Flask, render_template, url_for, request, jsonify app =
Flask(__name__) import translate # Root directory @app.route('/') def index_route(): phrase = request.args.get("q") if not phrase: return render_template("index.html", phrase="") return render_template("index.html", phrase=phrase) @app.route("/translate") def translate_route(): phrase = request.args.get("text") fro = request.args.get("from") to = request.args.get("to") translated_text = translate.get_translation(phrase, lang=fro + "-" + to) if translated_text == None: return "Failed to translate", 404 return translated_text if __name__ == '__main__': #app.run(host="0.0.0.0") # For development app.run() # For production
jss367/assemble
congress/congress/spiders/example.py
Python
mit
1,924
0.002079
import scrapy from congress.items import Article class Example(scrapy.Spider): '''Modeled after scrapy tutorial here: https://doc.scrapy.org/en/latest/intro/tutorial.html ''' # spider name should be name of website/source name = 'example' def start_requests(self): # list of URLs or single URL to start carwl urls = [ 'http://quotes.toscrape.com/page/1/' ] for url in urls: yield scrapy.Request(url=url, callback=self.parse) def parse(self, response): '''to learn more about xpath selectors: https://doc.scrapy.org/en/latest/topics/selectors.html ''' language = response.xpath('//html/@lang').extract_first() url = response.url source = 'example' # spider name # Select all quotes quotes = response.xpath('//div[@class="quote"]') for quote in quotes: # Each quote is itself a selector xpath. # To dig deeper inside this path use ".//" syntax text_blob = quote.xpath('.//span/text()').extract_first() # Using [contains@class] for illustrative purposes. We could
have used # @class="author" as well. This will return any small tag with class # that contains the w
ord "author" author = quote.xpath('.//small[contains(@class, "author")]').extract_first() # now we create our article item for a list of available fields see items.py article = Article( # Required fields language=language, url=url, source=source, text_blob=text_blob, # Optional field (add anything your site provides) authors=author ) # Sends our article off to the pipeline for validation! yield article
Simon-Hohberg/Pi-Radio
radiocontrol/manage.py
Python
mit
255
0
#!/usr/bin/env python import os import sys if
__name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_
MODULE", "radiocontrol.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
starcruiseromega/insolent-meow
import_resolver/test_import_resolver.py
Python
gpl-2.0
6,124
0.023607
# coding=utf-8 from __future__ import print_function, unicode_literals __author__ = "Sally Wilsak" import codecs import os import sys import textwrap import unittest import import_resolver # This isn't strictly correct; it will only work properly if your terminal is set to UTF-8. # However, Linux is usually set to UTF-8 and Windows' English code page 437 is at least ASCII-compatible this will work well enough for our purposes if sys.stdout.encoding != 'utf8': sys.stdout = codecs.getwriter('utf8')(sys.stdout, 'strict') if sys.stderr.encoding != 'utf8': sys.stderr = codecs.getwriter('utf8')(sys.stderr, 'strict') def simple_normpath(path): """On Windows, normpath substitutes back slashes into the file path. This makes cross-platform testing difficult since we're checking string output. But the test cases have simple filepaths so we can substitute something simpler for the tests. """ return path.replace("./", "") def simple_join(path, *args): """ Make os.path.join work the same on Windows and Linux. Again this is ok because the test cases have simple paths """ elements = [path] elements.extend(args) return "/".join(elements) class TestImportResolver(unittest.TestCase): def setUp(self): # Monkey-patch some path manipulations so we can string match with Unix-style paths and Windows won't mess them up import_resolver.os.path.normpath = simple_normpath import_resolver.os.path.join = simple_join def test_line_extraction(self): self.assertEqual(import_resolver.extract_import_files(""), []) self.assertEqual(import_resolver.extract_import_files("This isn't TypeScript.\nBut it does have multiple lines."), []) self.assertEqual(import_resolver.extract_import_files("import thing = require('./thing.ts');"), ["./thing.ts"]) import_statements = textwrap.dedent(""" // Comments should get ignored, of course import first = require('./lib/first.ts'); // Different amounts of whitespace should be ok import second=require('./second.ts') ; // so should other stuff at the end // Double quotes are also ok import _THIRD = require("./third.ts") // So is something that's not a ts file, but it gets .ts added import fourth = require("../fourth/file/path") // A Windows-style path doesn't match... import fifth = require("C:\\fifth.ts") // ...neither does an absolute Unix-style path... import sixth = require("/home/user6/sixth.ts") // ...but this mixed-up one does import seventh = require('./folder\\folder\\seventh.ts') // Capitalizing the keywords means it doesn't match Import eighth = Require('./eighth.ts') // Something that's not a file path doesn't match import ninth = require('ninth') // If it's not at the start of the line, it doesn't match some stuff import tenth = require('./tenth.ts') // And for good measure, a non-ASCII file path should work import eleventh = require('./одиннадцать.ts') """) expected_filenames = [ "./lib/first.ts", "./second.ts", "./third.ts", "../fourth/file/path.ts", "./folder\\folder\\seventh.ts", "./одиннадцать.ts", ] self.assertEqual(import_resolver.extract_import_files(import_statements), expected_filenames) def test_format(self): files = ["/badger/badger", "C:\\badger.ts", "/bad ger/snake.ts"] self.assertEqual(import_resolver.format_line("/file/name.ts", files), "/file/name.ts <- /badger/badger C:\\badger.ts /bad\\ ger/snake.ts") def test_circular_deps(self): circular_deps = { "/home/badger/a.ts": "import b = require('./b.ts');\nimport c = require('./c.ts');", "/home/badger/b.ts": "import d = require('./d.ts');", "/home/badger/c.ts": "", "/home/badger/d.ts": "import a = require('./a.ts');", } import_resolver.read_file = lambda x: circular_deps[x] expected_string = "\n".join([ "/home/badger/c.ts <- /home/badger/a.ts", "/home/badger/d.ts <- /home/badger/b.ts",
"/home/badger/a.ts <- /home/badger/d.ts", "/home/badger/b.ts <- /home/badger/a.ts", ]) self.assertEqual(import_resolver.do_dependency_resolve(["/home/badger/a.ts"]), expected_string) def test_triangle_deps(self): triangle_deps = { "/home/badger/a.ts": "import b = require('./b.ts');\nimport c = require('./c.ts');", "/home/badger/b.ts": "import c = require('./c.ts');", "/home/badger/c.ts": "", } import_resolver.read_file = lambda x: trian
gle_deps[x] expected_string = "\n".join([ "/home/badger/c.ts <- /home/badger/a.ts /home/badger/b.ts", "/home/badger/a.ts <- ", "/home/badger/b.ts <- /home/badger/a.ts", ]) self.assertEqual(import_resolver.do_dependency_resolve(["/home/badger/a.ts"]), expected_string) def test_inaccessible_deps(self): def inaccessible_deps(filename): if "a.ts" in filename: return "import b = require('./b.ts');" elif "b.ts" in filename: return "import c = require('./c.ts');" raise IOError import_resolver.read_file = inaccessible_deps expected_string = "\n".join([ "/home/badger/c.ts <- /home/badger/b.ts", "/home/badger/a.ts <- ", "/home/badger/b.ts <- /home/badger/a.ts", "Cannot read file '/home/badger/c.ts'", ]) self.assertEqual(import_resolver.do_dependency_resolve(["/home/badger/a.ts"]), expected_string) def test_lists(self): lists_deps = { "/home/badger/a.ts": "import b = require('./b.ts');\nimport c = require('./c.ts');\nimport d = require('./d.ts');", "/home/badger/b.ts": "import c = require('./c.ts');\nimport d = require('./d.ts');", "/home/badger/c.ts": "import d = require('./d.ts');", "/home/badger/d.ts": "", } import_resolver.read_file = lambda x: lists_deps[x] expected_string = "\n".join([ "/home/badger/c.ts <- /home/badger/a.ts /home/badger/b.ts", "/home/badger/d.ts <- /home/badger/a.ts /home/badger/b.ts /home/badger/c.ts", "/home/badger/a.ts <- ", "/home/badger/b.ts <- /home/badger/a.ts", ]) self.assertEqual(import_resolver.do_dependency_resolve(["/home/badger/a.ts"]), expected_string)
photo/export-flickr
fetch.py
Python
apache-2.0
5,401
0.018885
#!/usr/bin/env python import datetime # import os for file system functions import os # import json import json # import regex import re # for date parsing import time # import flickrapi # `easy_install flickrapi` or `pip install flickrapi` import flickrapi # main program def fetch(api_key, api_secret): # create an unauthenticated flickrapi object flickr=flickrapi.FlickrAPI(api_key, api_secret) print "Open the following URL in your browser " print "This Url >>>> %s" % flickr.web_login_url(perms='read') print "When you're ready press ENTER", raw_input() print "Copy and paste the URL (from theopenphotoproject.org) here: ", frob_url = raw_input() print "\nThanks!" print "Parsing URL for the token...", match = re.search('frob=([^&]+)', frob_url) frob = match.group(1) token = flickr.get_token(frob) print "OK" # create an authenticated flickrapi object flickr = flickrapi.FlickrAPI(api_key, api_secret, token=token) # now we get the authenticated user's id print "Fetching user id...", user_resp = flickr.urls_getUserProfile() user_fields = user_resp.findall('user')[0] user_id = user_fields.get('nsid') print "OK" # print "Enter your token: ", # token
= raw_input() per_page = 100 (token, frob) = flickr.get_token_part_one('read') flickr.get_token_part_two((token, frob)) # we'll paginate through the results # start at `page` and get `per_page` results at a time page=1 # store everything in a list or array or whatever python calls this photos_out=[] # while True loop till we get no photos back while True: # call the photos.search API # http://www.flickr.com/services/api/flickr.photos.search.html
print "Fetching page %d..." % page, photos_resp = flickr.people_getPhotos(user_id=user_id, per_page=per_page, page=page, extras='original_format,tags,geo,url_o,url_b,url_c,url_z,date_upload,date_taken,license,description') print "OK" # increment the page number before we forget so we don't endlessly loop page = page+1; # grab the first and only 'photos' node photo_list = photos_resp.findall('photos')[0] # if the list of photos is empty we must have reached the end of this user's library and break out of the while True if len(photo_list) == 0: break; # else we loop through the photos for photo in photo_list: # get all the data we can p = {} p['id'] = photo.get('id') p['permission'] = bool(int(photo.get('ispublic'))) p['title'] = photo.get('title') p['license'] = getLicense(photo.get('license')) description = photo.findall('description')[0].text if description is not None: p['description'] = description if photo.get('latitude') != '0': p['latitude'] = float(photo.get('latitude')) if photo.get('longitude') != '0': p['longitude'] = float(photo.get('longitude')) if len(photo.get('tags')) > 0: p['tags'] = photo.get('tags').split(' ') else: p['tags'] = [] if photo.get('place_id') is not None: p['tags'].append("flickr:place_id=%s" % photo.get('place_id')) if photo.get('woe_id') is not None: p['tags'].append("geo:woe_id=%s" % photo.get('woe_id')) p['tags'] = ",".join(p['tags']) p['dateUploaded'] = int(photo.get('dateupload')) p['dateTaken'] = int(time.mktime(time.strptime(photo.get('datetaken'), '%Y-%m-%d %H:%M:%S'))) # Attention : this is returned only for Pro accounts, it seems if photo.get('url_o') is not None: p['photo'] = photo.get('url_o') elif photo.get('url_b') is not None: p['photo'] = photo.get('url_b') elif photo.get('url_c') is not None: p['photo'] = photo.get('url_c') elif photo.get('url_z') is not None: p['photo'] = photo.get('url_z') t = datetime.datetime.fromtimestamp(float(p['dateUploaded'])) filename = '%s-%s' % (t.strftime('%Y%m%dT%H%M%S'), p['id']) print " * Storing photo %s to fetched/%s.json" % (p['id'], filename), f = open("fetched/%s.json" % filename, 'w') f.write(json.dumps(p)) f.close() print "OK" # create a directory only if it doesn't already exist def createDirectorySafe( name ): if not os.path.exists(name): os.makedirs(name) # construct the url for the original photo # currently this requires a pro account def constructUrl( photo ): return "http://farm%s.staticflickr.com/%s/%s_%s_o.%s" % (photo.get('farm'), photo.get('server'), photo.get('id'), photo.get('originalsecret'), photo.get('originalformat')) # map Flickr licenses to short names def getLicense( num ): licenses = {} licenses['0'] = '' licenses['4'] = 'CC BY' licenses['5'] = 'CC BY-SA' licenses['6'] = 'CC BY-ND' licenses['2'] = 'CC BY-NC' licenses['1'] = 'CC BY-NC-SA' licenses['3'] = 'CC BY-NC-ND' if licenses[num] is None: return licenses[0] else: return licenses[num] if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description='Backup your Flickr photos') parser.add_argument('--api-key', required=True, help='Flickr API key') parser.add_argument('--api-secret', required=True, help='Flickr API secret') config = parser.parse_args() # check if a fetched directory exist else create it createDirectorySafe('fetched') fetch(config.api_key, config.api_secret)
tersmitten/ansible
lib/ansible/modules/remote_management/foreman/_katello.py
Python
gpl-3.0
20,771
0.002503
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2016, Eric D Helms <ericdhelms@gmail.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['deprecated'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: katello short_description: Manage Katello Resources deprecated: removed_in: "2.12" why: "Replaced by re-designed individual modules living at https://github.com/theforeman/foreman-ansible-modules" alternative: https://github.com/theforeman/foreman-ansible-modules description: - Allows the management of Katello resources inside your Foreman server. version_added: "2.3" author: - Eric D Helms (@ehelms) requirements: - nailgun >= 0.28.0 - python >= 2.6 - datetime options: server_url: description: - URL of Foreman server. required: true username: description: - Username on Foreman server. required: true password: description: - Password for user accessing Foreman server.
required: true entity: description: - The Foreman resource that the action will be performed on (e.g. organization, host). choices: - repository - manifest - repository_set - sync_plan - content_view - lifecycle_environment - activation_key - product required: true action:
description: - action associated to the entity resource to set or edit in dictionary format. - Possible Action in relation to Entitys. - "sync (available when entity=product or entity=repository)" - "publish (available when entity=content_view)" - "promote (available when entity=content_view)" choices: - sync - publish - promote required: false params: description: - Parameters associated to the entity resource and action, to set or edit in dictionary format. - Each choice may be only available with specific entitys and actions. - "Possible Choices are in the format of param_name ([entry,action,action,...],[entity,..],...)." - The action "None" means no action specified. - Possible Params in relation to entity and action. - "name ([product,sync,None], [repository,sync], [repository_set,None], [sync_plan,None]," - "[content_view,promote,publish,None], [lifecycle_environment,None], [activation_key,None])" - "organization ([product,sync,None] ,[repository,sync,None], [repository_set,None], [sync_plan,None], " - "[content_view,promote,publish,None], [lifecycle_environment,None], [activation_key,None])" - "content ([manifest,None])" - "product ([repository,sync,None], [repository_set,None], [sync_plan,None])" - "basearch ([repository_set,None])" - "releaserver ([repository_set,None])" - "sync_date ([sync_plan,None])" - "interval ([sync_plan,None])" - "repositories ([content_view,None])" - "from_environment ([content_view,promote])" - "to_environment([content_view,promote])" - "prior ([lifecycle_environment,None])" - "content_view ([activation_key,None])" - "lifecycle_environment ([activation_key,None])" required: true task_timeout: description: - The timeout in seconds to wait for the started Foreman action to finish. - If the timeout is reached and the Foreman action did not complete, the ansible task fails. However the foreman action does not get canceled. default: 1000 version_added: "2.7" required: false verify_ssl: description: - verify the ssl/https connection (e.g for a valid certificate) default: false type: bool required: false ''' EXAMPLES = ''' --- # Simple Example: - name: Create Product katello: username: admin password: admin server_url: https://fakeserver.com entity: product params: name: Centos 7 delegate_to: localhost # Abstraction Example: # katello.yml --- - name: "{{ name }}" katello: username: admin password: admin server_url: https://fakeserver.com entity: "{{ entity }}" params: "{{ params }}" delegate_to: localhost # tasks.yml --- - include: katello.yml vars: name: Create Dev Environment entity: lifecycle_environment params: name: Dev prior: Library organization: Default Organization - include: katello.yml vars: name: Create Centos Product entity: product params: name: Centos 7 organization: Default Organization - include: katello.yml vars: name: Create 7.2 Repository entity: repository params: name: Centos 7.2 product: Centos 7 organization: Default Organization content_type: yum url: http://mirror.centos.org/centos/7/os/x86_64/ - include: katello.yml vars: name: Create Centos 7 View entity: content_view params: name: Centos 7 View organization: Default Organization repositories: - name: Centos 7.2 product: Centos 7 - include: katello.yml vars: name: Enable RHEL Product entity: repository_set params: name: Red Hat Enterprise Linux 7 Server (RPMs) product: Red Hat Enterprise Linux Server organization: Default Organization basearch: x86_64 releasever: 7 - include: katello.yml vars: name: Promote Contentview Environment with longer timout task_timeout: 10800 entity: content_view action: promote params: name: MyContentView organization: MyOrganisation from_environment: Testing to_environment: Production # Best Practices # In Foreman, things can be done in paralell. # When a conflicting action is already running, # the task will fail instantly instead of waiting for the already running action to complete. # So you sould use a "until success" loop to catch this. - name: Promote Contentview Environment with increased Timeout katello: username: ansibleuser password: supersecret task_timeout: 10800 entity: content_view action: promote params: name: MyContentView organization: MyOrganisation from_environment: Testing to_environment: Production register: task_result until: task_result is success retries: 9 delay: 120 ''' RETURN = '''# ''' import datetime import os import traceback try: from nailgun import entities, entity_fields, entity_mixins from nailgun.config import ServerConfig HAS_NAILGUN_PACKAGE = True except Exception: HAS_NAILGUN_PACKAGE = False from ansible.module_utils.basic import AnsibleModule from ansible.module_utils._text import to_native class NailGun(object): def __init__(self, server, entities, module, task_timeout): self._server = server self._entities = entities self._module = module entity_mixins.TASK_TIMEOUT = task_timeout def find_organization(self, name, **params): org = self._entities.Organization(self._server, name=name, **params) response = org.search(set(), {'search': 'name={0}'.format(name)}) if len(response) == 1: return response[0] else: self._module.fail_json(msg="No organization found for %s" % name) def find_lifecycle_environment(self, name, organization): org = self.find_organization(organization) lifecycle_env = self._entities.LifecycleEnvironment(self._server, name=name, organization=org) response = lifecycle_env.search() if len(response) == 1: return response[0]
MauHernandez/cyclope
cyclope/core/series/admin.py
Python
gpl-3.0
2,378
0.003786
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2010-2013 Código Sur Sociedad Civil. # All rights reserved. # # This file is part of Cyclope. # # Cyclope 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. # # Cyclope 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/>. from django.contrib import admin from django.contrib.contenttypes import generic from cyclope.core.frontend import site from cyclope.core.collections.admin import CollectibleAdmin from cyclope.admin import BaseContentAdmin from cyclope.apps.related_admin import GenericFKWidget, GenericModelForm from cyclope.apps.related_admin import GenericModelChoiceField as GMCField from models import Series, SeriesContent def series_inline_factory(series_model): class SeriesContentForm(GenericModelForm): other_object = GMCField(label='object', widget=GenericFKWidget('other_type', cts=series_model.get_content_models())) def __init__(self, *args, **kwargs): super(SeriesContentForm, self).__init__(*args, **kwargs) self.fields['other_type'].choices = series_model.get_content_types_choices() class Meta: model = SeriesContent fields = ('order', 'other_type', 'other_object') class SeriesContentInline(ge
neric.GenericStackedInline): model = SeriesContent form = SeriesContentForm ct_field = 'self_type' ct_fk_field = 'self_id' extr
a = 0 return [SeriesContentInline] class SeriesAdmin(CollectibleAdmin, BaseContentAdmin): inlines = series_inline_factory(Series) + CollectibleAdmin.inlines + BaseContentAdmin.inlines list_display = ('name', 'creation_date') + CollectibleAdmin.list_display search_fields = ('name', 'description', ) list_filter = CollectibleAdmin.list_filter + ('creation_date',)
prechelt/typecheck-decorator
typecheck/test_typecheck_basics.py
Python
bsd-2-clause
25,312
0.005768
# Most of this file is from the lower part of Dmitry Dvoinikov's # http://www.targeted.org/python/recipes/typecheck3000.py # reworked into py.test tests import random import re import time from traceback import extract_stack import typecheck as tc import typecheck.framework from .testhelper import expected ############################################################################ class expected: def __init__(self, e, msg_regexp=None): if isinstance(e, Exception): self._type, self._msg = e.__class__, str(e) elif isinstance(e, type) and issubclass(e, Exception): self._type, self._msg = e, msg_regexp else: raise Exception("usage: 'with expected(Exception)'") def __enter__(self): # make this a context handler try: pass except: pass # this is a Python3 way of saying sys.exc_clear() def __exit__(self, exc_type, exc_value, traceback): ass
ert exc_type is not None, \ "expected {0:s} to have been thrown".format(self._type.__name__) msg = str(exc_value) return (issubclass(exc_type, self._type) and (se
lf._msg is None or msg.startswith(self._msg) or # for instance re.match(self._msg, msg))) # for class + regexp ############################################################################ def test_wrapped_function_keeps_its_name(): @tc.typecheck def foo() -> type(None): pass print("method proxy naming") assert foo.__name__ == "foo" def test_no_excessive_proxying(): @tc.typecheck def foo(): assert extract_stack()[-2][2] != "typecheck_invocation_proxy" foo() @tc.typecheck def bar() -> type(None): assert extract_stack()[-2][2] == "typecheck_invocation_proxy" bar() def test_double_annotations_wrapping(): @tc.typecheck def foo(x: int): return x assert foo(1) == tc.typecheck(foo)(1) == 1 def test_empty_string_in_incompatible_values(): @tc.typecheck def foo(s: lambda s: s != ""=None): return s assert foo() is None assert foo(None) is None assert foo(0) == 0 with expected(tc.InputParameterError("foo() has got an incompatible value for s: ''")): foo("") @tc.typecheck def foo(*, k: typecheck.framework.optional(lambda s: s != "")=None): return k assert foo() is None assert foo(k=None) is None assert foo(k=0) == 0 with expected(tc.InputParameterError("foo() has got an incompatible value for k: ''")): foo(k="") @tc.typecheck def foo(s=None) -> lambda s: s != "": return s assert foo() is None assert foo(None) is None assert foo(0) == 0 with expected(tc.ReturnValueError("foo() has returned an incompatible value: ''")): foo("") def test_invalid_type_specification(): with expected(tc.TypeCheckSpecificationError("invalid typecheck for a")): @tc.typecheck def foo(a: 10): pass with expected(tc.TypeCheckSpecificationError("invalid typecheck for k")): @tc.typecheck def foo(*, k: 10): pass with expected(tc.TypeCheckSpecificationError("invalid typecheck for return")): @tc.typecheck def foo() -> 10: pass def test_incompatible_default_value(): with expected(tc.TypeCheckSpecificationError("the default value for b is incompatible with its typecheck")): @tc.typecheck def ax_b2(a, b: int="two"): pass with expected(tc.TypeCheckSpecificationError("the default value for a is incompatible with its typecheck")): @tc.typecheck def a1_b2(a: int="one", b="two"): pass with expected(tc.TypeCheckSpecificationError("the default value for a is incompatible with its typecheck")): @tc.typecheck def foo(a: str=None): pass with expected(tc.TypeCheckSpecificationError("the default value for a is incompatible with its typecheck")): @tc.typecheck def kw(*, a: int=1.0): pass with expected(tc.TypeCheckSpecificationError("the default value for b is incompatible with its typecheck")): @tc.typecheck def kw(*, a: int=1, b: str=10): pass def test_can_change_default_value(): @tc.typecheck def foo(a: list=[]): a.append(len(a)) return a assert foo() == [0] assert foo() == [0, 1] assert foo([]) == [0] assert foo() == [0, 1, 2] assert foo() == [0, 1, 2, 3] @tc.typecheck def foo(*, k: typecheck.framework.optional(list)=[]): k.append(len(k)) return k assert foo() == [0] assert foo() == [0, 1] assert foo(k=[]) == [0] assert foo() == [0, 1, 2] assert foo() == [0, 1, 2, 3] def test_unchecked_args(): @tc.typecheck def axn_bxn(a, b): return a + b assert axn_bxn(10, 20) == 30 assert axn_bxn(10, 20.0) == 30.0 assert axn_bxn(10.0, 20) == 30.0 assert axn_bxn(10.0, 20.0) == 30.0 with expected(TypeError, "axn_bxn"): axn_bxn(10) with expected(TypeError, "axn_bxn"): axn_bxn() def test_default_unchecked_args1(): @tc.typecheck def axn_b2n(a, b=2): return a + b assert axn_b2n(10, 20) == 30 assert axn_b2n(10, 20.0) == 30.0 assert axn_b2n(10.0, 20) == 30.0 assert axn_b2n(10.0, 20.0) == 30.0 assert axn_b2n(10) == 12 assert axn_b2n(10.0) == 12.0 with expected(TypeError, "axn_b2n"): axn_b2n() def test_default_unchecked_args2(): @tc.typecheck def a1n_b2n(a=1, b=2): return a + b assert a1n_b2n(10, 20) == 30 assert a1n_b2n(10, 20.0) == 30.0 assert a1n_b2n(10.0, 20) == 30.0 assert a1n_b2n(10.0, 20.0) == 30.0 assert a1n_b2n(10) == 12 assert a1n_b2n(10.0) == 12.0 assert a1n_b2n() == 3 def test_simple_checked_args1(): @tc.typecheck def axc_bxn(a: int, b): return a + b assert axc_bxn(10, 20) == 30 assert axc_bxn(10, 20.0) == 30.0 with expected(tc.InputParameterError("axc_bxn() has got an incompatible value for a: 10.0")): axc_bxn(10.0, 20) with expected(tc.InputParameterError("axc_bxn() has got an incompatible value for a: 10.0")): axc_bxn(10.0, 20.0) with expected(TypeError, "axc_bxn"): axc_bxn(10) with expected(TypeError, "axc_bxn"): axc_bxn() def test_simple_checked_args2(): @tc.typecheck def axn_bxc(a, b: int): return a + b assert axn_bxc(10, 20) == 30 with expected(tc.InputParameterError("axn_bxc() has got an incompatible value for b: 20.0")): axn_bxc(10, 20.0) assert axn_bxc(10.0, 20) == 30.0 with expected(tc.InputParameterError("axn_bxc() has got an incompatible value for b: 20.0")): axn_bxc(10.0, 20.0) with expected(TypeError, "axn_bxc"): axn_bxc(10) with expected(TypeError, "axn_bxc"): axn_bxc() def test_simple_default_checked_args1(): @tc.typecheck def axn_b2c(a, b: int=2): return a + b assert axn_b2c(10, 20) == 30 with expected(tc.InputParameterError("axn_b2c() has got an incompatible value for b: 20.0")): axn_b2c(10, 20.0) assert axn_b2c(10.0, 20) == 30.0 with expected(tc.InputParameterError("axn_b2c() has got an incompatible value for b: 20.0")): axn_b2c(10.0, 20.0) assert axn_b2c(10) == 12 assert axn_b2c(10.0) == 12.0 with expected(TypeError, "axn_b2c"): axn_b2c() def test_simple_default_checked_args2(): @tc.typecheck def a1n_b2c(a=1, b: int=2): return a + b assert a1n_b2c(10, 20) == 30 with expected(tc.InputParameterError("a1n_b2c() has got an incompatible value for b: 20.0")): a1n_b2c(10, 20.0) assert a1n_b2c(10.0, 20) == 30.0 with expected(tc.InputParameterError("a1n_b2c() has got an incompatible value for b: 20.0")): a1n_b2c(10.0, 20.0) assert a1n_b2c(10) == 12 assert a1n_b2c(10.0) == 12.0 assert a1n_b2c() == 3 def test_simple_default_checked_args3(): @tc.typecheck def axc_b2n(a: int, b=2):
google/google-ctf
third_party/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/json/tests/test_tool.py
Python
apache-2.0
2,037
0.000982
import os import sys import textwrap import unittest im
port subprocess from test import test_support from test.script_helper import assert_python_ok class TestTool(unittest.TestCase): data = """ [["blorpie"],[ "whoops" ] , [ ],\t"d-shtaeou",\r"d-nthiouh", "i-vhbjkhnth", {"nifty":87}, {"morefield" :\tfalse,"field" :"yes"} ] """ expect = textwrap.dedent("""\ [ [ "blo
rpie" ], [ "whoops" ], [], "d-shtaeou", "d-nthiouh", "i-vhbjkhnth", { "nifty": 87 }, { "field": "yes", "morefield": false } ] """) def test_stdin_stdout(self): proc = subprocess.Popen( (sys.executable, '-m', 'json.tool'), stdin=subprocess.PIPE, stdout=subprocess.PIPE) out, err = proc.communicate(self.data.encode()) self.assertEqual(out.splitlines(), self.expect.encode().splitlines()) self.assertEqual(err, None) def _create_infile(self): infile = test_support.TESTFN with open(infile, "w") as fp: self.addCleanup(os.remove, infile) fp.write(self.data) return infile def test_infile_stdout(self): infile = self._create_infile() rc, out, err = assert_python_ok('-m', 'json.tool', infile) self.assertEqual(out.splitlines(), self.expect.encode().splitlines()) self.assertEqual(err, b'') def test_infile_outfile(self): infile = self._create_infile() outfile = test_support.TESTFN + '.out' rc, out, err = assert_python_ok('-m', 'json.tool', infile, outfile) self.addCleanup(os.remove, outfile) with open(outfile, "r") as fp: self.assertEqual(fp.read(), self.expect) self.assertEqual(out, b'') self.assertEqual(err, b'')
patrickshuff/artofmemory
tests/test_major.py
Python
mit
489
0
"""Ensure testing of
the Major System does what we expect""" from artofmemory.major import NaiveMajorSystem, PhonemesMajorSystem def test_office(): # office shouldn't be "887" but rather actually "80"! naive_value = "887" correct_value = "80" assert NaiveMajorSystem().word_to_major("office") == naive_value assert PhonemesMajorSystem().word_to_major("office") == correct_value # Other tricky words: # passage, Alexander #
burn => 942, Nope, it is 92
dimagi/commcare-hq
corehq/ex-submodules/pillow_retry/migrations/0002_pillowerror_queued.py
Python
bsd-3-clause
372
0
from django.db import models, migrations class Migration(migrations.Migration):
dependencies = [ ('pillow_retry', '0001_initial'), ] operations = [ migrations.AddField( model_name='pillowerror', name='queued', field=models.BooleanField(default=False), preserve_defa
ult=True, ), ]
jmesteve/saas3
openerp/addons/crm/wizard/crm_merge_opportunities.py
Python
agpl-3.0
4,577
0.00284
############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either
version 3 of the # License, or (at your option) any later version. # # T
his program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv import fields, osv from openerp.tools.translate import _ class crm_merge_opportunity(osv.osv_memory): """ Merge opportunities together. If we're talking about opportunities, it's just because it makes more sense to merge opps than leads, because the leads are more ephemeral objects. But since opportunities are leads, it's also possible to merge leads together (resulting in a new lead), or leads and opps together (resulting in a new opp). """ _name = 'crm.merge.opportunity' _description = 'Merge opportunities' _columns = { 'opportunity_ids': fields.many2many('crm.lead', rel='merge_opportunity_rel', id1='merge_id', id2='opportunity_id', string='Leads/Opportunities'), 'user_id': fields.many2one('res.users', 'Salesperson', select=True), 'section_id': fields.many2one('crm.case.section', 'Sales Team', select=True), } def action_merge(self, cr, uid, ids, context=None): if context is None: context = {} lead_obj = self.pool.get('crm.lead') wizard = self.browse(cr, uid, ids[0], context=context) opportunity2merge_ids = wizard.opportunity_ids #TODO: why is this passed through the context ? context['lead_ids'] = [opportunity2merge_ids[0].id] merge_id = lead_obj.merge_opportunity(cr, uid, [x.id for x in opportunity2merge_ids], wizard.user_id.id, wizard.section_id.id, context=context) # The newly created lead might be a lead or an opp: redirect toward the right view merge_result = lead_obj.browse(cr, uid, merge_id, context=context) if merge_result.type == 'opportunity': return lead_obj.redirect_opportunity_view(cr, uid, merge_id, context=context) else: return lead_obj.redirect_lead_view(cr, uid, merge_id, context=context) def default_get(self, cr, uid, fields, context=None): """ Use active_ids from the context to fetch the leads/opps to merge. In order to get merged, these leads/opps can't be in 'Dead' or 'Closed' """ if context is None: context = {} record_ids = context.get('active_ids', False) res = super(crm_merge_opportunity, self).default_get(cr, uid, fields, context=context) if record_ids: opp_ids = [] opps = self.pool.get('crm.lead').browse(cr, uid, record_ids, context=context) for opp in opps: if opp.probability < 100: opp_ids.append(opp.id) if 'opportunity_ids' in fields: res.update({'opportunity_ids': opp_ids}) return res def on_change_user(self, cr, uid, ids, user_id, section_id, context=None): """ When changing the user, also set a section_id or restrict section id to the ones user_id is member of. """ if user_id: if section_id: user_in_section = self.pool.get('crm.case.section').search(cr, uid, [('id', '=', section_id), '|', ('user_id', '=', user_id), ('member_ids', '=', user_id)], context=context, count=True) else: user_in_section = False if not user_in_section: section_id = False section_ids = self.pool.get('crm.case.section').search(cr, uid, ['|', ('user_id', '=', user_id), ('member_ids', '=', user_id)], context=context) if section_ids: section_id = section_ids[0] return {'value': {'section_id': section_id}} # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
acabey/acabey.github.io
projects/demos/engineering.purdue.edu/scriptingwithobjects/swocode/chap7/Static4.py
Python
gpl-3.0
1,295
0.027027
#!/usr/bin/python ### Static3.py #------------------------- class Callable ---------------------------- class Callable: #(A) def __init__( self, anycallable ): #(B) self.__call__ = anycallable #(C) #---------------------------- class X ---------------------------
------ class X: #(D) def __init__( self, nn ): #(E) self.n = nn def getn( self ):
#(F) return self.n #(G) def foo(): #(H) print "foo called" #(I) foo = Callable( foo ) #(J) #-------------------- end of class definition ------------------------ xobj = X( 10 ) #(K) print xobj.getn() # 10 #(L) X.foo() # foo called #(M)
lhupfeldt/multiconf
test/utils_test.py
Python
bsd-3-clause
753
0
# Copyright (c) 2012 Lars Hupfeldt Nielsen, Hupfeldt IT # All rights reserved. This work is under a BSD license, see LICENSE.TXT. from multiconf import caller_file_line from .utils.utils import next_line_num from .utils_test_help
ers import bb, fn_aa_exp, ln_aa_exp ln_bb_exp = None def test_caller_file_line(): def cc(): global ln_bb_exp fnc, lnc = caller_file_line(2) print("fnc, l
nc:", fnc, lnc) ln_bb_exp = next_line_num() fnb, lnb, fna, lna = bb() return fnc, lnc, fnb, lnb, fna, lna fn_exp = __file__ ln_cc_exp = next_line_num() fnc, lnc, fnb, lnb, fna, lna = cc() assert fn_exp == fnc assert ln_cc_exp == lnc assert fn_exp == fnb assert ln_bb_exp == lnb
lexibrent/certificate-transparency
python/ct/client/log_client.py
Python
apache-2.0
22,405
0.000714
"""RFC 6962 client API.""" import base64 import json from ct.crypto import verify from ct.proto import client_pb2 import gflags import logging import requests import urllib import urlparse FLAGS = gflags.FLAGS gflags.DEFINE_integer("entry_fetch_batch_size", 1000, "Maximum number of " "entries to attempt to fetch in one request.") gflags.DEFINE_integer("get_entries_max_retries", 10, "Number of retries after " "which get-entries simply fails.") logging = logging.getLogger('log_client.py') class Error(Exception): pass class ClientError(Error): pass class HTTPError(Error): """Connection failed, or returned an error.""" pass class HTTPClientError(HTTPError): """HTTP 4xx.""" def __init__(self, code, reason, content, headers): super(HTTPError, self).__init__("%s (%s) %s" % (reason, content, headers)) self.code = code class HTTPServerError(HTTPError): """HTTP 5xx.""" def __init__(self, code, reason, content, headers): super(HTTPError, self).__init__("%s (%s) %s" % (reason, content, headers)) self.code = code class InvalidRequestError(Error): """Request does not comply with the CT protocol.""" pass class InvalidResponseError(Error): """Response does not comply with the CT protocol.""" pass ############################################################################### # Common utility methods and constants. # ############################################################################### _GET_STH_PATH = "ct/v1/get-sth" _GET_ENTRIES_PATH = "ct/v1/get-entries" _GET_STH_CONSISTENCY_PATH = "ct/v1/get-sth-consistency" _GET_PROOF_BY_HASH_PATH = "ct/v1/get-proof-by-hash" _GET_ROOTS_PATH = "ct/v1/get-roots" _GET_ENTRY_AND_PROOF_PATH = "ct/v1/get-entry-and-proof" _ADD_CHAIN = "ct/v1/add-chain" _ADD_PRECERT_CHAIN = "ct/v1/add-pre-chain" def _parse_sth(sth_body): """Parse a serialized STH JSON response.""" sth_response = client_pb2.SthResponse() try: sth = json.loads(sth_body) sth_response.timestamp = sth["timestamp"] sth_response.tree_size = sth["tree_size"] sth_response.sha256_root_hash = base64.b64decode(sth[ "sha256_root_hash"]) sth_response.tree_head_signature = base64.b64decode(sth[ "tree_head_signature"]) # TypeError for base64 decoding, TypeError/ValueError for invalid # JSON field types, KeyError for missing JSON fields. except (TypeError, ValueError, KeyError) as e: raise InvalidResponseError("Invalid STH %s\n%s" % (sth_bod
y, e)) return sth_response def _parse_entry(json_entry): """Convert a json array element to an EntryResponse.""" entry_response = client_pb2.EntryResponse() try: entry_response.leaf_input = base64.b64decode( json_entry["leaf_input"]) entry_response.extra_data = base64.b64decode( json_entry["extra_data"]) except (TypeError, ValueError, KeyError) as e: raise InvalidResponseError("Invalid entry: %s\n%s" % (json_entry, e)) return entry
_response def _parse_entries(entries_body, expected_response_size): """Load serialized JSON response. Args: entries_body: received entries. expected_response_size: number of entries requested. Used to validate the response. Returns: a list of client_pb2.EntryResponse entries. Raises: InvalidResponseError: response not valid. """ try: response = json.loads(entries_body) except ValueError as e: raise InvalidResponseError("Invalid response %s\n%s" % (entries_body, e)) try: entries = iter(response["entries"]) except (TypeError, KeyError) as e: raise InvalidResponseError("Invalid response: expected " "an array of entries, got %s\n%s)" % (response, e)) # Logs MAY honor requests where 0 <= "start" < "tree_size" and # "end" >= "tree_size" by returning a partial response covering only # the valid entries in the specified range. # Logs MAY restrict the number of entries that can be retrieved per # "get-entries" request. If a client requests more than the # permitted number of entries, the log SHALL return the maximum # number of entries permissible. (RFC 6962) # # Therefore, we cannot assume we get exactly the expected number of # entries. However if we get none, or get more than expected, then # we discard the response and raise. response_size = len(response["entries"]) if not response_size or response_size > expected_response_size: raise InvalidResponseError("Invalid response: requested %d entries," "got %d entries" % (expected_response_size, response_size)) return [_parse_entry(e) for e in entries] def _parse_consistency_proof(response, servername): try: response = json.loads(response) consistency = [base64.b64decode(u) for u in response["consistency"]] except (TypeError, ValueError, KeyError) as e: raise InvalidResponseError( "%s returned invalid data: expected a base64-encoded " "consistency proof, got %s" "\n%s" % (servername, response, e)) return consistency # A class that we can mock out to generate fake responses. class RequestHandler(object): """HTTPS requests.""" def __init__(self, connection_timeout=60, ca_bundle=True, num_retries=None): self._timeout = connection_timeout self._ca_bundle = ca_bundle # Explicitly check for None as num_retries being 0 is valid. if num_retries is None: num_retries = FLAGS.get_entries_max_retries self._num_retries = num_retries def __repr__(self): return "%r()" % self.__class__.__name__ def __str__(self): return "%r()" % self.__class__.__name__ def get_response(self, uri, params=None): """Get an HTTP response for a GET request.""" uri_with_params = self._uri_with_params(uri, params) num_get_attempts = self._num_retries + 1 while num_get_attempts > 0: try: return requests.get(uri, params=params, timeout=self._timeout, verify=self._ca_bundle) except requests.exceptions.ConnectionError as e: # Re-tries regardless of the error. # Cannot distinguish between an incomplete read and other # transient (or permanent) errors when using requests. num_get_attempts = num_get_attempts - 1 logging.info("Retrying fetching %s, error %s" % ( uri_with_params, e)) raise HTTPError( "Connection to %s failed too many times." % uri_with_params) def post_response(self, uri, post_data): try: return requests.post(uri, data=json.dumps(post_data), timeout=self._timeout, verify=self._ca_bundle) except requests.exceptions.RequestException as e: raise HTTPError("POST to %s failed: %s" % (uri, e)) @staticmethod def check_response_status(code, reason, content='', headers=''): if code == 200: return elif 400 <= code < 500: raise HTTPClientError(code, reason, content, headers) elif 500 <= code < 600: raise HTTPServerError(code, reason, content, headers) else: raise HTTPError("%s (%s) %s" % (reason, content, headers)) @staticmethod def _uri_with_params(uri, params=None): if not params: return uri components = list(urlparse.urlparse(uri)) if params: # Update the URI query, which is at index 4 of the tuple. components[4] = urllib.urlencode(params) return urlparse.urlunparse(components) def get_response_body(self, uri, params=None): response = self.ge
patrickwestphal/owlapy
owlapy/model/owlclassexpression.py
Python
gpl-3.0
174
0.005747
from
.owlpropertyrange import OWLPropertyRange from .swrlpredicate import SWRLPredicate class OWLClassExpression(OWLPropertyRange, SWRLPredicate): """TODO: i
mplement"""
ergo/ziggurat_foundations
ziggurat_foundations/migrations/versions/438c27ec1c9_normalize_constraint_and_key_names.py
Python
bsd-3-clause
12,558
0.001593
"""normalize constraint and key names correct keys for pre 0.5.6 naming convention Revision ID: 438c27ec1c9 Revises: 439766f6104d Create Date: 2015-06-13 21:16:32.358778 """ from __future__ import unicode_literals from alembic import op from alembic.context import get_context from sqlalchemy.dialects.postgresql.base import PGDialect import sqlalchemy as sa # revision identifiers, used by Alembic. revision = "438c27ec1c9" down_revision = "439766f6104d" # correct keys for pre 0.5.6 naming convention def upgrade(): c = get_context() insp = sa.inspect(c.connection.engine) # existing migration # pre naming convention keys groups_permissions_pkey = "groups_permissions_pkey" groups_pkey = "groups_pkey" groups_resources_permissions_pkey = "groups_resources_permissions_pkey" users_groups_pkey = "users_groups_pkey" users_permissions_pkey = "users_permissions_pkey" users_resources_permissions_pkey = "users_resources_permissions_pkey" if isinstance(c.connection.engine.dialect, PGDialect): op.execute( "ALTER INDEX groups_unique_group_name_key RENAME to ix_groups_uq_group_name_key" ) # noqa op.drop_constraint("groups_permissions_perm_name_check", "groups_permissions") op.execute( """ ALTER TABLE groups_permissions ADD CONSTRAINT ck_groups_permissions_perm_name CHECK (perm_name::text = lower(perm_name::text)); """ ) # noqa op.drop_constraint( "groups_resources_permissions_perm_name_check", "groups_resources_permissions", ) op.execute( """ ALTER TABLE groups_resources_permissions ADD CONSTRAINT ck_groups_resources_permissions_perm_name CHECK (perm_name::text = lower(perm_name::text)); """ ) # noqa op.drop_constraint("user_permissions_perm_name_check", "users_permissions") op.execute( """ ALTER TABLE users_permissions ADD CONSTRAINT ck_user_permissions_perm_name CHECK (perm_name::text = lower(perm_name::text)); """ ) # noqa op.drop_constraint( "users_resources_permissions_perm_name_check", "users_resources_permissions" ) op.execute( """ ALTER TABLE users_resources_permissions ADD CONSTRAINT ck_users_resources_permissions_perm_name CHECK (perm_name::text = lower(perm_name::text)); """ ) # noqa op.execute("ALTER INDEX users_email_key2 RENAME to ix_users_uq_lower_email") op.execute( "ALTER INDEX users_username_uq2 RENAME to ix_users_ux_lower_username" ) # noqa if ( groups_permissions_pkey == insp.get_pk_constraint("groups_permissions")["name"] ): op.execute( "ALTER INDEX groups_permissions_pkey RENAME to pk_groups_permissions" ) # noqa if groups_pkey == insp.get_pk_constraint("groups")["name"]: op.execute("ALTER INDEX groups_pkey RENAME to pk_groups") if ( groups_resources_permissions_pkey == insp.get_pk_constraint("groups_resources_permissions")["name"] ): op.execute( "ALTER INDEX groups_resources_permissions_pkey RENAME to pk_groups_resources_permissions" ) # noqa if users_groups_pkey == insp.get_pk_constraint("users_groups")["name"]: op.execute("ALTER INDEX users_groups_pkey RENAME to pk_users_groups") if ( users_permissions_pkey == insp.get_pk_constraint("users_permissions")["name"] ):
op.execute( "ALTER INDEX users_permissions_pkey RENAME to pk_users_permissions" ) # noqa if ( users_resources_permissions_pkey == insp.get_pk_constraint("users_resources_permissions")["name"] ): op.execute( "ALTER INDEX users_resources_permission
s_pkey RENAME to pk_users_resources_permissions" ) # noqa if ( "external_identities_pkey" == insp.get_pk_constraint("external_identities")["name"] ): op.execute( "ALTER INDEX external_identities_pkey RENAME to pk_external_identities" ) # noqa if "external_identities_local_user_name_fkey" in [ c["name"] for c in insp.get_foreign_keys("external_identities") # noqa ]: op.drop_constraint( "external_identities_local_user_name_fkey", "external_identities", type_="foreignkey", ) op.create_foreign_key( None, "external_identities", "users", remote_cols=["user_name"], local_cols=["local_user_name"], onupdate="CASCADE", ondelete="CASCADE", ) if "groups_permissions_group_id_fkey" in [ c["name"] for c in insp.get_foreign_keys("groups_permissions") ]: op.drop_constraint( "groups_permissions_group_id_fkey", "groups_permissions", type_="foreignkey", ) op.create_foreign_key( None, "groups_permissions", "groups", remote_cols=["id"], local_cols=["group_id"], onupdate="CASCADE", ondelete="CASCADE", ) if "groups_group_name_key" in [ c["name"] for c in insp.get_unique_constraints("groups") ]: op.execute( "ALTER INDEX groups_group_name_key RENAME to uq_groups_group_name" ) # noqa if "groups_resources_permissions_group_id_fkey" in [ c["name"] for c in insp.get_foreign_keys("groups_resources_permissions") # noqa ]: op.drop_constraint( "groups_resources_permissions_group_id_fkey", "groups_resources_permissions", type_="foreignkey", ) op.create_foreign_key( None, "groups_resources_permissions", "groups", remote_cols=["id"], local_cols=["group_id"], onupdate="CASCADE", ondelete="CASCADE", ) if "groups_resources_permissions_resource_id_fkey" in [ c["name"] for c in insp.get_foreign_keys("groups_resources_permissions") # noqa ]: op.drop_constraint( "groups_resources_permissions_resource_id_fkey", "groups_resources_permissions", type_="foreignkey", ) op.create_foreign_key( None, "groups_resources_permissions", "resources", remote_cols=["resource_id"], local_cols=["resource_id"], onupdate="CASCADE", ondelete="CASCADE", ) if "resources_pkey" == insp.get_pk_constraint("resources")["name"]: op.execute("ALTER INDEX resources_pkey RENAME to pk_resources") if "resources_owner_group_id_fkey" in [ c["name"] for c in insp.get_foreign_keys("resources") ]: op.drop_constraint( "resources_owner_group_id_fkey", "resources", type_="foreignkey" ) op.create_foreign_key( None, "resources", "groups", remote_cols=["id"], local_cols=["owner_group_id"], onupdate="CASCADE", ondelete="SET NULL", ) if "resources_owner_user_id_fkey" in [ c["name"] for c in insp.get_foreign_keys("resources") ]: op.drop_constraint( "resources_owner_user_id_fkey", "resources", type_="foreignkey" ) o
dpgaspar/Flask-AppBuilder
examples/quickcharts2/build/lib/app/views.py
Python
bsd-3-clause
5,082
0.004132
import random import logging import datetime import calendar from flask_appbuilder.models.datamodel import SQLAModel from flask_appbuilder.views import ModelView from flask_appbuilder.charts.views import DirectChartView, DirectByChartView, GroupByChartView from models import CountryStats, Country, PoliticalType from app import appbuilder, db from flask_appbuilder.models.group import aggregate_count, aggregate_sum, aggregate_avg log = logging.getLogger(__name__) def fill_data(): countries = ['Portugal', 'Germany', 'Spain', 'France', 'USA', 'China', 'Russia', 'Japan'] politicals = ['Democratic', 'Authorative'] for country in countries: c = Country(name=country) try: db.session.add(c) db.session.commit() except Exception as e: log.error("Update ViewMenu error: {0}".format(str(e))) db.session.rollback() for political in politicals: c = PoliticalType(name=political) try: db.session.add(c) db.session.commit() except Exception as e: log.error("Update ViewMenu error: {0}".format(str(e))) db.session.rollback() try: for x in range(1, 20): cs = CountryStats() cs.population = random.randint(1, 100) cs.unemployed = random.randint(1, 100) cs.college = random.randint(1, 100) year = random.choice(range(1900, 2012)) month = random.choice(range(1, 12)) day = random.choice(range(1, 28)) cs.stat_date = datetime.datetime(year, month, day) cs.country_id = random.randint(1, len(countries)) cs.political_type_id = random.randint(1, len(politicals)) db.session.add(cs) db.session.commit() except Exception as e: log.error("Update ViewMenu error: {0}".format(str(e))) db.session.rollback() class CountryStatsModelView(ModelView): datamodel = SQLAModel(CountryStats) list_columns = ['country', 'stat_date', 'population', 'unemployed', 'college'] class CountryModelView(ModelView): datamodel = SQLAModel(Country) class PoliticalTypeModelView(ModelView): datamodel = SQLAModel(PoliticalType) class CountryStatsDirectChart(DirectChartView): datamodel = SQLAModel(CountryStats) chart_title = 'Statistics' chart_type = 'LineChart' direct_columns = {'General Stats': ('stat_date', 'population', 'unemployed', 'college')} base_order = ('stat_date', 'asc') def pretty_month_year(value): return calendar.month_name[value.month] + ' ' + str(value.year) class CountryDirectChartView(DirectByChartView): datamodel = SQLAModel(CountryStats) chart_title = 'Direct Data' definitions = [ { #'label': 'Monthly', 'group': 'stat_date', 'series': ['unemployed', 'population', 'college'] } ] class CountryGroupByChartView(GroupByChartView): datamodel = SQLAModel(CountryStats) chart_title = 'Statistics' definitions = [ { 'label': 'Country Stat', 'g
roup': 'country', 'series': [(aggregate_avg, 'unemployed'), (aggre
gate_avg, 'population'), (aggregate_avg, 'college') ] }, { #'label': 'Monthly', 'group': 'month_year', 'formatter': pretty_month_year, 'series': [(aggregate_avg, 'unemployed'), (aggregate_avg, 'population'), (aggregate_avg, 'college') ] } ] """ [{ 'label': 'String', 'group': '<COLNAME>'|'<FUNCNAME>' 'formatter: <FUNC> 'series': [(<AGGR FUNC>, <COLNAME>|'<FUNCNAME>'),...] } ] """ #label_columns = {'month_year': 'Month Year', 'country_political': 'Country Political'} group_by_columns = ['country', 'political_type', 'country_political', 'month_year'] # ['<COL NAME>'] aggregate_by_column = [(aggregate_avg, 'unemployed'), (aggregate_avg, 'population'), (aggregate_avg, 'college')] # [{'aggr_func':<FUNC>,'column':'<COL NAME>'}] formatter_by_columns = {'month_year': pretty_month_year} db.create_all() fill_data() appbuilder.add_view(CountryModelView, "List Countries", icon="fa-folder-open-o", category="Statistics") appbuilder.add_view(PoliticalTypeModelView, "List Political Types", icon="fa-folder-open-o", category="Statistics") appbuilder.add_view(CountryStatsModelView, "List Country Stats", icon="fa-folder-open-o", category="Statistics") appbuilder.add_separator("Statistics") appbuilder.add_view(CountryStatsDirectChart, "Show Country Chart", icon="fa-dashboard", category="Statistics") appbuilder.add_view(CountryGroupByChartView, "Group Country Chart", icon="fa-dashboard", category="Statistics") appbuilder.add_view(CountryDirectChartView, "Show Country Chart", icon="fa-dashboard", category="Statistics")
ioos/comt
python/pyugrid_test.py
Python
mit
3,158
0.00665
# coding: utf-8 # ##Test out UGRID-0.9 compliant unstructured grid model datasets with PYUGRID # In[1]: name_list=['sea_surface_elevation', 'sea_surface_height_above_geoid', 'sea_surface_height','water level', 'sea_surface_height_above_sea_level', 'water_surface_height_above_reference_datum', 'sea_surface_height_above_reference_ellipsoid'] models = dict(ADCIRC=('http://comt.sura.org/thredds/dodsC/data/comt_1_archive/inundation_tropical/' 'UND_ADCIRC/Hurricane_Ike_2D_final_run_with_waves'), FVCOM=('http://www.smast.umassd.edu:8080/thredds/dodsC/FVCOM/NECOFS/' 'Forecasts/NECOFS_GOM3_FORECAST.nc'), SELFE=('http://comt.sura.org/thredds/dodsC/data/comt_1_archive/inundation_tropical/' 'VIMS_SELFE/Hurricane_Ike_2D_final_run_with_waves'), WW3=('http://comt.sura.org/thredds/dodsC/data/comt_2/pr_inundation_tropical/EMC_ADCIRC-WW3/' 'Dec2013Storm_2D_preliminary_run_1_waves_only')) # In[2]: import iris iris.FUTURE.netcdf_promote = True def cube_func(cube): return (cube.standard_name in name_list) and (not any(m.method == 'maximum' for m in cube.cell_methods)) constraint = iris.Constraint(cube_func=cube_func) cubes = dict() for model, url in models.items(): cube = iris.load_cube(url, constraint) cubes.update({model: cube}) # In[3]: cubes # In[4]: import pyugrid import matplotlib.tri as tri def get_mesh(cube, url): ug = pyugrid.UGrid.
from_ncfile(url) cube.mesh = ug cube.mesh_dimension = 1 return cube def get_triang(cube): lon = cube.mesh.nodes[:, 0] lat = cube.mesh.nodes[:, 1] nv = cube.mesh.faces return tri.Triangulation(lon, lat, tri
angles=nv) # In[5]: tris = dict() for model, cube in cubes.items(): url = models[model] cube = get_mesh(cube, url) cubes.update({model: cube}) tris.update({model: get_triang(cube)}) # In[6]: get_ipython().magic('matplotlib inline') import numpy as np import cartopy.crs as ccrs import matplotlib.pyplot as plt def plot_model(model): cube = cubes[model] lon = cube.mesh.nodes[:, 0] lat = cube.mesh.nodes[:, 1] ind = -1 # just take the last time index for now zcube = cube[ind] triang = tris[model] fig, ax = plt.subplots(figsize=(7, 7), subplot_kw=dict(projection=ccrs.PlateCarree())) ax.set_extent([lon.min(), lon.max(), lat.min(), lat.max()]) ax.coastlines() levs = np.arange(-1, 5, 0.2) cs = ax.tricontourf(triang, zcube.data, levels=levs) fig.colorbar(cs) ax.tricontour(triang, zcube.data, colors='k',levels=levs) tvar = cube.coord('time') tstr = tvar.units.num2date(tvar.points[ind]) gl = ax.gridlines(draw_labels=True) gl.xlabels_top = gl.ylabels_right = False title = ax.set_title('%s: Elevation (m): %s' % (zcube.attributes['title'], tstr)) return fig, ax # In[7]: fig, ax = plot_model('ADCIRC') # In[8]: fig, ax = plot_model('FVCOM') # In[9]: fig, ax = plot_model('WW3') # In[10]: fig, ax = plot_model('SELFE')
SvetoslavKuzmanov/altimu10v5
altimu10v5/lsm6ds33.py
Python
mit
6,967
0.000431
# -*- coding: utf-8 -*- """Python library module for LSM6DS33 accelerometer and gyroscope. This module for the Raspberry Pi compu
ter helps interface the LSM6DS33 accelerometer and gyro.The library makes it
easy to read the raw accelerometer and gyro data through I²C interface and it also provides methods for getting angular velocity and g forces. The datasheet for the LSM6DS33 is available at [https://www.pololu.com/file/download/LSM6DS33.pdf?file_id=0J1087] """ import math from i2c import I2C from time import sleep from constants import * class LSM6DS33(I2C): """ Set up and access LSM6DS33 accelerometer and gyroscope. """ # Output registers used by the gyroscope gyro_registers = [ LSM6DS33_OUTX_L_G, # low byte of X value LSM6DS33_OUTX_H_G, # high byte of X value LSM6DS33_OUTY_L_G, # low byte of Y value LSM6DS33_OUTY_H_G, # high byte of Y value LSM6DS33_OUTZ_L_G, # low byte of Z value LSM6DS33_OUTZ_H_G, # high byte of Z value ] # Output registers used by the accelerometer accel_registers = [ LSM6DS33_OUTX_L_XL, # low byte of X value LSM6DS33_OUTX_H_XL, # high byte of X value LSM6DS33_OUTY_L_XL, # low byte of Y value LSM6DS33_OUTY_H_XL, # high byte of Y value LSM6DS33_OUTZ_L_XL, # low byte of Z value LSM6DS33_OUTZ_H_XL, # high byte of Z value ] def __init__(self, bus_id=1): """ Set up I2C connection and initialize some flags and values. """ super(LSM6DS33, self).__init__(bus_id) self.is_accel_enabled = False self.is_gyro_enabled = False self.is_gyro_calibrated = False self.gyro_cal = [0, 0, 0] self.is_accel_calibrated = False self.accel_angle_cal = [0, 0] def __del__(self): """ Clean up.""" try: # Power down accelerometer and gyro self.writeRegister(LSM6DS33_ADDR, LSM6DS33_CTRL1_XL, 0x00) self.writeRegister(LSM6DS33_ADDR, LSM6DS33_CTRL2_G, 0x00) super(LSM6DS33, self).__del__() print('Destroying') except: pass def enable(self, accelerometer=True, gyroscope=True, calibration=True): """ Enable and set up the given sensors in the IMU.""" if accelerometer: # 1.66 kHz (high performance) / +/- 4g # binary value -> 0b01011000, hex value -> 0x58 self.write_register(LSM6DS33_ADDR, LSM6DS33_CTRL1_XL, 0x58) self.is_accel_enabled = True if gyroscope: # 208 Hz (high performance) / 1000 dps # binary value -> 0b01011000, hex value -> 0x58 self.write_register(LSM6DS33_ADDR, LSM6DS33_CTRL2_G, 0x58) self.is_gyro_enabled = True if calibration: self.calibrate() self.is_gyro_calibrated = True self.is_accel_calibrated = True def calibrate(self, iterations=2000): """ Calibrate the gyro's raw values.""" print('Calibrating Gryo and Accelerometer...') for i in range(iterations): gyro_raw = self.get_gyroscope_raw() accel_angles = self.get_accelerometer_angles() self.gyro_cal[0] += gyro_raw[0] self.gyro_cal[1] += gyro_raw[1] self.gyro_cal[2] += gyro_raw[2] self.accel_angle_cal[0] += accel_angles[0] self.accel_angle_cal[1] += accel_angles[1] sleep(0.004) self.gyro_cal[0] /= iterations self.gyro_cal[1] /= iterations self.gyro_cal[2] /= iterations self.accel_angle_cal[0] /= iterations self.accel_angle_cal[1] /= iterations print('Calibration Done') def get_gyroscope_raw(self): """ Return a 3D vector of raw gyro data. """ # Check if gyroscope has been enabled if not self.is_gyro_enabled: raise(Exception('Gyroscope is not enabled!')) sensor_data = self.read_3d_sensor(LSM6DS33_ADDR, self.gyro_registers) # Return the vector if self.is_gyro_calibrated: calibrated_gyro_data = sensor_data calibrated_gyro_data[0] -= self.gyro_cal[0] calibrated_gyro_data[1] -= self.gyro_cal[1] calibrated_gyro_data[2] -= self.gyro_cal[2] return calibrated_gyro_data else: return sensor_data def get_gyro_angular_velocity(self): """ Return a 3D vector of the angular velocity measured by the gyro in degrees/second. """ # Check if gyroscope has been enabled if not self.is_gyro_enabled: raise(Exception('Gyroscope is not enabled!')) # Check if gyroscope has been calibrated if not self.is_gyro_calibrated: raise(Exception('Gyroscope is not calibrated!')) gyro_data = self.get_gyroscope_raw() gyro_data[0] = (gyro_data[0] * GYRO_GAIN) / 1000 gyro_data[1] = (gyro_data[1] * GYRO_GAIN) / 1000 gyro_data[2] = (gyro_data[2] * GYRO_GAIN) / 1000 return gyro_data def get_accelerometer_raw(self): """ Return a 3D vector of raw accelerometer data. """ # Check if accelerometer has been enabled if not self.is_accel_enabled: raise(Exception('Accelerometer is not enabled!')) return self.read_3d_sensor(LSM6DS33_ADDR, self.accel_registers) def get_accelerometer_g_forces(self): """ Return a 3D vector of the g forces measured by the accelerometer""" [x_val, y_val, z_val] = self.get_accelerometer_raw() x_val = (x_val * ACCEL_CONVERSION_FACTOR) / 1000 y_val = (y_val * ACCEL_CONVERSION_FACTOR) / 1000 z_val = (z_val * ACCEL_CONVERSION_FACTOR) / 1000 return [x_val, y_val, z_val] def get_accelerometer_angles(self, round_digits=0): """ Return a 2D vector of roll and pitch angles, based on accelerometer g forces """ # Get raw accelerometer g forces [acc_xg_force, acc_yg_force, acc_zg_force] = self.get_accelerometer_g_forces() # Calculate angles xz_dist = self._get_dist(acc_xg_force, acc_zg_force) yz_dist = self._get_dist(acc_yg_force, acc_zg_force) accel_roll_angle = math.degrees(math.atan2(acc_yg_force, xz_dist)) accel_pitch_angle = -math.degrees(math.atan2(acc_xg_force, yz_dist)) if self.is_accel_calibrated: accel_roll_angle -= self.accel_angle_cal[0] accel_pitch_angle -= self.accel_angle_cal[1] if round_digits != 0: return [round(accel_roll_angle, round_digits), round(accel_pitch_angle, round_digits)] else: return [accel_roll_angle, accel_pitch_angle] else: return [accel_roll_angle, accel_pitch_angle] def _get_dist(self, a, b): return math.sqrt((a * a) + (b * b))