prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
#!/usr/bin/env python """ @package mi.dataset.parser.test @fid mi-instrument/mi/dataset/parser/test/test_ctdav_nbosi_auv.py @author Rene Gelinas @brief Test code for a ctdav_nbosi_auv data parser """ import os from nose.plugins.attrib import attr from mi.core.log import get_logger from mi.dataset.driver.ctdav_nbosi...
Parser(stream_handle, self.exception_callback) particles = parser.get_records(20) self.assert_particles(particles, 'ctdav_nbosi_auv.yml', RESOURCE_PATH) self.assertEqual(self.exception_callback_value, []) stream_handle.close() def test_long_strea...
handle = open(os.path.join(RESOURCE_PATH, 'CP05MOAS-A6264_AUVsubset.csv'), 'rU') parser = CtdavNbosiAuvParser(stream_handle, self.exception_callback) particles = parser.get_records(10000) self.assertEqual(len(particles), 10000) self.assertEqual(self.e...
for ip in port['fixed_ips']] return port_dict class NeutronRestProxyV2Base(db_base_plugin_v2.NeutronDbPluginV2, external_net_db.External_net_db_mixin): supported_extension_aliases = ["binding"] servers = None @property def l3_plugin(self): ...
_get_mapped_network_with_subnets(net) flips_n_ports = mapped_network if get_floating_ips: flips_n_ports = self._get_network_with_floatingips(
mapped_network) if get_ports: ports = [] net_filter = {'network_id': [net.get('id')]} net_ports = plugin.get_ports(admin_context, filters=net_filter) or [] for port in net_ports: ...
es=25): randomSeed(0) drawBot.newDrawing() for i in range(numFrames): drawBot.newPage(500, 500) drawBot.frameDuration(1/25) drawBot.fill(1) drawBot.rect(0, 0, 500, 500) drawBot.fill(0) drawBot.rect(random.randint(0, 100), ra...
ual(drawBot.imageSize(tmp.path), (125, 125)) def test_imagePNGInterlaced(self): self.makeTestDrawing() defaultSize = self._saveImageAndReturnSize(".png") interlacedSize = self._saveImageAndReturnSize(".png", imagePNGInterlaced=True) # XXX Huh, seems to make no difference, output fil...
nterlacedSize) def test_imagePNGGamma(self): self.makeTestDrawing() defaultSize = self._saveImageAndReturnSize(".png") gammaSize = self._saveImageAndReturnSize(".png", imagePNGGamma=0.8) self.assertLess(defaultSize, gammaSize) def test_imageJPEGProgressive(self): self.m...
ire their stock levels to be #: tracked. track_stock = models.BooleanField(_("Track stock levels?"), default=True) #: These are the options (set by the user when they add to basket) for this #: item class. For instance, a product class of "SMS message" would always #: require a message to be speci...
null=True, max_length=255) slug = SlugField(_('Slug'), max_length=255, db_index=True) _slug_separator = '/' _full_name_separator = ' > ' def __str__(self): return self.full_name @property def full_name(self): """ Returns a string representation ...
programming'. It's rarely used in Oscar's codebase, but used to be stored as a CharField and is hence kept for backwards compatibility. It's also sufficiently useful to keep around. """ names = [category.name for category in self.get_ancestors_and_self()] return self._fu...
(self, start_item=0, max_items=50): return self._send_cmd_response(SonosCommand.favradio(start_item, max_items)) def version(self): return "v1.3\t2015-01-18" class SonosSpeaker(): def __init__(self): self.uid = [] self.ip = [] self.model = [] self.zone_name = [...
ac_address = [] self.playlist_position = [] self.volume = [] self.mute = [] self.led = [] self.streamtype = [] self.stop = [] self.pl
ay = [] self.pause = [] self.track_title = [] self.track_artist = [] self.track_duration = [] self.track_position = [] self.track_album_art = [] self.track_uri = [] self.radio_station = [] self.radio_show = [] self.status = [] self....
# ------------------------------------------------------------------------------ # Security Central # ------------------------------------------------------------------------------ from .models import User from pyramid.security import Allow, Everyone, Authenticated, ALL_PERMISSIONS from pyramid.authentication import Se...
------------------------------------------------------------- def includeme(config): """Set up the authentication and authorization policies""" authnPolicy = SessionAuthenticationPolicy(callback=getGroups) authzPolicy = ACLAuthorizationPolicy() con
fig.set_authentication_policy(authnPolicy) config.set_authorization_policy(authzPolicy) config.set_root_factory(Root) # Custom predicates config.add_view_predicate("userNeedsVerification", UserNeedsVerificationPredicate) log.info("security set up") # -----------------...
from nltk.tokenize import sent_tokenize,word_tokenize from nltk.corpus import stopwords from collections import defaultdict from string import punctuation from heapq import nlargest import re """ Modified from http://glowingpython.blogspot.co.uk/2014/09/text-summarization-with-nltk.html """ class FrequencySummarizer...
sent: if w in self._freq and len(w)>4: #Only count words of length>4 as significant ranking[i] += self._freq[w] sentsindx = self._rank(ranking, n) return [sents[j].encode('ascii', errors='backslashreplace') for j in sentsindx] def _rank(self, ranking, n): """ return the first n se...
h highest ranking """ return nlargest(n, ranking, key=ranking.get)
lf._types_of_builtin_functions return library def _get_declarations(self): lst = [(key, tp) for (key, (tp, qual)) in self.ffi._parser._declarations.items()] lst.sort() return lst def _generate(self, step_name): for name, tp in self._get_d...
lue)) self._prnt(' %s;' % errcode) def _extra_local_variables(self, tp, localvars, freelines): if isinstance(tp, model.PointerType): localvars.add('Py_ssize_t datasize') localvars.add('struct _cffi_freeme_s *large_args_free = NULL') freelines.add('if (large_ar...
prnt(' datasize = _cffi_prepare_pointer_call_argument(') self._prnt(' _cffi_type(%d), %s, (char **)&%s);' % ( self._gettypenum(tp), fromvar, tovar)) self._prnt(' if (datasize != 0) {') self._prnt(' %s = ((size_t)datasize) <= 640 ? ' 'alloca((size_t)datasi...
# -*- coding: utf-8 -*- # Generated by Django 1.10a1 on 2016-06-19 04:22 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='post', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('timestamp', models...
.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ]
"""Support for monitoring Repetier Server Sensors.""" from datetime import datetime import logging import time from homeassistant.components.sensor import SensorDeviceClass, SensorEntity from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from . import REPETIE...
art = data["from_start"] time_end = start + round(print_time, 0) self._state = datetime.utcfromtimestamp(time_end) remaining = print_time - from_start
remaining_secs = int(round(remaining, 0)) _LOGGER.debug( "Job %s remaining %s", job_name, time.strftime("%H:%M:%S", time.gmtime(remaining_secs)), ) class RepetierJobStartSensor(RepetierSensor): """Class to create and populate a Repetier Job Start timestamp...
# lesson4/exercises.py # Control flow and conditionals # # This file contains exercises about Python conditionals. # Last lesson, we encountered the boolean type. # Python uses booleans to evaluate conditions. # Last time, we directly assigned boolean values True and False, but booleans are # also returned by compari...
on operators, the most common ones are: # == for equality # != for inequality #
> for greater than # < for less than # >= for greater than or equal # <= for less than or equal # # Don't mistake the == operator with the = operator that we learned when studying # variables. # The == operator (equal to) asks whether two values are the same as each other and # returns a boolean (True or False) ...
import FlicketUser, FlicketGroup from app
lication.flicket.scripts.hash_password im
port hash_password admin = 'admin' # configuration defaults for flicket flicket_config = {'posts_per_page': 50, 'allowed_extensions': ['txt', 'log', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'msg', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx'], 'ti...
#!/usr/bin/env python # -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # ---------------------------------------------...
:: MIT License', ] DEPENDENCIES = [
'azure-cli-acr', 'azure-cli-acs', 'azure-cli-appservice', 'azure-cli-batch', 'azure-cli-backup', 'azure-cli-billing', 'azure-cli-cdn', 'azure-cli-cloud', 'azure-cli-cognitiveservices', 'azure-cli-component', 'azure-cli-container', 'azure-cli-configure', 'azure-cli-cons...
NotImplementedError def clear(self): """ Forget about objects in the collection. """ self.listing = {} def find(self, name=None, return_list=False, no_errors=False, **kargs): """ Return first object in the collection that maches all item='value' pairs pa...
ith either. Thankfully we don'
t have a LOT to remap. """ newhash = {} for x in hash.keys(): if self.SEARCH_REKEY.has_key(x): newkey = self.SEARCH_REKEY[x] newhash[newkey] = hash[x] else: newhash[x] = hash[x] return newhash def to_datastruct(self)...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file './viewer.ui' # # Created: Sun Aug 23 04:04:27 2009 # by: PyQt4 UI code generator 4.4.2 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui class Ui_MainWindow(object): def setupUi(self, MainWin...
etText(QtGui.QApplication.translate("MainWindow", "[image]", None, QtGui.QApplication.UnicodeUTF8)) self.commandCheck.setText(QtGui.QApplication.translate("MainWindow", "Command", None, QtGui.QApplication.UnicodeUTF8)) self.commandEdit.setText(QtGui.QApplication.t
ranslate("MainWindow", "xmms -p", None, QtGui.QApplication.UnicodeUTF8)) self.centeredCheck.setText(QtGui.QApplication.translate("MainWindow", "Centered", None, QtGui.QApplication.UnicodeUTF8)) self.playButton.setText(QtGui.QApplication.translate("MainWindow", "Play", None, QtGui.QApplication.UnicodeUTF...
# -*- coding: utf-8 -*- """ Utility that imports a function. """ # Future from __future__ import absolute_import, division, print_function, \ uni
code_literals, with_statement def import_function(function): """Imports function given by qualified package name""" function = __import__(function, globals(), locals(), ['function'], 0).f # function = getattr(__import__(function["module"], globals(), locals(), ['function'], 0), function["name"]) TODO ...
tion # Also note this always imports the function "f" as "function". return function
#!/usr/bin/env python3 """ >>> baralho = Baralho() >>> len(baralho) 52 >>> baralho[0] Carta(valor='2', naipe='paus') >>> baralho[-1] Carta(valor='A', naipe='espadas') >>> from random import choice >>> choice(baralho) #doctest:+SKIP Carta(valor='4', naipe='paus') ...
>>> baralho[:5] #doctest:+NORMALIZE_WHITESPACE [Carta(valor='2', naipe='paus'), Carta(valor='3', naipe='paus'), Carta(valor='4', naipe='paus'), Carta(valor='5', naipe='paus'), Carta(valor='6', naipe='paus')] >>> baralho[-3:] #doctest:+NORMALIZE_WHITESPACE ...
#doctest:+ELLIPSIS ... print(carta) ... Carta(valor='2', naipe='paus') Carta(valor='3', naipe='paus') Carta(valor='4', naipe='paus') ... Carta(valor='Q', naipe='espadas') Carta(valor='K', naipe='espadas') Carta(valor='A', naipe='espadas') To generate a reversed listing...
md5_source = self.session.cmd("%s %s" % (params["md5_cmd"], source_file)) try: md5_source = md5_source.split(" ")[0] except IndexError: error.TestError("Failed to get md5 from source file," ...
lean(self): clean_cmd = "%s %s" % (params["clean_cmd"], dest_file) self.session.cmd(clean_cmd) if self.dest_dir:
self.session.cmd("umount %s" % self.dest_dir) self.session.close() class Multihost(MiniSubtest): def test(self): error.context("Preparing migration env and floppies.") mig_protocol = params.get("mig_protocol", "tcp") self.mig_type = utils_te...
ch callback.cli/callback.C class TestCallbackResults(unittest.TestCase): def test_get_item(self): cb = CallbackBase() results = {'item': 'some_item'} res = cb._get_item(results) self.assertEquals(res, 'some_item') def test_get_item_no_log(self): cb = CallbackBase() ...
_header': 'generated from template somefile.j2', 'before': 'one\ntwo\nthree', 'after': 'one\ntwo\nthree\n', })), textwrap.dedent('''\ --- before: somefile.txt +++ after: generated from template somefile.j2 @@ -1,3 +1...
e +three ''')) def test_no_trailing_newline_after(self): self.assertMultiLineEqual( self._strip_color(self.cb._get_diff({ 'before_header': 'somefile.txt', 'after_header': 'generated from template somefile.j2', 'before'...
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2014 KenV99 # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any l...
5 = 101 VK_NUMPAD6 = 102 VK_NUMPAD7 = 103 VK_NUMPAD8 = 104 VK_NUMPAD9 = 105 VK_F1 = 112 VK_F2 = 113 VK_F3 = 114 VK_F4 = 115 VK_F5 = 116 VK_F6 = 117 VK_F7 = 118 VK_F8 = 119 VK_F9 = 120 VK_F10 = 121 VK_F11 = 122 VK_F12 = 123 VK_F13 = 124 VK_F14 = 125 VK_F15 = 126 VK_F16 = 127 VK_F17 = 128 VK_F18 = 129 VK_F19 = 130 VK_F20...
ALT = 1 MOD_CONTROL = 2 MOD_SHIFT = 4 MOD_WIN = 8
#!/usr/bin/python # -*- coding: utf-8 -*- """ This file is part of XBMC Mega Pack Addon. Copyright (C) 2014 Wolverine (xbmcmegapack@gmail.com) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Softwar...
Togo(): '''Class that manages this specific menu context.'
'' def open(self, plugin, menu): menu.add_xplugins(plugin.get_xplugins(dictionaries=["Channels", "Events", "Live", "Movies", "Sports", "TVShows"], countries=["Togo"]))
from joueur.delta_mergeable import DeltaMergeable from joueur.base_game_object import BaseGameObject from joueur.utilities import camel_case_converter from joueur.serializer import is_game_object_reference, is_object # @class GameManager: managed the game and it's game objects including unserializing deltas class Game...
_key = key # array's keys are real numbers, not strings e.g. "1" key_in_state = False if isinstance(state, list): state_key = int(key) key_in_state = state_key < len(state) else: if isinstance(state, DeltaMergeable): ...
if d == self._DELTA_REMOVED: value = None if key_in_state: del state[state_key] elif is_game_object_reference(d): # then this is a shallow reference to a game object value = self.game.get_game_object(d['id']) elif is_object(d) ...
from .entity import Entity class Edge
(Entity): """Basic class for all edge objects""" meta = { "ontology": "gch", "typename": "Edge", "hierarchy": "gch/Entity.Edge" } def __init__(self, attributes={}, tags=set([])):
super(Edge, self).__init__(attributes, tags)
# -------------------------------------------------------- # Theano @ Dragon # Copyright(c) 2017 SeetaTech # Written by Ting Pan # --------------------------------------------------------
import numpy as np import dragon.core.workspace as ws from dragon.core.tensor import Tensor, GetTensorName def shared(value, name=None, **kwargs): """Construct a Tensor initialized with ``value``. Parameters ---------- value : basic type, list or numpy.ndarray The numerical values. name...
The initialized tensor. """ if not isinstance(value, (int, float, list, np.ndarray)): raise TypeError("Unsupported type of value: {}".format(type(value))) if name is None: name = GetTensorName() tensor = Tensor(name).Variable() ws.FeedTensor(tensor, value) return tensor
impo
rt os def generate_enum(path, localizations): full_path = path + "/" + "Language.swift" if not os.path.isfile(full_path): enum_file = open(full_path, 'w+') enum_file.write("import Foundation\n\n") enum_file.write("enum Language: String {\n") enum_file.write("\tprivate static l...
eKey = \"AppleLanguages\"\n") enum_file.write("\tprivate static var currentLanguage: Language?\n\n") for localization in localizations: enum_file.write("\tcase " + localization + " = \"" + localization + "\"\n") enum_file.write("\tcase Undefined = \"\"\n\n") enum_file.write...
s and variables of other packages. Scheme of the db ---------------- # {'function_name': # {'variables': # {'variable_name': # {'question_info': # {'qtype': ['simple_input', 'confirmation_question', # 'selection_options', 'selection_list_options'], # ...
desc_2_level = ['agg_description', 'agg_name'] vars_2_level = ['question_info', 'default'] vars_3_level = ['qtype', 'question_spec'] # Messages of errors m0 = "The given database of functions is not a dictionary." m1 = "The function '%s' does not have "+str(first_level)+" as keys." m2 = "The va...
t question_info format for function %s and variable %s." m5 = "Not a string the 'qtype' of function %s and variable %s." m6 = "Incorrect 'question_spec' format for function %s and variable %s." m7 = "Descendants of the function %s is not a list." m8 = "Elements of the list of descendants not a dict for ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function, absolute_import import unittest from ..morf import analyze, disambiguate # EINO SANTANEN. Muodon vanhimmat # http://luulet6lgendus.blogspot.com/ sentences = '''KÕIGE VANEM MUDEL Pimedas luusivad robotid, originaalsed tšehhi robotid kahe...
kauguse
s, mattudes vastuoludesse, muutudes peaaegu julmaks oma õiglusejanus. Robota! Kui päike pageb monoliitide kohalt, tähistavad nad vägisi öö salajast geomeetriat. Õudne on inimesel vaadata neid metsikuid mudeleid. Kuuntele, romantiikkaa, 2002'''.split('\n') class TestDisambiguator(unittest.TestCase): """Test the s...
from django.core.management.base import BaseCommand, CommandError from optparse import make_option from django.template.loader import render_to_string from django.conf import settings from preferences.models import UserPreferences from summaries.models import Unseen from django.contrib.sites.models import Site from op...
ew links for you:" % len(unseen_links) email_body_txt = render_to_string("summaries/body.txt", { "user": user, "links": unseen_links, "site": Site.objects.get_current() }) email_body_
html = render_to_string("summaries/body.html", { "user": user, "links": unseen_links, "site": Site.objects.get_current() }) email = EmailMultiAlternatives( email_title, email_body_txt, ...
# -*- coding: utf-8 -*- # # Modoboa documentation build configuration file, created by # sphinx-quickstart on Mon Jan 3 22:29:25 2011. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All...
he version info for the project you're documenting, acts a
s replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '1.6' # The full version, including alpha/beta/rc tags. release = '1.6.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supp...
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2016-11-03 14:00 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ (
'restaurant', '0009_permission'), ] operations = [ migrations.AlterModelOptions( name='permission', options={'permissions': (('isC
ook', 'Can see the cooks page'), ('isWaiter', 'Can see the waiter page'), ('isCashier', 'Can see the cashier page'))}, ), ]
#!/usr/bin/env python from setuptools import setup, find_packages # get requirements.txt with open('requirements.txt') as f: required = f.read().splitlines() setup(name='athos-core', description = 'Athos project core', url = 'https://github.com/AthosOrg/', packages = find_packages(), entry_points...
] }, install_requires = required,
package_data = {'athos': ['default.yml']} )
.files import uncommented_lines from fabtools.utils import run_as_root # Python2 and 3 compatibility from past.builtins import basestring def exists(name): """ Check if a user exists. """ with settings(hide('running', 'stdout', 'warnings'), warn_only=True): return run('getent passwd %(name)s'...
with open(filename) as public_key_file: public_key = public_key_file.read().strip() # we don't use fabric.contrib.files.append() as it's buggy if public_key not in authorized_keys(name): sudo('echo %s >>%s' % (quote(public_key), quote(...
"" from fabtools.require.files import ( directory as _require_directory, file as _require_file, ) ssh_dir = posixpath.join(home_directory(name), '.ssh') _require_directory(ssh_dir, mode='700', owner=name, use_sudo=True) known_hosts_filename = posixpath.join(ssh_dir, 'known_hosts')...
import mut
able_attr import unittest class T(unittest.TestCase): def test_foo(self): mutable_attr.y =
3
from ctypes import * import unittest import sys class Test(unittest.TestCase): def test_array2pointer(self): array = (c_int * 3)(42, 17, 2) # casting an array to a pointer works. ptr = cast(array, POINTER(c_int)) self.assertEqual([ptr[i] for i in range(3)], [42, 17, 2]) i...
:], [1, 2, 96, 4]) self.assertEqual(p[3:-1:-1], [4, 96, 2, 1]) self.assertEqual(p[:4:3], [1, 4]) c_int() self.assertEqual(p[:4], [1, 2, 96, 4]) self.assertEqual(p[:4:], [1, 2, 96, 4]) self.assertEqual(p[3:-1:-1], [4, 96, 2, 1]) self.assertEqual(p[:4:3], [1, 4]) ...
b"hiho") try: c_wchar_p except NameError: pass else: def test_wchar_p(self): s = c_wchar_p("hiho") self.assertEqual(cast(cast(s, c_void_p), c_wchar_p).value, "hiho") if __name__ == "__main__": uni...
', # SET THIS! 'component': component, #"Database Queries", # SET THIS! 'version': 'unspecified', 'blocked': '', # SET THIS! (to tracking bug or empty for no tracking bug) 'op_sys': 'All', 'rep_platform': 'All', } base_url = "https://bugzilla.wikimedia.org/xmlrpc.cgi" saveMigrat...
return h.handle(html) users = {} try: f = open('user-email-mapping.json', 'r') users = json.load(f) except Exception, e: print e def getBZuser(email, name): global user
s if not email: email = name + "@invalid" if email in users: return users[email] try: user = bz.getuser(email) users[email] = email return email except bugzilla.xmlrpclib.Fault, e: if e.faultCode == 51: pass else: raise ...
#!/usr/bin/env python # -*- coding: UTF-8 -*- # If this page isn't working, try executing `chmod +x app.py` in terminal. # enable debugging import cgitb, cgi; cgitb.enable() from classes import Factory fieldStorage = cgi.FieldStorage() factory = Factory.Factory()
webApp = factory.makeWebApp(fieldStorage) def outputHeaders(): print "Content-Type: text/html" print # signals
end of headers outputHeaders() print webApp.getOutput()
# -*- coding: utf-8 -*- def get_instance_children(obj, depth=0, sig=0): """ Récupèration récursive des relations enfants d'un objet
@depth: integer limitant le niveau de recherche des enfants, 0=illimité """ children = [] # Pour toute les relations enfants de l'objet for ch
ild in obj._meta.get_all_related_objects(): # Nom de l'attribut d'accès cname = child.get_accessor_name() verbose_name = child.model._meta.verbose_name # Récupère tout les objets des relations for elem in getattr(obj, cname).all(): followed = [] # Recherch...
from django.test import TestCase from bookstore.models import Book, Ca
tegory class InventoryModelTest(TestCase): def test_string_representation_of_categories(self): category = Category.objects.create(name="health", description="health category") self.assertEqual(category.name, 'health') def test_string_representation_of_books(self): test_category2 = Ca...
fields.many2one('product.pricelist', 'Pricelist', help='Pricelist of the selected partner.'), 'partner_invoice_id': fields.many2one('res.partner', 'Invoicing Address'), 'invoice_method': fields.selection([ ("none", "No Invoice"), ("b4repair", "Before Repair"), ("after...
ue': { 'address_id': False, 'partner_invoice_id': False, 'pricelist_id': pricelist_obj.search(cr, uid, [], limit=1)[0] } } addr = part_obj.address_get(cr, uid, [part], ['delivery', 'invoice', 'contact']) ...
partner.property_product_pricelist and partner.property_product_pricelist.id or False return {'value': { 'address_id': addr['delivery'] or addr['contact'], 'partner_invoice_id': addr['invoice'], 'pricelist_id': pricelist } } ...
""" Test using HAR files in Python tests against the Django ReST framework. """ from django import http from rest_framework import response from test_har import django_rest_har as test_har from test_har import tests class HARDogfoodDRFTests(tests.HARDogfoodTestCase, test_har.HARTestCase): """ Test using HA...
nst the Django ReST framework. """ RESPONSE_TYPE = (http.HttpResponse, response.Response) def test_runner(self): """ Ens
ure tests are running. """ self.assertTrue(True)
pty if False. hidden_c (set): columns that should be hidden. squash_c (bool): column is removed if True or empty if False. colsize (dict): mapping column index to its required width. width (int): total width of the table. height (int): total heigth of the table. nrows (i...
for c in range(self.ncols): cz = self.colsize.get(c, 0) if len(rr) > 0 else 0 self.colsize[c] = max(cz, self.getcolsize(c, rr, squash=False)) def getcolsize(self, c, rr=None, squash=True): "compute the given column width (over rr
list of row indices if not None.)" cz = 0 if not rr: rr = range(self.nrows) for i in rr: if self.rowparams["squash_c"] and (i in self.hidden_r): if squash: continue cz = max(cz, self.rows[i].colsize(c)) return cz ...
''' Takes file names from the final/ folder and parses the information into readable values and produces statistical measures. Use this modul
e as an executable to process all result information for a single problem, such as: python stats.py final/multiply*.dat Do not mix problems in a single run. NOTE: You CANNOT
use pypy for this as scipy is current unsupported. Use python 2.7 instead. ''' from scipy import stats import json import sys from os import path from collections import defaultdict from util import pretty_name, median_deviation from scipy.stats.mstats import kruskalwallis if __name__ == '__main__': # Run throug...
from selenium.webdriver.firefox.webdriver import WebDriver from tests_group.group_lib import GroupBase from tests_contract.contract_lib import ContactBase class SessionHelper: def __init__(self, app): self.app = app def login(self, user_name, password): wd = self.app.wd self.app.open_...
r("input[type=\"submit\"]").click() def logout(self): wd = self.app.wd wd.find_element_by_link_text("Logout").click() def is_logged_in(self,): wd = self.app.wd return len(wd.find_elements_by_link_text("Logout")) > 0 def is_logged_in_as(self, username): wd = self.a...
lf.is_logged_in(): self.logout() def ensure_login(self, user_name, password): if self.is_logged_in(): if self.is_logged_in_as(user_name): return else: self.logout() self.login(user_name, password) class BaseClass(): def __i...
import asposebarcodecloud from asposebarcodecloud.BarcodeApi import BarcodeApi from asposebarcodecloud.BarcodeApi import ApiException import asposestoragecloud from asposestoragecloud.StorageApi import StorageApi from asposestoragecloud.StorageApi import ResponseMessage import ConfigParser config = Config...
I SDK storage_apiClient = asposestoragecloud.ApiClient.ApiClient(apiKey, appSid, True) storageApi = StorageApi(storage_apiClient) #Instantiate Aspose Barcode API SDK api_client = asposebarcodecloud.ApiClient.ApiClient(apiKey, appSid, True) barcodeApi = BarcodeApi(api_client); #Set the barcode file name created ...
barcode" #Set Text to encode inside barcode. text = "Aspose.BarCode" #Set Barcode Symbology type = "Code128" #Set Generated Barcode Image Format format = "PNG" #Set height, Width and quality of the image imageHeight = 1.0; imageWidth = 1.0; imageQuality = "default"; try: #invok...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from lxml import etree as ElementTree from odoo.http import Controller, route, request class Board(Controller): @route('/board/add_to_dashboard', type='json', auth='user') def add_to_dashboard(self, action_id...
new_action = ElementTree.Element('action', { 'name': str(action_id), '
string': name, 'view_mode': view_mode, 'context': str(context_to_save), 'domain': str(domain) }) column.insert(0, new_action) arch = ElementTree.tostring(xml, encoding='unicode') ...
from argparse import Action from flexget.options import Argument
Parser def test_subparser_nested_namespace(): p = ArgumentParser() p.add_argument('--outer') p.add_subparsers(nested_namespaces=True) sub = p.add_subparser('sub') sub.add_argument('--inner') sub.add_subparsers() subsub = sub.add_subparser('subsub') subsub.add_argument('--innerinner') ...
d be nested under subparser name assert result.sub.inner == 'b' assert not hasattr(result, 'inner') # The second layer did not define nested_namespaces, results should be in first subparser namespace assert result.sub.innerinner == 'c' assert not hasattr(result, 'innerinner') def test_subparser_pa...
from django.test import TestCase from restclients.myplan import get_plan class MyPlanTestData(TestCase): def test_javerage(self): plan = get_plan(regid="9136CCB8F66711D5BE060004AC494FFE", year=2013, quarter="spring", terms=4) self.assertEquals(len(plan.terms), 4) self.assertEquals(plan.ter...
erm_data.registration_href, "https://uwkseval.cac.washington.edu/student/myplan/mplogin/netid?rd=/student/myplan/registration/20132") self.assertEquals(term_data.registered_courses_count, 0) self.assertEquals(term_data.registered_sections_count, 0) self.assertEquals(ter...
rm_data.courses[0].curriculum_abbr, 'CSE') self.assertEquals(term_data.courses[0].course_number, '101') self.assertEquals(len(term_data.courses[0].sections), 3) self.assertEquals(term_data.courses[0].sections[0].section_id, 'A') self.assertEquals(term_data.courses[0].sections[1].section_...
# Some useful functions to extract data out of emails # Copyright (C) 2002-2012 John Goerzen & contributors # # Thi
s 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 usefu...
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 St, Fifth Floor, Boston, MA 02...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import datetime from django.utils import timezone from django.test import TestCase from django.contrib.auth.models import User from django.test.utils import override_settings import six from happenings.models import Event @override_settings(CALENDAR_...
d</a><a class=' cls.cal_str = lambda self, day: html % day cls.event_div = '<div class="calendar-event">' @classmethod def tearDownClass(cls): cls.user.delete() def clean_whitespace(self, resp
onse): """Remove all newlines and all occurances of multiple spaces.""" if hasattr(response, 'content'): is_response = True content = response.content else: is_response = False content = response if isinstance(content, six.text_type): ...
""" (c) 2013 LinkedIn Corp. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");?you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing...
(self, record): pass
log.addHandler(NullHandler())
#### NOTICE: THIS FILE IS AUTOGENERATED ##
## MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Tangible() result.template = "object/tangible/ship/crafted/weapon/shared_shield_effectiveness_intensifier_mk4.iff" result.attribute_template_id = 8 result...
DIFICATIONS #### return result
ullable=True), sa.Column(u'release_version', sa.TEXT(), nullable=True), sa.Column(u'major_version', sa.TEXT(), nullable=True), sa.PrimaryKeyConstraint(u'id'), schema=u'bixie' ) op.create_table(u'full_urls', sa.Column(u'id', sa.INTEGER(), nullable=False), sa.Column(u'url', sa.TEXT(), null...
') op.drop_table(u'error_messages', schema=u'bixie') op.drop_table(u'os_names', schema=u'bixie') op.drop_table(u'release_channels', schema=u'bixie') op.drop_table(u'crashes', schema=u'bixie') op.drop_table(u'signatures', schema=u'bixie') op.drop_table(u'hosts', schema=u'bixie') op.drop_table...
leases', schema
# # author: Cosmin Basca # # Copyright 2010 University of Zurich # # 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 Lice
nse 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 speci
fic language governing permissions and # limitations under the License. # __author__ = 'basca' version = (0, 9, 5) str_version = '.'.join([str(v) for v in version])
ch}""" if isinstance( other, basestring ): other = Literal( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) return None retu...
) return None return other & self def __invert__( self ): """Implementation of ~ operator - returns C{NotAny}""" return NotAny( self ) def __call__(self, name): """Shortcut for C{setResultsName}, with C{listAllMatches=defau
lt}:: userdata = Word(alphas).setResultsName("name") + Word(nums+"-").setResultsName("socsecno") could be written as:: userdata = Word(alphas)("name") + Word(nums+"-")("socsecno") If C{name} is given with a trailing C{'*'} character, then C{listAllMatches} w...
from .models import HourRegistration from orders.models import Product from django.utils import timezone from django.http import JsonResponse from django.contrib.auth.decorators import login_required from datetime import datetime import pytz from django.contrib.auth.decorators import permission_required @login_requir...
' in request.POST: startdate = request.POST['startDate'] starttime = request.POST['startTime'] enddate = request.POST['endDate'] endtime = request.POST['endTime'] product_id = request.POST['product_i
d'] description = "" if 'description' in request.POST: description = request.POST['description'] start_date = format_date_and_time(startdate, starttime) end_date = format_date_and_time(enddate, endtime) product = Product.objects.get(pk=product_id) time = Hou...
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2013, Michael DeHaan <michael@ansible.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',...
e: break else: module.fail_json(msg='Unable to find either %s' % ', '.join(possibles)) if module.check_mode: module.exit_
json(msg=msg, changed=False) say(module, executable, msg, voice) module.exit_json(msg=msg, changed=True) if __name__ == '__main__': main()
from flask import request from flask_restful import Resource import json from core.bo.clienteBo import ClienteBo class Cliente(Resource): def __init__(self): self.cliente = ClienteBo() def
get(self, parameter=""): if parameter == "": return self.cliente.get_all(), 201 else: parameter = json.loads(parameter) if parameter.get('id'): return self.cliente.get_by_id(parameter["id"]), 201 elif parameter.get('d
ocument'): return self.cliente.get_document(parameter["document"], parameter["cliente"]), 201 elif parameter.get('board'): return self.cliente.get_board(), 201 else: return self.cliente.get_by_filter(parameter), 201 def put(self, parameter): ...
# -*- coding: utf-8 -*- from dCore import * from dConstants import * from dLog import * from dThread import * from dModules import * class DamnVideoLoader(DamnThread): def __init__(self, parent, uris, thengo=False, feedback=True, allownonmodules=True): DamnThread.__init__(self) self.uris = [] if type(uris) not i...
lse: self.SetStatusText(DV.l('Skipped ') + uri + DV.l(' (directory recursion disabled).')) else: Damnlog('URI',uri,'is a file.') filename = os.path.basename(uri) if uri in self.parent.videos: self.SetStatusText(DV.l('Skipped ') + filen
ame + DV.l(' (already in list).')) if len(uris) == 1: # There's only one file, so an alert here is tolerable self.showDialog(DV.l('Duplicate found'), DV.l('This video is already in the list!'), wx.ICON_EXCLAMATION | wx.OK) else: self.addValid({'name':filename[0:filename.rfind('.')], 'profile...
#!/usr/bin/env python """Vandermonde matrix example Demonstrates matrix computations using the Vandermonde matrix. * http://en.wikipedia.org/wiki/Vandermonde_matrix """ from sympy import Matrix, pprint, Rational, sqrt, symbols, Symbol, zeros def symbol_gen(sym_str): """Symbol generator Generates sym_str_...
for i in range
(num_pts): subs_dict[tmp_syms[i][j]] = points[i][j] V_pts = V.subs(subs_dict) V_inv = V_pts.inv() coeffs = V_inv.multiply(Matrix([points[i][-1] for i in xrange(num_pts)])) f = 0 for j,term in enumerate(terms): t = 1 for k in term: t *= syms[k] f += c...
# -*- codin
g: utf-8 -*- import pandas as pd import numpy as np from axiomatic.base import AxiomSystem from axiomatic.elementary_conditions import MinMaxAxiom # l, r, pmin, pmax params = [1, 1, -0.8, 0.8] axiom_list = [MinMaxAxiom(params)] ts = pd.DataFrame(np.random.random((10, 2))) print(ts) print(MinMaxAxiom(params).run(ts, ...
iom_list) print(now.perform_marking(ts))
s about this component, please refer to the documentation at https://home-assistant.io/components/proximity/ """ import logging from homeassistant.helpers.entity import Entity from homeassistant.helpers.event import track_state_change from homeassistant.util.location import distance DEPENDENCIES = ['zone', 'device_tr...
lf.update_ha_state() return # Stop if we cannot calculate the direction of travel (i.e. we don't # have a previous state and a current LAT and LONG). if old_state is None or 'latitude' not in old_state.attributes: self.dist_to = round(distances_to_zon
e[entity]) self.dir_of_travel = 'unknown' self.nearest = entity_name self.update_ha_state() return # Reset the variables distance_travelled = 0 # Calculate the distance travelled. old_distance = distance(proximity_latitude, proximity_long...
from h
andlers.BaseHandlers import BaseHandler class HomePageHandler(BaseHandler): def get(self, *args, **kwargs):
self.render('home.html')
# -*- coding: iso-8859-1 -*- """MoinMoin Desktop Edition (MMDE) - Configuration ONLY to be used for MMDE - if you run a personal wiki on your notebook or PC. This is NOT intended for internet or server or multiuser use due to relaxed security settings! """ import sys, os from MoinMoin.config import multiconfig, url...
/your/instance/is' instance_dir = os.path.join(wikiconfig_dir, 'wiki') # Where your own wiki pages are (make regular
backups of this directory): data_dir = os.path.join(instance_dir, 'data', '') # path with trailing / # Where system and help pages are (you may exclude this from backup): data_underlay_dir = os.path.join(instance_dir, 'underlay', '') # path with trailing / DesktopEdition = True # give all local users ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2011-2013,2015 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio 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 v...
st.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_001_t(self): original = (1,) * 100 + (-1,) * 100 + (0,) * 50 + (10,) + (0,) * 49 expected_result = [(-200,) * 50 + (0,) + (-200,) * 49, (-20,) * 100] src = blocks.ve...
self.tb.connect(src, dst) self.tb.run() result_data = dst.get_plot_data() result_data1 = dst.get_plot_data() self.assertEqual(expected_result[0], tuple(result_data[0])) self.assertEqual(expected_result[0], tuple(result_data1[0])) self.tb.stop() self.tb.wa...
#!/usr/bin/python # -*- coding: utf-8 -*- """ The Art of an Artificial Intelligence http://art-of-ai.com https://github.com/artofai """ __author__ = 'xevaquor' __license__ = 'MIT' import numpy as np import util class LayerBase(object): def __init__(self): self.size = None self.W = np.zeros((0,0))...
orward(X) return (self.y_hat - y) def cost_prime(self, X, y): # output layer delta deltas
= [None] * len(self.layers) differentials = [None] * len(self.layers) nabla_cost = self.nabla_cost(X, y) deltas[-1] = np.multiply(nabla_cost, self.layers[-1].phi_prime(self.layers[-1].v)) differentials[2] = np.dot(self.layers[1].a.T, deltas[2]) truncatedW = self.layers[-1].W[...
''' @author: Team Alpha, <aa5186@nyu.edu> Name: Customer Model Purpose: This library is part of the
customer REST API for the ecommerce website ''' from cust
omer import Customer
# this app has been deprecated but sticks around for
migrations
dependencies
""" Flarf: Flask Request Filter ------------- Configurable request filters """ from setuptools import setup setup( name='Flask-Flarf', version='0.0.5', url='https://github.com/thrisp/flarf', license='MIT', author='Thrisp/Hurrata', author_email='blueblank@gmail.com', description='Flask requ...
sk>=0.9' ], test_suite='nose.collector', tests_require=[ 'nose', 'blinker'], classifiers=[ 'Development Stat
us :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Topic :: Internet :: WWW...
# 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 # distribu...
fficients_for_reversible_sampling) from ._operator_utils import (chemist_ordered, count_q
ubits, eigenspectrum, fourier_transform, freeze_orbitals, get_file_path, hermitian_conjugated, inline_sum, inverse_fourier_transform, is_hermitian, is_identity, ...
""" Feature detection (Szeliski 4.1.1) """ import numpy as np import scipy.signal as sig import scipy.ndimage as ndi from compvis.utils import get_patch def sum_sq_diff(img_0, img_1, u, x, y, x_len, y_len): """ Returns the summed square difference between two image patches, using even weighting across the...
u, x, y, x_len, y_len): """ Returns the auto-correlation function for an image patch with a displacement of u. Uses even weighting across the patch. (This function simply calls sum_sq_diff() with both images the same, and is left here for reference/convenience.) Parameters : img
: image u : displacement vector between patches x, y : coordinates of top-left corner of patch x_len, y_len : dimensions of patch """ return sum_sq_diff(img, img, u, x, y, x_len, y_len) def autocorr_surface(img, u_x_range, u_y_range, x, y, x_len, y_len): ...
""" This
file implements the lowering for `dict()` """ from numba.targets.imputils import lower_builtin @lower_builtin(dict) def impl_dict(context, builder, sig, args): """ The `dict()` implementation simply forwards the work to `Dict.empty()`. """ from numba.typed import Dict dicttype = sig.return_type ...
.key_type, dicttype.value_type def call_ctor(): return Dict.empty(kt, vt) return context.compile_internal(builder, call_ctor, sig, args)
""" Copyright 2012, July 31 Written by Pattarapol (Cheer) Iamngamsup E-mail: IAM.PATTARAPOL@GMAIL.COM
Sum square difference Problem 6 The sum of the squares of the first ten natural numbers is, 1^2 + 2^2 + ... + 10^2 = 385 The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 1
0)^2 = 55^2 = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 385 = 2640. Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. """ ###########################...
'pycsw:PublicationDate']}, 'apiso:OrganisationName': {'xpath': 'gmd:identificationInfo/gmd:MD_DataIdentification/gmd:pointOfContact/gmd:CI_ResponsibleParty/gmd:organisationName/gco:CharacterString', 'dbcol': self.context.md_core_model['mappings']['pycsw:OrganizationName']}, ...
tifier']}, 'apiso:KeywordType': {'xpath': 'gmd:identificationInfo/gmd:MD_DataIdentification/gmd:descriptiveKeywords/gmd:MD_Keywords/gmd:type/gmd:MD_KeywordTypeCode', 'dbcol': self.context.md_core_model['mappings']['pycsw:KeywordType']}, 'apiso:TopicCategory': {'xpath':
'gmd:identificationInfo/gmd:MD_DataIdentification/gmd:topicCategory/gmd:MD_TopicCategoryCode', 'dbcol': self.context.md_core_model['mappings']['pycsw:TopicCategory']}, 'apiso:ResourceLanguage': {'xpath': 'gmd:identificationInfo/gmd:MD_DataIdentification/gmd:citation/gmd:CI_Citation/gmd:identifie...
import sys from core import loop from util import jsonmanager, debug def make_console_menu(name): menu_data_file_path = '_Resources/Data/MenuData/' path = menu_data_file_path + name + '.json' data = jsonmanager.get_data(path) title = data['Title'] item_data = data['Items'] args = [] for...
] for argument in args: self.add_menu_item(argument[0], argument[1]) def add_menu_item(self, text, action): self.menu_items.append(ConsoleMenuItem(text, action)) def get_menu_item(self, index): return self.menu_items[index] def display_menu_item(self, index): ...
enu_items)): self.display_menu_item(index) result = input('Choose an option: ') self.get_menu_item(int(result)).invoke() def run_loop(game_loop): game_loop.set_scene('pallet-town') game_loop.run() def run_editor(): run_loop(loop.EditorLoop()) def run_game(): run_loop(...
#!/usr/bin/env python3 import idmaker import utils from tkinter import * from PIL import Image, ImageTk top = Tk() top.wm_title("Voice Research Laboratory") top.iconbitmap('icons/favicon.ico') top.state('zoomed') class MainWindow: def __init__(self, top): self.top = top self....
lf.getReplacement) self.submit.pack() def getEmailtext(self):
self.body = self.e1.get() utils.Emailz.send_email(self.body) self.emailwindow.destroy() def emailCallBack(self): self.emailwindow = Toplevel() self.emailwindow.title('Emailer') self.emailwindow.focus_set() self.emailLabel = Label(self.emailwindow, text="E...
prefix = "tabulator-" delete = self.__workbook_cache is None source_bytes = self.__loader.load(source, mode="b", encoding=encoding) target_bytes = NamedTemporaryFile(prefix=prefix, delete=delete) shutil.copyfileobj(source_bytes, target_bytes) ...
to abandon this attempt to convert because the code is not recognized return None prev_code = ec excel_code = "" if is_escap
e_char: char_escaped = True elif is_misc_char: # Add the misc char if checking_minute_or_month: minute_or_month_buffer += c else: python_date += c else: # Just add to the cod
import torch from deluca.lung.core import Controller, LungEnv class PIDCorrection(Controller): def __init__(self, base_controller: Controller, sim: LungEnv, pid_K=[0.0, 0.0], decay=0.1, **kwargs): self.base_controller = base_controller self.sim = sim self.I = 0.0 self.K = pid_K ...
def compute_action(self, state, t): u_in_base, u_out = self.base_controller(state, t) err = self.sim.pressure - state self.I = self.I * (1 - self.decay) + err * self.decay pid_correction = self.K[0] * err + self.K[1] * self.I u_in = torch.clamp(u_in_base + pid_correction, ...
, u_out, t) return u_in, u_out
""" Tests for split's copy_from_template method. Currently it is only used for content libraries. However for these tests, we make sure it also works when copying from course to course. """ import ddt from xmodule.modulestore import ModuleStoreEnum from xmodule.modulestore.exceptions import ItemNotFoundError from xmodu...
ished) ) self.assertEqual(problem_published.display_name, display_name_expected) def test_copy_from_template_auto_publish(self): """ Make sure that copy_from_template works with things like 'chapter' that are always auto-published. """ source_course =...
=self.store) course = CourseFactory.create(modulestore=self.store) # Populate the course: about = self.make_block("about", source_course) chapter = self.make_block("chapter", source_course) sequential = self.make_block("sequential", chapter) # And three blocks that are N...
#import os import sys import time import xmltodict import pprint pp = pprint.PrettyPrinter(indent=4,stream=sys.stderr) testing = False # def poll_co
ndor(jonbr, bagnr): def poll_condor(filename): # filename = "hist-%d-%d.xml" % ( jobnr, bagnr ) # command = "condor_history -constraint 'HtcJob == %d &&
HtcBag == %d' -xml > %s" % ( jobnr, bagnr, filename ) # os.system( command ) tries = 0 poll_dict = {} while tries < 4: tries += 1 _trystr = "Try %d (%s) :" % (tries, filename) xml = open(filename).read() xmldict = xmltodict.parse(xml) print >> sys.stderr, "type(xm...
import sys import logging logger = logg
ing.getLogger(__name__) def configure_logging(): root = logging.getLogger() root.setLevel(logging.DEBUG) handler = logging.StreamHandler(sys.stdout) handler.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s %(name)12s %(levelname)7s - %(message)s') handler.setFormatter(form
atter) root.addHandler(handler)
from datetime import datetime import random import string from bson import ObjectId class DuplicateUserException(Exception): def __init__(self, message='User name/email already exits'): Exception.__init__(self, message) pass class UserServiceException(Exception): def __init__(self, message=None...
les' not in item or item['roles'] is None or len(item['roles']) == 0: item['roles'] = ['member'] return self.users.insert
(item) def get_by_email(self, email): return self.users.find_one({"email": email}) def validate_user(self, username, password): query = {'email': username, 'password': password} return self.users.find(query).count() > 0 def search(self, email=None): query = {} if e...
ight]) if not nodes: nodes.append(node) else: pos = 0 while pos < len(nodes) and nodes[pos].weight > node.weight: pos += 1 nodes.insert(pos, node) top = nodes[0] tree = Tree(top) tree.reduce(15) codes = tree.codes() c...
pos = 0 while pos < len(compressed): bits = compressed[pos
:pos + 8] byte = int(bits, 2) if len(bits) < 8: byte <<= (8 - len(bits)) out.append(byte) pos += 8 return out def compressed_str(self): return ''.join(self.codes[car] for car in self.text) class Decompresser: def __init__(self, ...
# -*- coding: utf-8 -*- # Licence: GPL v.3 http://www.gnu.org/licenses/gpl.html # This is an XBMC addon for demonstrating the capabilities # and usage of PyXBMCt framework. import os import xbmc import xbmcaddon import pyxbmct from lib import utils import plugintools from itertools import tee, islice, chain, izip _a...
addon.getAddonInfo('path') # Enable or disable Estuary-based design ex
plicitly # pyxbmct.skin.estuary = True def previous_and_next(some_iterable): prevs, items, nexts = tee(some_iterable, 3) prevs = chain([None], prevs) nexts = chain(islice(nexts, 1, None), [None]) return izip(prevs, items, nexts) class categorySelectDialog(pyxbmct.AddonDialogWindow): def __init_...
# Copyright (C) 2017 Daniel Wa
tkins <daniel@daniel-watkins.co.uk> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use th
is 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...
class Image(meta.Entity): data = meta.Bytes
()
from __future__ import print_function,division # duner. using numbers and sample. """ q +-----+ r +-----+ ---->| C |---->| D |--> s ^ +-----+ +-+---+ | | +-----------------+ C = stock of clean diapers D = stock of dirty diapers q = inflow of clean diapers r = flow of clean diapers...
s=0) for dt,t,u,v in sim(world,life=60,spy=True,dt=0.5): v.C += dt*(u.q - u.r) v.D += dt*(u.r - u.s) v.q = 70 if saturday(t) else 0 v.s = u.D if saturday(t) else 0 if t == 27: # special case (the
day i forget) v.s = 0 diapers()
# -*- coding: utf-8 -*- # Copyright(C) 2013 Julien Veyssier # # This file is part of weboob. # # weboob 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 Fou
ndation, either version 3 of the License, or # (at your option) any later version. # # weboob
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 wi...
"RESTRICT") # Make available for S3Models s3.role_required = role_required s3.roles_permitted = roles_permitted # ============================================================================= # Other reusable fields # ----------------------------------------------------------------------------- # Reusable comments ...
t(table.name, table.level, table.parent, table.path,
limitby=(0, 1)).first() if location: if location.level == "L0": vars.L0 = location.name elif location.level == "L1": vars.L1 = location.name if location.parent: query = (table.id == location.parent) ...
#!/usr/bin/env python ############################################################################# ## ## Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ## All rights reserved. ## Contact: Nokia Corporation (qt-info@nokia.com) ## ## This file is part of the documentation of the Qt Toolkit. ## ## $QT_...
rdWrap(True) caption.setMargin(2) layout.addWidget(caption, 1, 2, Qt.AlignCenter |
Qt.AlignTop) elif qt == "4.1": opaqueWidget = CustomWidget(label, fake = True) opaqueWidget.setAttribute(Qt.WA_OpaquePaintEvent, True) layout.addWidget(opaqueWidget, 0, 2, Qt.AlignCenter) caption = QLabel("With WA_OpaquePaintEvent set", label) caption.setAutoFillBackground(Tr...
""" Application for testing syncing algorithm (c) 2013-2014 by Mega Limited, Wellsford, New Zealand This file is part of the MEGA SDK - Client Access Engine. Applications using the MEGA API must present a valid application key and comply with th
e the rules set forth in the Terms of Service. The MEGA SDK 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. @copyright Simplified (2-clause) BSD License. You should have received a copy of the ...
s import re from sync_test_app import SyncTestApp from sync_test import SyncTest import logging import argparse class SyncTestMegaCliApp(SyncTestApp): """ operates with megacli application """ def __init__(self, local_mount_in, local_mount_out, delete_tmp_files=True, use_large_files=True, check_if_ali...
from utils.functions.models import row
s_to_dict_list_lower, GradeQtd def grade_estoque( cursor, ref=None, dep=None, data_ini=None, tipo_grade=None, modelo=None, referencia=None): filtro_modelo = '' filtro_modelo_mask = '' if modelo is not None: filtro_modelo_mask = f'''-- AND TRIM( ...
B]?([0-9]+)[a-zA-Z]*$', '\\1' ) ) ) = '{modelo}' ''' filtro_referencia = '' filtro_referencia_mask = '' if referencia is not None: filtro_referencia_mask = f'''-- AND {{}} = '{referencia}' ''' teste...
import py
test import dask.array as da from ..utils import assert_eq xr = pytest.importorskip("xarray")
def test_mean(): y = da.mean(xr.DataArray([1, 2, 3.0])) assert isinstance(y, da.Array) assert_eq(y, y) def test_asarray(): y = da.asarray(xr.DataArray([1, 2, 3.0])) assert isinstance(y, da.Array) assert_eq(y, y) def test_asanyarray(): y = da.asanyarray(xr.DataArray([1, 2, 3.0])) a...
"""Precompute the polynomials for the asymptotic expansion of the generalized exponential integral. Sources ------- [1] NIST, Digital Library of Mathematical Functions, http://dlmf.nist.gov/8.20#ii """ from __future__ import division, print_function, absolute_import import os import warnings try: # Can remo...
* Do not edit it manually! */ """ def main(): print(__doc__) fn = os.path.join('..', 'cephes', 'expn.h') K = 12 A = generate_A(K) with open(fn + '.new', 'w') as f: f.write(WARNING) f.write("#define nA {}\n".format(len(A))) for k, Ak in enumerate(A): tmp = ',...
ouble A{}[] = {{{}}};\n".format(k, tmp)) tmp = ", ".join(["A{}".format(k) for k in range(K + 1)]) f.write("double *A[] = {{{}}};\n".format(tmp)) tmp = ", ".join([str(Ak.degree()) for Ak in A]) f.write("int Adegs[] = {{{}}};\n".format(tmp)) os.rename(fn + '.new', fn) if __name__ == ...
face': 'Logowanie do panelu administracyjnego', 'Models': 'Modele', 'Modules': 'Moduły', 'NO': 'NIE', 'New Record': 'Nowy rekord', 'New application wizard': 'New application wizard', 'New simple application': 'New simple application', 'No databases in this application': 'Brak baz danych w tej aplikacji', 'Original/Tran...
ser, cannot change password here': 'PAM authenticated user, cannot change password here', 'Peeking at file': 'Podgląd pliku', 'Plugin "%s" in application': 'Wtyczka "%s" w aplikacji', 'Plugins': 'Wtyczki', 'Powered by': 'Zasilane przez', 'Query:': 'Zapytanie:', 'Resolve Conflict file': 'Rozwiąż ko
nflikt plików', 'Rows in table': 'Wiersze w tabeli', 'Rows selected': 'Wierszy wybranych', 'Saved file hash:': 'Suma kontrolna zapisanego pliku:', 'Searching:': 'Searching:', 'Static files': 'Pliki statyczne', 'Sure you want to delete this object?': 'Czy na pewno chcesz usunąć ten obiekt?', 'TM': 'TM', 'Testing applica...
@property def monitors(self): if self._values['monitors'] is None: return None if self._values['monitors'] == '/Common/bigip': return '/Common/bigip' monitors = [fq_name(self.partition, x) for x in self.monitors_list] if self.availability_requirement_typ...
def state(self): if self._values['state'] == 'enabled': return 'present' return self._values['state'] @property def iquery_allow_path(self): if self._values['iquery_options'] is None: return None elif self._values['iquery_options']['allow_path'] is Non...
return self._values['iquery_options']['allow_path'] @property def iquery_allow_service_check(self): if self._values['iquery_options'] is None: return None elif self._values['iquery_options']['allow_service_check'] is None: return None return self._values['...
# -*- coding: utf-8 -*- """ *************************************************************************** ExtentFromLayer.py --------------------- Date : August 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com ***********************...
perim = (2 * width) + (2 * height) rect = [QgsPoint(minx, miny), QgsPoint(minx, maxy), QgsPoint(maxx, maxy), QgsPoint(maxx, miny), QgsPoint(minx, miny) ] geometry = QgsGeometry().fromPolygon([rect]) feat = QgsFe...
ture() feat.setGeometry(geometry) attrs = [QVariant(minx), QVariant(miny), QVariant(maxx), QVariant(maxy), QVariant(cntx), QVariant(cnty), QVariant(area), QVariant(perim), ...
add_argument('--tf_value_cuttoff', type=float, default=0.0, help='The cutoff z-score tf_value for which activity plots are generated (default: 0.0) ') parser.add_argument('--version', help='Print version and exit.', action='version', ...
BAM_FOLDER = False data_filenames = [] gene_expression_filenames = [] sample_na
mes = [] with open(samples_filename_or_bam_folder) as infile: for line in infile: if not line.strip(): continue if line.startswith('#'): # skip optional header line or empty lines info('Skipping header/comment line:%s' % lin...
"""Module for configuring the host environment""" import os import json import sys class HostConfig(): """Sets up the required components on the host environment""" def __init__(self): """Host""" self.path = None self.apps = None def get_path(self): """Gets...
son', 'r') as file: content = json.load(file) self.apps = [app for app in content.get('apps')] def build(self): """Builds folders using the specified path and apps.json""" print('Building folders...') for app in self.apps: try: ap...
t(self.path, app.get('name')) os.mkdir(app_path) print('Created {}'.format(app_path)) except OSError: print('Folder for {} already exists. Skipping..') if __name__ == '__main__': pass
''' Broken (piecewise continuous) random field generation using rft1d.randn1d
Note: When FWHM gets large (2FWHM>nNodes), the data should be padded using the *pad* keyword. ''' import numpy as np from matplotlib import pyplot import rft1d #(0) Set parameters: np.random.seed(12345) nResponses = 5 nNodes = 101 FWHM = 20.0 ### create a boolean mask: nodes = np.array([True...
"""Uploads apk to rollout track with user fraction.""" import sys import socket from apiclient.discovery import build from oauth2client.service_account import ServiceAccountCredentials import subprocess import xml.etree.ElementTree as ET import os from pathlib import Path TRACK = 'beta' USER_FRACTION = 1 APK_FILE = '...
eName=package_name, media_body
=apk_file ).execute() print('Version code %d has been uploaded' % apk_response['versionCode']) track_response = service.edits().tracks().patch( editId=edit_id, track=TRACK, packageName=package_name, body={ 'releases': [{ 'releaseNotes': [{ ...