prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
from modeltranslation.translator import translator, TranslationOptions from nsms.text.models import * from django.utils.translation import ugettext as _ from django.utils.translation import get_language as _get_language from modeltranslation import utils class TextTranslationOptions(TranslationOptions): fields =
('text',)
translator.register(Text, TextTranslationOptions) # need to translate something for django translations to kick in _("Something to trigger localizations") # monkey patch a version of get_language that isn't broken def get_language(): lang = _get_language() return lang utils.get_language = get_language
import logging from serial_grabber.reader import MessageVerifier class XBeeMessageVerifier(MessageVerifier): logger = logging.getLogger("MessageVerifier") def verify_message(self, transaction):
try: data = transaction.split("\n") if int(data[-2]) == len("\n".join(data[1:-2])): return True, "OK" else: self.logger.error("Reported length: %s, Actual length: %s"%(int(data[-2]), len("\n".join(data[1:-2])))) raise ValueError() ...
False, "NA"
nate_lines(self, x_page_offsets, page_y_top): """ Step three go through the lines and put each in page(s) """ for box1 in self.boxes: if not box1.line_to: continue line = box1.line_to pages = [box1.page.y_page_num] end = line.start + lin...
self.note.doc = self.doc self.note.page = self else: self.__paginate(colsperpage) #------------------------------------------------------------------------ # # Class Box_Base # #------------------------------------------------------------------------ class BoxBase:...
""" def __init__(self): self.page = None #'None' will cause an error. Sub-classes will init self.boxstr = "None" self.text = "" #level requires ... # (# - which column am I in (zero based) # ,# - Am I a (0)direct descendant/ancestor or (>0)other ...
#!/usr/bin/python
#coding=utf-8 ''' @
author: sheng @license: ''' SPELL=u'shuǐdào' CN=u'水道' NAME=u'shuidao34' CHANNEL='stomach' CHANNEL_FULLNAME='StomachChannelofFoot-Yangming' SEQ='ST28' if __name__ == '__main__': pass
#!/usr/bin/env python # # Beautiful Capi generates beautiful C API wrappers for your C++ classes # Copyright (C) 2015 Petr Petrovich Petrov # # This file is part of Beautiful Capi. # # Beautiful Capi is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as publis...
me) for nested_namespace in namespace.namespaces: self.process_namespace(nested_namespace) for cur_class in namespace.classes: self.process_class(cur_class, namespace) self.class_stack.pop() def process(self): for cur_namespace in self.root_node.namespaces: ...
essor(root_node) semantic_processor.process()
from d
jango.conf.urls import include, url from . import views app_name = 'todo' urlpatterns = [ url(r'^lists/$', views.todolists, name='todo_lists'), url(r'^lists/(?P<list
_id>[\w\d]+)/update/$', views.UpdateTodoList.as_view(), name='update_list'), url(r'^lists/card/(?P<card_id>[\w\d]+)/$', views.cards, name='cards'), url(r'^lists/new/$', views.CreateList.as_view(), name='new_list'), url(r'^lists/card/new/(?P<list_id>[\w\d]+)/$', views.CreateCard.as_view(), name='new_card'), url(r'^l...
on = False self.vtkSelector.addEnabled = False self.vtkSelector.removeEnabled = False self.vtkSelector.noneEnabled = True self.vtkSelector.setMRMLScene(slicer.mrmlScene) self.vtkSelector.setToolTip("Select the Fiber Bundle to filter") self.vtkSelectorFrame.layout()....
True else: self.calculateLengthButton.enabled = False def onOutputSelect(self, node): self.outputNode = node self.outputNode.CreateDefaultDisplayNodes() self.outputPolyData = vtk.vtkPolyData() def onCalculateLength(self): self.inputPolyData
= self.vtkNode.GetPolyData() points = self.inputPolyData.GetPoints() lines = self.inputPolyData.GetLines() lines.InitTraversal() self.distanceTable = list() for i in range(self.inputPolyData.GetNumberOfCells()): fiberLength = 0 ids = vtk.vtkIdList...
""" Th
is package contains different `unittests <https://docs.python.org/3/library/unittest.html>`_ for the project. Those tests help to validate difficult pieces
of the software. """ __author__ = 'Wuersch Marcel' __license__ = "GPLv3"
from __future__ import absolute_import import platform import datetime import sunpy __all__ = ['system_info'] def system_info(): """Prints system information. Prints information about the runtime environment that SunPy lives in. Information about the OS, architecture, Python, and all major dependen...
# OS and architecture information if system == "Linux": distro = " ".join(platform.linux_distribution()) print("OS: %s (Linux %s %s)" % (distro, platform.release(), proc)) elif system == "Darwin": print("OS: Mac OS X %s (%s)" % (platform.mac_ver()[0], proc)) elif system == "Windo...
platform.version(), proc)) else: print ("Unknown OS (%s)" % proc) # Python version arch = platform.architecture()[0] print("Python: %s (%s)\n" % (platform.python_version(), arch)) # Dependencies try: from numpy import __version__ as numpy_ver...
from hitchhttp import http_request from ruamel.yaml import dump from ruamel.yaml.dumper import RoundTripDumper from ruamel.yaml.comments import CommentedMap from hitchhttp.models import Database from os import path import tornado.web import tornado import requests import random import json import time import sys clas...
'a') as handle: #handle.write("\n{}".format( #dum
p([yaml_snip], default_flow_style=False, Dumper=RoundTripDumper)) #) for header_var, header_val in self.response.headers.items(): if header_var.lower() not in ["transfer-encoding", "content-encoding", ]: self.set_header(header_var, header_val)...
#CHIPSEC: Platform Security Assessment Framework #Copyright (c) 2010-2015, Intel Corporation # #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; Version 2. # #This program is distributed in t...
self.logger.log_good( "Could not modify EFI variable %s {%s}" % (name, guid) ) return ok # checks authentication of Secure Boot EFI variables def check_secureboot_key_variables(self): sts = 0 sts |= self.check_EFI_variable_authentication( EFI_VAR_NAME_PK, EFI...
k_EFI_variable_authentication( EFI_VAR_NAME_KEK, EFI_VARIABLE_DICT[EFI_VAR_NAME_KEK] ) sts |= self.check_EFI_variable_authentication( EFI_VAR_NAME_db, EFI_VARIABLE_DICT[EFI_VAR_NAME_db] ) sts |= self.check_EFI_variable_authentication( EFI_VAR_NAME_dbx, EFI_VARIABLE...
""" This example outputs a custom waveform and records the waveform on Channel A. The output of the AWG must be connected to Channel A. """ import os import numpy as np # if matplotlib is available then plot the results try: import matplotlib.pyplot as plt except ImportError: plt = None from msl.equipment i...
_to_pk=2.0) scope.run_block(pre_trigger=2.5) # start acquisition scope.wait_until_ready() # wait until all requested samples are collected scope.set_data_buffer('A') # set the data buffer for Channel A scope.get_values() # fill the data buffer of Channel A with the values saved in the PicoScope's internal memory s...
): print('{0:f}, {1:f}'.format(t[i], scope.channel['A'].volts[i])) if plt is not None: plt.plot(t, scope.channel['A'].volts, 'bo') plt.show()
"value": '**', "first": { "type": "name", "value": 'a' }, "second": { "type": "binary_operator", "value": '**', "first": { "type": "name", "value": 'b' ...
tor", "value": '**', "first": { "type": "name", "value": 'a' }, "second": { "type": "unitary_operator", "value": '~',
"target": { "type": "name", "value": 'b', }, "formatting": [], }, "first_formatting": [{"type": "space", "value": " "}], "second_formatting": [{"type": "space", "value": " "}] } ]) ...
from others import sms_request print(sms_request('1
5683000435', '1234
56'))
############################################################################### # tetrapy.py # Tetrapy # # Copyright (C) 2013 Kesara Rathnayake # # Tetrapy 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, eithe...
pass class TetrominoI(Tetromino): def __init__(self, colour): super(TetrominoI, self).__init__(colour) self.W = 20 self.H = 80 self.x = 0 self.y = 0 def draw(self, screen): rect = pygame.Rect(self.x, self.y, self.W, self.H) pygame.draw.rect(scr...
self.x + direction <= X-20 and self.x + direction >= 0: self.x += direction if self.y <= Y-80: self.y += 20 def isLocked(self, matrix): if self.y + 80 == Y: self.locked = True return True elif (self.collied(matrix)): re...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Nov 15 14:09:59 2017 @author: SaintlyVi """ import pandas as pd import numpy as np from support import writeLog def uncertaintyStats(submodel): """ Creates a dict with statistics for observed hourly profiles for a given year. Use evaluati...
valid_unit_count = valid_data['valid_hours'].sum() unit = 'total_valid_hours' except: valid_unit_count = valid_data['AnswerID_count'].sum() unit = 'valid_AnswerID_count' validmodels =
validmodels.append({'submodel_name':name, 'valid_data':valid_data, 'uncertainty_index':uix, 'valid_unit_count':valid_unit_count, 'unit':unit}, igno...
import testtools from keystoneclient.middleware import memcache_crypt class MemcacheCryptPositiveTests(testtools.TestCase): def _setup_keys(self, strategy): return memcache_crypt.derive_keys('token', 'secret', strategy) def test_constant_time_compare(self): # make sure it works as a compare,...
def test_protect_wrappers(self): data = 'My Pretty Little Data' for strategy in ['MAC', 'ENCRYPT']: keys = self._setup_keys(strategy) protected = memcache_crypt.protect_data(keys, data) self.assertNotEqual(protected, data) if strategy =
= 'ENCRYPT': self.assertNotIn(data, protected) unprotected = memcache_crypt.unprotect_data(keys, protected) self.assertEqual(data, unprotected) self.assertRaises(memcache_crypt.InvalidMacError, memcache_crypt.unprotect_data, ...
en = True, )) s3db.configure(tablename, crud_form = crud_form, ) if r.representation == "geojson": from s3 import S3Represent s3db.vehicle_vehicle.vehicle_type_id.represent = S3Repre...
.label = T("Incident Type") table.organisation_id.readable = table.organisation_id.writable = False # Report options report_fact = [(T("Number of Missions"), "count(id)"),
(T("Number of Countries"), "count(location_id)"), (T("Number of Incident Types"), "count(event_type_id)"), (T("Number of Responses"), "sum(response_count)"), (T("Number of Deployments"), "sum(hrquantity)"), ] rep...
from . imp
ort Checker class ExactChecker(Checker): async def check(self, sandbox, task): output = await sandbox.read("/tmp/output.txt") task.accepted = output == task.testcase.output task.verdict = "AC"
if task.accepted else "WA"
""" Cardiac Arrhythmia Database The original dataset and further information can be found here: https://archive.ics.uci.edu/ml/datasets/Arrhythmia Brief description ----------------- This data contains 452 observations on 279 variables (206 linear valued + 73 nominal) on ECG readings. The data was collected to...
20 S' wave 21 Number of intrinsic deflections, linear 22 Existence of ragged R wave, nominal 23 Existence of diphasic derivation of R wave, nominal 24 Existence of ragged P wave, nominal 25 Existence of diphasic derivation of P wave, nominal 26 Existence of ragged T wave, nominal ...
of T wave, nominal Of channel DII: 28 .. 39 (similar to 16 .. 27 of channel DI) Of channels DIII: 40 .. 51 Of channel AVR: 52 .. 63 Of channel AVL: 64 .. 75 Of channel AVF: 76 .. 87 Of channel V1: 88 .. 99 Of channel V2: 100 .. 111 Of c...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # li
cense information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------
- from .error import Error from .api_error import APIError, APIErrorException from .face_rectangle import FaceRectangle from .coordinate import Coordinate from .face_landmarks import FaceLandmarks from .facial_hair import FacialHair from .head_pose import HeadPose from .emotion import Emotion from .hair_color import H...
ng_list_property('action_time') followed_age = long_list_property('followed_age') followed_gender = long_list_property('followed_gender') followed_time = long_list_property('followed_time') @classmethod def default_statistics(cls): stats = cls() for prop in ('reached', 'rogered', 'a...
NewsButtonsProperty(db.UnindexedProperty): # Tell what the user type is. data_type = NewsButtons
# For writing to datastore. def get_value_for_datastore(self, model_instance): with closing(StringIO()) as stream: _serialize_news_buttons(stream, super(NewsButtonsProperty, self).get_value_for_datastore(model_instance)) return db.Blob(stream.getvalue()) # For reading from...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 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 version 3...
n(res)) self.assertLess(np.max(res), maximum) def test_002_short(self): minimum = 42 maximum = 1025 seed = 3 n_items = 10000 rnd_src = analog.random_uniform_source_s(minimum, maximum, seed) head = blocks.head(2, n_items) snk = blocks.vector_sink_s(1) ...
head, snk) # set up fg self.tb.run() # check data res = snk.data() self.assertGreaterEqual(minimum, np.min(res)) self.assertLess(np.max(res), maximum) def test_003_int(self): minimum = 2 ** 12 - 2 maximum = 2 ** 17 + 5 seed = 3 n_item...
he individual algorithms. It would be possible to use alternative implementations """ import numpy as np import theano from theano import tensor as T from theano.tensor import nlinalg class algorithms_numpy(): """ The algorithms implemented in numpy. This should be the base class for any extended impleme...
TODO: change call signature to make more pythonic TODO: use a data structure for the raw data """ nt0 = ops.nt0 NT, n_Filt, Th = Params[0:2] pm = Params[8] fft_data = np.fft.fft(data,axis=0) proj = np.fft.i
fft(fft_data * fW[:,:]).real #convolution proj = np.sum(proj.reshape(NT, n_filt,3), 2) Ci = proj + (mu * lam).T Ci = (Ci**2) / (1 + lam.T) Ci = Ci - (lam*mu**2).T imax = np.argmax(Ci, axis=1) mX = Ci[imax] maX = -my_min(-mX,31,1) # Err... my_min? This function s...
def
bar():
print('bar!')
#!/usr/
bin/python #coding:utf-8 print 'start to load...' import sys name = 42 def func(): pass class kclass : pass print 'done
loading.'
import wx from service.fit import Fit import gui.mainFrame from gui import globalEvents as GE from .calc.fitRemoveBooster import FitRemoveBoosterCommand class GuiRemoveBoosterCommand(wx.Command): def __init__(self, fitID, position): wx.Command.__init__(self, True, "") self.mainFrame = gui.mainFra...
fitID = fitID self.position = position def Do(self): if self.internal_history.Submit(FitRemoveBoosterCommand(self.fitID, self.position)): self.sFit.recalc(self.fitID) wx.PostEvent(self.ma
inFrame, GE.FitChanged(fitID=self.fitID)) return True return False def Undo(self): for _ in self.internal_history.Commands: self.internal_history.Undo() self.sFit.recalc(self.fitID) wx.PostEvent(self.mainFrame, GE.FitChanged(fitID=self.fitID)) return ...
= PypmWrapper.printDeviceSummary FUNCTIONS = {} FUNCTION_ARITY = {} def _add_global(name, arity, v): globals()[name] = v FUNCTIONS[v] = name FUNCTION_ARITY[v] = arity __all__.append(name) for i in range(16): no = i + 1 _add_global('NOTEOFF_CHAN%d' % no, 2, 0x80 + i) _add_global('NOTEON_...
FTERTOUCH_CHAN%d' % no, 2, 0xA0 + i) _add_global('CONTROLCHANGE_CHAN%d' % no, 2, 0xB0 + i) _add_global('PROGRAMCHANGE_CHAN%d' % no, 2, 0xC0 + i) _add_global('CHANAFTERTOUCH_CHAN%d' % no, 2, 0xD0 + i) _add_global('PITCHWHEEL_CHAN%d' % no, 2, 0xE0
+ i) _add_global('SYSTEMEXCL', 2, 0xf0) _add_global('MTC_QFRAME', 2, 0xf1) _add_global('SONGPOSPOINTER', 2, 0xf2) _add_global('SONGSELECT', 2, 0xF3) _add_global('RESERVED1', 2, 0xF4) _add_global('RESERVED2', 2, 0xF5) _add_global('TUNEREQ', 2, 0xF6) _add_global('EOX', 2, 0xF7) _add_global('TIMINGCLOCK', 2, 0xF8) _add...
class EnvironmentNotBootst
rapped(Exception): def __init__(self, environment): self.environment = environment def __s
tr__(self): return "environment %s is not bootstrapped" % self.environment
# Enthought library imports from traits.api import HasTraits, Int, Bool from kiva.trait_defs.api import KivaFont from enable.colors import ColorTrait class TextFieldStyle(HasTraits): """ This class holds style settings for rendering an EnableTextField. fixme: See docstring on EnableBoxStyle """ #...
ext (must be monospaced!) font = KivaFont("Courier 12") # The color of highlighted text highlight_color = ColorTrait((.65,0,0,1.0)) # The background color of highlighted items highlight_bgcolor = ColorTrait("lightgray") # The font for flagged text (must be monospaced!) highlight_font = Ki...
f pixels between each line line_spacing = Int(3) # Space to offset text from the widget's border text_offset = Int(5) # Cursor properties cursor_color = ColorTrait((0,0,0,1)) cursor_width = Int(2) # Drawing properties border_visible = Bool(False) border_color = ColorTrait((0,0,0,1...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ [tests/stdlib/test_cd.py] Test the cd command. """ import unittest import os import tempfile from ergonomica import ergo class TestCd(unittest.TestCase): """Tests the cd command.""" def test_cd(self): """ Tests the cd command. "
"" olddir = os.getcwd() newdir = tempfile.mkdtemp() ergo("cd {}".format(newdir))
self.assertEqual(os.getcwd(), newdir) ergo("cd {}".format(olddir)) self.assertEqual(os.getcwd(), olddir)
"""Django admin interface for the shopping cart models. """ from django.contrib import admin from shoppingcart.models import ( Coupon, CourseRegistrationCodeInvoiceItem, DonationConfiguration, Invoice, InvoiceTransaction, PaidCourseRegistrationAnnotation ) class SoftDeleteCouponAdmin(admin.Mo...
min for invoices. This is intended for the internal finance team to be able to view and update invoice information, including payments and refunds. """ date_hierarchy = 'created' can_delete = False readonly_fields = ('created', 'modified') search_field
s = ( 'internal_reference', 'customer_reference_number', 'company_name', ) fieldsets = ( ( None, { 'fields': ( 'internal_reference', 'customer_reference_number', 'created', ...
''' This module searches the shodan data for IPs using a user-specified https certificate ''' from common import helpers class Analytics: def __init__(self, cli_options): self.cli_name = "CertSearch" self.description = "Searches for user-provided HTTPS certificate" self.https_cert = '' ...
TPS certificate you want to search for." self.https_cert = raw_input(' \n\n[>] HTTPS Cert (including start and end tags): ').strip() for path, single_ip in all_ip_objects.iteritems(): if single_ip[0].shodan_info is not '' and\ 'No available information within Shodan abou...
if 'opts' in item: if 'pem' in item['opts']: if self.https_cert.strip() in item['opts']['pem'].encode('utf-8').replace('\n', '').replace('\r', ''): self.found_ips.append(single_ip[0].ip_address) if len(self.found_ips...
import sys import numpy as np import cv2 def main(): w, h = map(int, (sys.argv[1] if len(sys.argv) > 1 else '2048x1944').split('x')) imgfile = sys.argv[2] if len(sys.argv) > 2 else r'D:\Downloads\example-navcam-imgs\navcamTests0619\rubbleML-def-14062019-25.raw' imgout = sys.argv[3] if len(sys.ar...
dtype=np.uint16, count=w * h) raw_img = raw_img.reshape((h, w)) # flip rows pairwise final_img = raw_img[:, np.array([(i*2+1, i*2) for i in range(0, w//2)]).flatten()] cv2.imshow('img', final_img) cv2.waitKey() cv2.imwrite(imgout, final_img) if __name__ == '__main__': mai...
from .classification import Clas
sification from .ranking import
Ranking
from srqi.core import inquiry import matplotlib.pyplot as plt import numpy as np def get_accumulation_fig(proc): fig = plt.figure() plt.title("Accumulation During Procedure for Patient " + str(proc.PatientID) + " on " + str(proc.StudyDate)) event_starts = [e.DateTime_Started for e in proc.get_events...
mag_ax.plot(event_starts, [e.iiDiameter for e in proc.get_events()]) plt.ylim((200,500)) plt.ylabel('iiDiameter') # plot the event type on top of the mag plot a_events = [e for e in proc.get_event
s() if e.Irradiation_Event_Type =='Stationary Acquisition'] s_events= [e for e in proc.get_events() if e.Acquisition_Protocol=='Spot'] f_events = [e for e in proc.get_fluoro_events()] o_events = [e for e in proc.get_events() if not (e.Irradiation_Event_Type=="Stationary Acquisition" or e.Acquisition_Prot...
def _lsbStrToInt(str): return ord(str[0]) + (o
rd(str[1]) << 8) + (ord(str[2]) << 16) + (ord(str[3]) << 24)
rver.environment'] == 'production') tmpl = self.tmpl_lookup.get_template(tmpl_fname) # Render the template # If an exception occurs, render an error page showing the traceback try: return tmpl.render(**kwargs) except: traceback_...
input index as a dict inputd = config.file_dict(self.input_dir) tn_size = int(cherrypy.config.get('input.thumbnail.size', '192')) # TODO: build via list-comprehension for (input_id, input_info) in inputd.it
ems(): # convert the files to a list of file names # by splitting at blank characters # and generate thumbnails and thumbnail urls fname = input_info['files'].split() tn_fname = [thumbnail(self.input_dir + f, (tn_size, tn_size)) for f i...
import random import numpy as np import tensorflow as tf from language_model import LM from hparams import HParams def get_test_hparams(): return HParams( batch_size=21, num_steps=12, num_shards=2, num_layers=1, learning_rate=0.2, max_grad_norm=1.0, vocab_s...
p.zeros([batch_size, num_steps], np.int32) for i in range(batch_size): first = random.randrange(0, 20) for j in range(num_steps): x[i, j] = first + j y[i, j] = first + j + 1 return x, y, np.ones([batch_size, num_steps], np.uint8) class TestLM(tf.test.test_util.TensorF
lowTestCase): def test_lm(self): hps = get_test_hparams() with tf.variable_scope("model"): model = LM(hps) with self.test_session() as sess: tf.initialize_all_variables().run() tf.initialize_local_variables().run() loss = 1e5 for...
from flask import render_template from . import auth @auth.app_errorhandler(403) def page_not_found(e): return render_template('403.html'), 403 @auth.app_errorhandler(404) def page_not_found(e): return render_template('404.html'), 4
04 @auth.app_errorhandler(
500) def internal_server_error(e): return render_template('500.html'), 500
#!/usr/bin/env python # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor # Here's a UDP version of the simplest possible protocol cl
ass EchoUDP(DatagramProtocol): def datagramReceived(self, datagram, address):
self.transport.write(datagram, address) def main(): reactor.listenUDP(8000, EchoUDP()) reactor.run() if __name__ == '__main__': main()
umerator, expected_denominator) self.assertEqual(expected_repr, repr(r)) def test_float(self): for numerator, denominator, expected_numerator, expected_denominator in self.known_values: with self.subTest(numerator=numerator, denominator=denominator): r = Rational...
r1=r1, r2=r2, result=False): self.assertFalse(r1 <= r2) def test_eq(self): true_test_cases = [(Rational(), Rational()), (Rational(-1, 2), Rational(1, -2)), (Rational(1, 2), Rational(2, 4))] false_test_cases = [(Rational(-1, 2), ...
, (Rational(), Rational(1, 2)), (Rational(1, 2), Rational()), (Rational(), Rational(-1, 2)), (Rational(-1, 2), Rational(1, 2)), (Rational(1, 4), Rational(1, 2)), ...
# Copyright (c) 2020 Bartosz Szczesny <bszcz@bszcz.org> # This program is free software under the MIT license. print('\n# avoid new line at the beginning') s = """\ test """ print(s) print('\n# string are immutable') s = 'string' try: s[1] = 'p' except TypeError as e: print(e) print('\n# enumerate() functi...
ses s = sum(i * i for i in range(10)) print(s) print('\n# regex') import re # can use \1 in regex string r = re.sub(r'([0-9]) \1', r'\1', '1 2 2 3 3 3') print(r) print('\n# array') # store numbers of the same type efficiently import sys from array import array l = list([1, 2, 3, 4, 5]) a = array('B', [1, 2, 3, 4, 5...
i = 3.14159 print(pi.as_integer_ratio()) print('\n# float as hex') pi = 3.14159 print(pi.hex()) print(float.fromhex('0x1.921f9f01b866ep+1')) print('\n# precise sum') a = [0.3, 0.3, 0.3, 0.1] print(sum(a) == 1) print(math.fsum(a) == 1)
# coding: utf-8 from setuptools import setup, find_packages setup( name='tc_librato', version="0
.0.1", description='Thumbor Librato extensions', author='Peter Schröder, Sebastian Eichner', author_email='peter.schroeder@jimdo.com, sebastian.eichner@jimdo.com', zip_safe=False, include_package_data=True, packages=find_packages(), install_requires=[
'thumbor', 'librato-metrics', ] )
# coding=utf-8 fr
om django import http from django.conf import settings from django.contrib.auth import authenticate from django.uti
ls.cache import patch_vary_headers from registry.exceptions import RegistryException __author__ = 'pivstone' class CustomHeaderMiddleware(object): """ 增加自定头 """ def process_response(self, request, response): for key, value in settings.CUSTOM_HEADERS.items(): response[key] = value...
import os import sys import signal import time import subprocess WHO = None def handler(signum, frame): global WHO print('Signal handler', signum, WHO, frame) print('Disable handler', signum, WHO, frame) signal.signal(signal.SIGINT, signal.SIG_DFL) def main(argv): global WHO WHO = argv[1] ...
index, WHO) if WHO == 'parent': p.send_signal(signal.SIGINT) p.communicate() else: while True: time.sleep(1) print('S
leep 1 infinity') if __name__ == '__main__': main(sys.argv)
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2018-12-14 12:23 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('comissoes', '0018_auto_20180924_1724'),
] operations = [ migrations.AlterField( model_name='reuniao',
name='hora_fim', field=models.TimeField(blank=True, null=True, verbose_name='Horário de Término (hh:mm)'), ), ]
# Exceptions used throughout feedparser # Copyright 2010-2021 Kurt McKee <contactme@kurtmckee.org> # Copyright 2002-2008 Mark Pilgrim # All rights reserved. # # This file is a part of feedparser. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the follo...
CT, 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 O...
Y WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. __all__ = [ 'ThingsNobodyCaresAboutButMe', 'CharacterEncodingOverride', 'CharacterEncodingUnknown', 'NonXMLContentType', 'UndeclaredNamespace', ] class ThingsNobodyCaresAboutButMe(Exception): pass cl...
# -*- coding: utf-8 -*- ifac
e =
None
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Flash' db.create_table('cmsplugin_flash', ( ('cmsplugin_ptr', self.gf('django.db...
('file', self.gf('django.db.models.fields.files.FileField')(max_length=100)), ('width', self.gf('django.db.models.fields.CharField')(max_length=6)), ('height', self.gf('django.db.models.fields
.CharField')(max_length=6)), )) db.send_create_signal('flash', ['Flash']) def backwards(self, orm): # Deleting model 'Flash' db.delete_table('cmsplugin_flash') models = { 'cms.cmsplugin': { 'Meta': {'object_name': 'CMSPlugin'}, 'changed_date': ...
#!/usr/bin/python # # linearize.py: Construct a linear, no-fork, best version of the blockchain. # # # Copyright (c) 2013 The Carboncoin developers # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # import json import struct i...
plib import sys ERR_SLEEP = 15 MAX_NONCE = 1000000L settings = {} class CarboncoinRPC: OBJID = 1 def __init__(self, host, port, username, password): authpair = "%s:%s" % (username, password) self.authhdr = "Basic %s" % (base64.b64encode(authpair)) self.conn = httplib.HTTPConnection(host, port, False, 30) d...
+= 1 obj = { 'version' : '1.1', 'method' : method, 'id' : self.OBJID } if params is None: obj['params'] = [] else: obj['params'] = params self.conn.request('POST', '/', json.dumps(obj), { 'Authorization' : self.authhdr, 'Content-type' : 'application/json' }) resp = self.conn.getresponse()...
if h: for i in range(16): x[i] += y[i] for i in range(4): x[5*i] -= ld32(c[4*i:]) x[6+i] -= ld32(in_[4*i:]) for i in range(4): out[4*i:] = st32(out[4*i:], x[5*i]) out[16 + 4*i:] = st32(out[16 + 4*i:], x[6 + i]) else: for i in range(...
+= 1 c[j] = 1 m = m[j:]; n -= j add1305(h, c) for i in range(17): x[i] = 0 for j in range(17): x[i] += h[j]*(r[i - j] if j <= i else 320*r[i + 17 - j]) for i in range(17): h[i] = x[i] u = 0 for j
in range(16): u += h[j] h[j] = u & 255 u >>= 8 u += h[16]; h[16] = u & 3 u = 5*(u >> 2) for j in range(16): u += h[j] h[j] = u & 255 u >>= 8 u += h[16]; h[16] = u for j in range(17): g[j] = h[j] add1305(h...
ion.remove(component) else: selection.append(component) def setVerifiedValue(self, row, field, value): """Sets the *value* for *field* in the parameter indexed by *row*, only if the value is within set limits :param row: the ith parameter number :type row: int ...
def setParameterList(self, paramlist): """Clears and sets all parameters to *paramlist* :param paramlist: all parameters for this model to have :type paramlist: list<dict> """ self._parameters = paramlist def insertRow(self, position): """Inserts an em
pty parameter at index *position* :param position: order to insert new parameter to :type position: int """ if position == -1: position = self.nrows() defaultparam = { 'start': 0, 'step': 0, 'stop': 0, ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('Alarma', '0004_auto_20151025_0206'), ] operations = [ migrations.CreateModel( name='DjkombuMessage', ...
)), ('sent_at', models.DateTimeField(null=True, blank=True)), ('payload', models.TextField()),
], options={ 'db_table': 'djkombu_message', 'managed': False, }, ), migrations.CreateModel( name='DjkombuQueue', fields=[ ('id', models.IntegerField(serialize=False, primary_key=True)), ('n...
btitlesgr, title_query), executor.submit(self.vipsubs, title_query), executor.submit(self.podnapisi, title_query), executor.submit(self.subtitlesgr, season_episode_query) ] ...
query) ] for future in concurrent_futures.as_completed(threads): item = future.result() if not item:
continue self.list.extend(item) if not dup_removal: log_debug('Query used for subtitles search: ' + query) self.query = query self.query = py3_dec(self.query) else: # Manual query with concurre...
UTH_URL='{}'".format( v2AuthUrl ) ) print ";".join( export ) if persist: rcfile = os.environ[ 'HOME' ] + "/.swiftrc" logging.debug( "persisting environment variables" ) _persist( export, rcfile ) def csh(creds, auth_version, savepw=False, persist=False ): export = [] if auth_v...
dest = 'persist', action = 'store_false', help = "do not write credentials to $HOME/.swiftrc" ) aparser.add_argument( '--version', '-v', help = "show script version", action = 'version', version = "sw2account version {}".format( __version__)
) aparser.add_argument( '--debug', action = "store_true", help = "log level for client" ) if __name__ == "__main__": # Get the config first # Need to prime the pump to find defaults tparse = argparse.ArgumentParser() tparse.add_argument( '--config', ...
import numpy as np from . import finiteelements as fe from . import matrices from math import cos class Result: def __init__(self): pass def __init__(self, freq, u1, u2, u3, mesh, geometry): self.freq = freq self.u1 = u1 self.u2 = u2 self.u3 = u3 self.mesh ...
3, time): B = matrices.deriv_to_grad(self.geometry, x1, x2, x3) u = self.get_displacement_and_deriv(x1, x2, x3, time) grad_u = B.dot(u) E = matrices.grad_to_strain() # E_NL = grad_to_strain_nonlinear_matrix
(alpha1, alpha2, geometry, grad_u) return E.dot(grad_u) def get_strain_nl(self, x1, x2, x3, time): B = matrices.deriv_to_grad(self.geometry, x1, x2, x3) u = self.get_displacement_and_deriv(x1, x2, x3, time) grad_u = B.dot(u) E = matrices.grad_to_strain() ...
#!/usr/bin/env python # Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra # # This file is part of Essentia # # Essentia 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 ...
hile len(frame) != 0: spectrum = specAlg(windowingAlg(frame)) (freqs, mags) = sPeaksAlg(spectrum) hpcp = hpcpAlg(freqs,mags) self.assertTrue(not any(numpy.isnan(hpcp))) self.assertTrue(not any(numpy
.isinf(hpcp))) frame = fc(audio) suite = allTests(TestHPCP) if __name__ == '__main__': TextTestRunner(verbosity=2).run(suite)
required_sta
tes = ['accept', 'reject', 'init'] class TuringMachine(object):
def __init__(self, sigma, gamma, delta): self.sigma = sigma self.gamma = gamma self.delta = delta self.state = None self.tape = None self.head_position = None return def initialize(self, input_string): for char in input_string:...
#!/usr/bin/python3 # Copyright (c) 2016-2021 Dell Inc. or its subsidiaries. # # 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 requ...
ther express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import json import os from ironicclient import client from subprocess import check_output from credential_helper import CredentialHelper
def main(): parser = argparse.ArgumentParser() parser.add_argument("--power", required=True, default=None, choices=["on", "off", "reset", "cycle"], help="Control power state of all overcloud nodes") args = parser.parse_args() os_auth_url, os_tenant_nam...
# -*- coding: utf-8 -*- from __future__ import absolute_import from kombu.async.http.curl import READ, WRITE, CurlClient from kombu.tests.case import ( HubCase, Mock, call, patch, case_requires, set_module_symbol, ) @case_requires('pycurl') class test_CurlClient(HubCase): class Client(CurlClient): ...
1 _pycurl.error = KeyError x._timeout_check(_pycurl=_pycurl) x._multi.socket_all.return_value = None x._multi.socket_all.side_effect = _pycurl.error(333) x._timeout_check(_pycurl=_pycurl) def test_on_readable_on_writeable(self): with patch('kombu...
url=_pycurl) x._on_event.assert_called_with(fd, _pycurl.CSELECT_IN) x.on_writable(fd, _pycurl=_pycurl) x._on_event.assert_called_with(fd, _pycurl.CSELECT_OUT)
# -*- coding: utf-8 -*- """\ This is a python port of "Goose" orignialy licensed to Gravity.com under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Python port was written by Xavier Grangier for Recrutae Gravity.co...
'src': movie.src, }) return d
ata
med view Arguments: x -- optional dataset or list of datasets for x values y -- dataset or list of datasets title -- title of plot name -- name of plot view to use (if None, use default name) ''' if name is None: name = _PVNAME _process_line(x, y, title, name, 'add') ...
ven image explorer view order can be "none", "alpha", "chrono" prefix is the start of a regular expression to match the beginnings of filenames suffices can be a list of filename endings (eg. ["png", "tif"], each can be a regex) columns is the number of columns to use in grid (-1 makes grid square...
e returns number of images loaded ''' maxint = ((1<<30) - 1) + (1<<30) # maximum value for signed 32-bit integer return _plot_scanforimages(name, path, _order(order), prefix, suffices, columns, rowMajor, maxint, 1) def getbean(name=None): '''Get GUI bean (contains information from na...
from __future__ import print_function import os import sys import fnmatch import mmap def clean_files(path,pattern): all_files = os.listdir(path) filtered = fnmatch.filter(all_files,pattern+"*") for element in filtered: os.remove(os.path.join(path,element)) def find_files(path,target): matche...
if target in files: matches.append(root) return matches def find_dirs_files_pattern(path,pattern): matches = [] for root, dirnames, filenames in os.walk(path): for filename in fnmatch.filter(filenames, pattern): matches.appen
d([root,filename]) return matches def return_value(filename,pattern): if type(pattern) is str: pattern = pattern.encode() with open(filename, "r") as fin: # memory-map the file, size 0 means whole file m = mmap.mmap(fin.fileno(), 0, prot=mmap.PROT_READ) # ...
import serial import time ser = serial.Serial( port = "/dev/ttyACM0", baudrate = 9600, bytesize = serial.EIGHTBITS ) time.sleep(2) ser.write("\x36\x20\x00") print(hex(ord(ser
.read(1)))) print(hex(ord(ser.read(1)))) print(hex(ord(ser.read(1)))) print(hex(ord(ser.read(1)))) print(hex(ord(ser.read(1)))) print(hex(ord(ser.read(1)))) print(hex(ord(ser.read(1)))) print(hex(ord
(ser.read(1)))) print(hex(ord(ser.read(1)))) print(hex(ord(ser.read(1)))) print(hex(ord(ser.read(1)))) print(hex(ord(ser.read(1)))) print(hex(ord(ser.read(1))))
# -*- coding: utf-8 -*- ''' Exodus Add-on Copyright (C) 2016 Exodus This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any l...
'href') for url in r: links.append({'url': url, 'quality': i[1], 'info': info}) except: pass for i in links: try: url = i['url'] ur
l = client.replaceHTMLCodes(url) url = url.encode('utf-8') host = re.findall('([\w]+[.][\w]+)$', urlparse.urlparse(url.strip().lower()).netloc)[0] if not host in hostDict: raise Exception() host = client.replaceHTMLCodes(host) ...
DictLink':'datadict_link', 'DataDictWhole':'datadict_whole', 'Pickle':'pickle', 'RCD_Whole':'RCD_whole', 'RCD_Dicts':'RCD_dicts', 'RCD_Dicts_Whole':'RCD_dicts_whole', 'ChunkFunc':'chunkfunc', 'ChunkDict':'chunkdict', 'Model':'model'...
'Tests':'tests_', 'Val':'Val', 'Res':'Res', 'Locals':'_locals', 'Locals1':'_locals1', '_baseEAR':'_base_ear', '_finResid':'_fin_resid', '_extractValid':'_extract_valid', '_mergeAnsKey':'_merge_anskey', '_scor...
'_finFit':'_fin_fit', '_baseEst':'_base_est', '_restoreInvalid':'_restore_invalid', '_itemdiff':'_item_diff', } ############# ## Get ## ## Names ## ############# if mode == 'inspect': objs = [] names = [] # Import module for i in range(len...
"""manager.py: Flask-Script launcher for services using https://github.com/yabb85/ueki as prototype """ from os import path from flask_script import Manager, Server from publicAPI import create_app import prosper.common.prosper_logging as p_logging import prosper.common.prosper_config as p_config HERE = path.abspa...
ANAGER.add_command( 'debug', Server( use_debugger=True, port=CONFIG.get('DEBUG', 'PORT') ) ) if __name__ == '__main__': MANAGER.run
()
#!/usr/local/bin/python3 """ Copyright (c) 2015-2019 Ad Schellevis <ad@opnsense.org> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain th...
------ returns a list of pf tables (optional as a json container) """ import subprocess import sys import ujson if __name__ == '__main__': result = [] sp = subprocess.run(['/sbin/pfctl', '-sT'], capture_output=True, text=True) for line in sp.stdout.strip().split('\n'): result.append(line.strip(...
for table in result: print (table)
# check that we can do certain things without allocating heap memory import gc def f1(a): print(a) def f2(a, b=2): print(a, b) def f3(a, b, c, d): x1 = x2 = a x3 = x4 = b x5 = x6 = c x7 = x8 = d print(x1, x3, x5, x7, x2 + x4 + x6 + x8) global_var = 1 def test(): global global_var ...
l f1(i * 2 + 1) # binary operation with small ints f1(a=i) # keyword arguments f2(i) # default arg (second one) f2(i, i) # 2 args f3(1, 2, 3, 4) # function with lots of local state # call h with heap allocation disabled and all memory used up g
c.disable() try: while True: 'a'.lower # allocates 1 cell for boundmeth except MemoryError: pass test() gc.enable()
self): return self.uuid def setValue(self, value): self.value = value return 0 def getValue(self, value): return self.value def undefine(self): self.value = None return 0 class LibvirtVolumeBaseTestCase(test.NoDBTestCase): """Contains common setup and...
ubs.Set(utils, 'execute', fake_execute) self.useFixture(fakelibvirt.FakeLibvirtFixture()) class FakeLibvirtDriver(object): def __init__(self): self._host = host.Host("qemu:///system")
def _get_all_block_devices(self): return [] self.fake_conn = FakeLibvirtDriver() self.connr = { 'ip': '127.0.0.1', 'initiator': 'fake_initiator', 'host': 'fake_host' } self.disk_info = { "bus": "virtio", ...
# This file is part of Static Sauce <http://github.com/jdufresne/staticsauce>. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later ...
domain=settings.SITE_DOMAIN, path=route.fil
ename ) static_file = StaticFile(fmt_filename, uri) kwargs = {} if route.kwargs: kwargs.update(route.kwargs) kwargs.update(permutation) try: controller(static_file, **kwargs) ...
import os from setuptools import find_packages from setuptools import setup version = '1.0' project = 'kotti_mb' install_requires=[ 'Kotti', ], here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README.r
st')).read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read() setup(name=project, version=version, description="AddOn for Kotti", long_description=README + '\n\n' + CHANGES, classifiers=[ "Programming Language :: Python", "Framework :: Pyramid", "License :: Repoze Public Lice...
# This file is
part of Indico. # Copyright (C) 2002 - 2019 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from __future__ import unicode_literals def serialize_ip_network_group(group): """Serialize group to JSON-like obje...
'identifier': 'IPNetworkGroup:{}'.format(group.id), '_type': 'IPNetworkGroup' }
#!/usr/bin/env python # -*- coding: utf-8 -*- from collections import deque import SokoMove import Helper as hlp class SokoGoodFloors(): # Interface: # findGoodFloors() -> good-floor-List def __init__(self, pgs, pgdp, zfl, pp): self.pgs=pgs self.pgdp=pgdp self.zfl=zfl self.pp=pp self.bf=[]...
tion. def __pullableBordersForSingleBox(self, x, y): pbl=[] for i in range(4): if self.pgs[y+self.ppp
i[i][1]][x+self.pppi[i][0]]!="#": # das Feld, von dem der Player ziehen soll, ist frei if self.pgs[y+self.pdpi[i][1]][x+self.pdpi[i][0]]!="#": # das Feld, auf dem der Player landen soll, ist frei pbl.append(hlp.mpack((x+self.pppi[i][0], y+self.pppi[i][1]), i)) return(pbl) # #...
# -*- coding: utf-8 -*- # Copyright (c) 2004 - 2015 Detlev Offenbach <detlev@die-offenbachs.de> # """ Module implementing templates for the documentation generator (lists style). """ from __future__ import unicode_literals ################################################# ## Common templates for index and docu fil...
</dt> {{Links}} </dl>''' seeListEntryTemplate = \ '''<dd> {{Link}} </dd>''' seeLinkTemplate = '''<a style="color:{LinkColor}" {{Link}}''' sinceInfoTemplate = \ '''<p> <b>since</b> {{Info}} </p>''' ################################# ## Templates for index files ## ################################# indexBodyTemplat...
und-color:{Level1HeaderBgColor};color:{Level1HeaderColor}"> {{Title}}</h1> {{Description}} {{Subpackages}} {{Modules}}''' indexListPackagesTemplate = ''' <h3 style="background-color:{Level2HeaderBgColor};color:{Level2HeaderColor}"> Packages</h3> <table> {{Entries}} </table>''' indexListModulesTemplate = ''' <h3 style...
# Copyright 2019 Verily Life Sciences Inc. All Rights Re
served. # # 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 # distribute...
ONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Package marker file."""
# -*- coding:utf-8 -*- import mock import pytest import libpy import libpy.shadow class TestShadow(object): def test(self): proxy = libpy.shadow.Shadow(ShadowTarget()) assert isinstance(proxy, libpy.shadow.Shadow) assert proxy.a == mock.sentinel.proxy_target_a assert proxy.b == ...
proxy, 'a') assert proxy.a == 'new_value_for_a' def test_override(self): proxy = libpy.shadow.Shadow(ShadowTarget(), a='override_a') assert proxy.a == 'override_a' assert proxy.b == mock.sentinel.proxy_target_b proxy.b = 'dynamic_override_b' assert proxy.b == 'dynam...
nit__(self): self.b = mock.sentinel.proxy_target_b self._c = mock.sentinel.proxy_target_c
" __copyright__ = "Copyright 2011, The QIIME Project" __credits__ = [ "Antonio Gonzalez Pena", "Andrew J. King", "Michael S. Robeson", ] __license__ = "GPL" __version__ = "1.9.1-dev" __maintainer__ = "Antonio Gonzalez Pena" __email__ = "antgonza@gmail.com" from qiime.distance_matrix_from_mapping import com...
0, 0, 0, 0] def test_compute_distance_matrix_from_metadata_int(self): """ distance calculations on ints should throw no errors""" exp_out = array( [[0, 0, 92, 9096, 9992, 9894, 18898, 18898, 18898], [0, 0, 92, 9096, 9992, 9894, 18898, 18898, 18898], [92, 92, 0, 9188, 10084,...
[9992, 9992, 10084, 896, 0, 98, 8906, 8906, 8906], [9894, 9894, 9986, 798, 98, 0, 9004, 9004, 9004], [18898, 18898, 18990, 9802, 8906, 9004, 0, 0, 0], [18898, 18898, 18990, 9802, 8906, 9004, 0, 0, 0], ...
from django.utils.unittest.case import TestCase from scheduler.models import ScheduleGenerator from uni_info.models import Semester, Course class ScheduleGeneratorTest(TestCase): """ Test class for schedule generator, try different courses """ fixtures = ['/scheduler/fixtures/initial_data.json'] ...
icts """ soen341 = [s for s in Course.objects.all() if s.course_letters == 'SOEN' and s.course_numbers == '341'][0] soen343 = [s for s in Course.objects.all() if s.course_letters == 'SOEN' and s.course_numbers == '343']...
[s for s in Course.objects.all() if s.course_letters == 'SOEN' and s.course_numbers == '287'][0] course_list = [soen287, soen341, soen343] generator = ScheduleGenerator(course_list, self.fall_2013_semester) result = generator.generate_schedules() ...
from dja
ngo.conf.urls import patterns, include, url from django.contrib import admin import urls from apps.blog import views urlpatterns = patterns('', # Examples: # url(r'^$', 'gigsblog.views.home', name='home'), # url(r'^blog/', include('blog.urls')), # url(r'^admin/', include(admin.site.urls)
), url(r'^$', views.Index.as_view(), name='index'), url(r'^signup', views.SignUp.as_view(), name='signUp'), url(r'^login', views.Login.as_view(), name='login'), url(r'^logout', 'django.contrib.auth.views.logout',{'next_page':'/'}, name='logout'), url(r'^post/', include('urls.blog', namespace='post')...
#!/usr/bin/env python3 # # mmgen = Multi-Mode GENerator, a command-line cryptocurrency wallet # Copyright (C)2013-2022 The MMGen Project <mmgen@tuta.io> # Licensed under the GNU General Public License, Version 3: # https://www.gnu.org/licenses # Public project repositories: # https://github.com/mmgen/mmgen # http...
t seed length of {yellow(str(Seed.dfl_len))} bits\n' + 'If this is not what you want, use the --seed-len option' ) self._get_hash_preset() bw_seed_len = opt.seed_len or Seed.dfl_len qmsg_r('Hashing brainwallet data. Please wait...') # Use buflen arg of scrypt.hash() to get see
d of desired length seed = crypto.scrypt_hash_passphrase( self.brainpasswd.encode(), b'', d.hash_preset, buflen = bw_seed_len // 8 ) qmsg('Done') self.seed = Seed(seed) msg(f'Seed ID: {self.seed.sid}') qmsg('Check this value against your records') return True def _format(self): raise NotImpl...
#!/usr/bin/python # # Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the
"License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed
to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This example creates a campaign in a given ad...
#!/usr/bin/env python # B a r a K u d a # # L. Brodeau, 2017] import sys import numpy as nmp from PIL import Image import string import os from netCDF4 import Dataset narg = len(sys.argv) if narg != 2: print 'Usage: '+sys.argv[0]+' <mesh_mask>'; sys.exit(0) cf_mm = sys.argv[1] cf_bmp = string.repl...
sult.save(cf_bmp) print ' **
* Image '+cf_bmp+' saved!\n'
# -*- coding: utf-8 -*- ''' Created on Mar 12, 2012 @author: moloch Copyright 2012 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...
' name = self.__name__ return ( name[0].lower() + re.sub(r'([A-Z])', lambda letter: "_" + letter.group(0).lower(), na
me[1:] ) ) id = Column(Integer, unique=True, primary_key=True) # lint:ok uuid = Column(String(36), unique=True, default=generate_uuid) created = Column(DateTime, default=datetime.now) # Create an instance called "BaseObject" DatabaseObject = declarative_base(cls=_DatabaseObject)
!/usr/bin/env python # # Copyright (C) 2012 Strahinja Val Markovic <val@markovic.io> # # This file is part of MatchTagAlways. # # MatchTagAlways 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...
== 0 and previous_char == '
\n': return offset -1 break previous_char = char return None def LineColumnForOffsetInString( text, offset ): current_offset = -1 current_line = 1 current_column = 0 for char in text: current_offset += 1 current_column += 1 if char == '\n': current_line += 1 current...
from pymongo import MongoClient from pymongo.collection import Collection from pymongo.errors import AutoReconnect from django.conf import settings from types import FunctionType import functools import time __all__ = ("connection", "connections", "db", "get_db") """ Goals: * To provide a clean universal handler fo...
eturn old def __getitem__(self, func): old = getattr(self._database, func) if isinstance(old, Collection): return CollectionWrapper(old) return old def __repr__(self): return "<DatabaseWrapper %s>" % self._database.__repr
__() def __str__(self): return "<DatabaseWrapper %s>" % self._database.__str__() class ConnectionWrapper(object): def __init__(self, connection, default=None): self._connection = connection self._databases = {} self._default = default def __getattr__(self, alias): ...
#!/usr/bin/env python # encoding: utf-8 # Thomas Nagy, 2006-2010 (ita) """ Support for the KDE4 libraries and msgfmt """ import os, sys, re from waflib import Options, TaskGen, Task, Utils from waflib.TaskGen import feature, after_method @feature('msgfmt') def apply_msgfmt(self): """ Process all languages to creat...
Task): """ Transform .po files into .mo files """ color = 'BLUE' run_str = '${MSGFMT} ${SRC} -o ${TGT}' def configure(self): """ Detect kde4-config and set various variables for the *use* system:: def options(opt): opt.load('compiler_cxx kde4') def configure(conf): conf.load('compiler_cxx kde4')
def build(bld): bld.program(source='main.c', target='app', use='KDECORE KIO KHTML') """ kdeconfig = self.find_program('kde4-config') prefix = self.cmd_and_log('%s --prefix' % kdeconfig).strip() fname = '%s/share/apps/cmake/modules/KDELibsDependencies.cmake' % prefix try: os.stat(fname) except OSError: fna...
""" This is a comment """ #try: # this part to import as part of the DIRAC framework import xml.sax from xml.sax.handler import ContentHandler from DIRAC.Core.Workflow.Parameter import * from DIRAC.Core.Workflow.Module import * from DIRAC.Core.Workflow.Step import * from DIRAC.Core.Workflow.Workflow import Workf...
ons.append(self.stack.pop()) elif name == "StepInstance": self.root.step_instances.append(self.stack.pop()) elif name == "ModuleDefinition": self.root.addModule(self.stack.pop()) elif name == "ModuleInstance": obj=self.stack.pop() self.stack[len(self.stack)-1].module_instances.append...
print "UNTREATED! endElement", name def getCharacters(self): # combine all strings and clear the list ret = ''.join(self.strings) self.clearCharacters() return str(ret) def clearCharacters(self): del self.strings self.strings=[] def characters(self, content): self.strings.appe...
#encoding:utf-8 subreddit = 'getm
otivated' t_channel = '@r_getmotivated' def send_post(submission, r2t): return r2t.send_simple(subm
ission)
'), 'LIST,len=5') self.assertEquals(token_value('container(TUPLE,len=2)'), 'TUPLE,len=2') self.assertEquals(token_value('number(42)'), '42') self.assertEquals(token_value('string("ab(c)")'), '"ab(c)"') def test_token_length(self): self.assertEquals(token_length('key(field1)'), 1) ...
s[0][0][0][1].token, 'string("s2")') self.assertEquals(len(s[0]
[0][0][1]), 0) self.assertEquals(s[0][0][0][2].token, 'string("s3")') self.assertEquals(len(s[0][0][0][2]), 0) self.assertEquals(s[0][0][1].token, 'wrapper(OPTIONAL)') self.assertEquals(len(s[0][0][1]), 1) self.assertEquals(s[0][0][1][0].token, 'string("s4")') self.assert...
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry.page import page as page_module from telemetry.page import page_set as page_set_module class PathologicalMobileSitesPage(page_module.Page): ...
__( url=url, page_set=page_set, credentials_path='data/credentials.json') self.user_agent_type = 'mobile' self.archive_data_file = 'data/pathological_mobile_sites.json' def RunPageInteractions(self, act
ion_runner): interaction = action_runner.BeginGestureInteraction( 'ScrollAction', is_smooth=True) action_runner.ScrollPage() interaction.End() class PathologicalMobileSitesPageSet(page_set_module.PageSet): """Pathologically bad and janky sites on mobile.""" def __init__(self): super(Path...
import os import shutil import logging import tarfile import tempfile import subprocess from threading import Thread class TarToWebmCompressor(object): @staticmethod def compress(filename): thread = Thread(target=TarToWebmCompressor._compress, args=(filename,)) thread.start() @staticmetho...
null = 'NUL' cmd1 = 'ffmpeg -y -v quiet -nostats -f image2 -i "%s" -pass 1 -f rawvideo %s %s' % (input_images, vopts, null) cmd2 = 'ffmpeg -y -v quiet -nostats -f image2 -i "%s" -pass 2 %s "%s"' % (input_images, vopts, hour_webm) try: subprocess.check_call(cmd1)
subprocess.check_call(cmd2) os.remove(filename) except subprocess.CalledProcessError: logging.exception("Failed to compress %s file" % (filename,)) finally: shutil.rmtree(tmp_dir, ignore_errors=True) # combine 1-hour movies to daily movies # combined...
#! /usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'Lunzhy' import sys from PyQt4.QtGui import * from PyQt4.QtCore import * from pyshanbay.shanbay import VisitShanbay from pyshanbay import page_parser as parser from gui.ui_main import UIMainWidget class MainForm(QWidget): def __init__(self): s...
TableWidgetItem(member['nickname']) self.table.setItem(row_index, 0, new_item) new_item = QTableWidgetItem(str(member['checked_today'])) self.table.setItem(row_index, 1, new_item) return def show_selected(self): select = self.table.selectionModel().selectedRows()...
ct[0].row(), 0).text()) print(self.table.item(select[0].row(), 1).text()) return def get_data(): shanbay = VisitShanbay() shanbay.login() page_members = shanbay.members() total_page = parser.total_page_members(page_members) pages = [] for page in range(1, int(total_page) + 1...
from typing import List import click from valohai.internals.pipeline import get_pipeline_from_source from valohai.yaml import config_to_yaml from valohai_yaml.objs.config import Config from valohai_cli.ctx import get_project from valohai_cli.exceptions import ConfigurationError from valohai_cli.messages import error,...
_config = old_config.merge_with(new_config) if old_config.serialize() != merged_config.serialize(): with open(yaml_filename, "w") as out_file: out_file.write(config_to_yaml(merg
ed_config)) did_update = True if did_update: info(f"{yaml_filename} updated.") else: info(f"{yaml_filename} already up-to-date.") def get_current_config(project: Project) -> Config: try: return project.get_config() except FileNotFoundError as fnfe: valohai_y...
import os from pip.backwardcompat import urllib from tests.lib.path import Path from pip.index import package_to_requirement, HTMLPage from pip.index import PackageFinder, Link, INSTALLED_VERSION from tests.lib import path_to_url from string import ascii_lowercase from mock import patch def test_package_name_should_b...
p://supervisord.org/">http://supervisord.org/</a> </li>""", "supervisor") links = list(page.scraped_rel_links()) assert len(links) == 1 assert links[0].url == 'http://supervisord.org/' def test_sort_locations_file_find_link(data): """ Test that a file:// find-link dir gets listdir run ...
finder = PackageFinder([data.find_links], []) files, urls = finder._sort_locations([data.find_links]) assert files and not urls, "files and not urls should have been found at find-links url: %s" % data.find_links def test_sort_locations_file_not_find_link(data): """ Test that a file:// url dir that's ...
#!/usr/bin/python # -*- coding: utf-8 -*- # # This file is part of box-linux-sync. # # Copyright (C) 2013 Vítor Brandão <noisebleed@noiselabs.org> # # box-linux-sync is free software; you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the # Free Software...
print("Waiting",secs,"seconds before starting (Control-C to abort)...") pr
int(doing+" in: ", end=' ') ticks=list(range(secs)) ticks.reverse() for sec in ticks: sys.stdout.write(colorize("red", str(sec+1)+" ")) sys.stdout.flush() time.sleep(1) print()
": 1, "test2": "{{ beer }}"}, ["{{ beer }}", 1],
) def test_time_zone(): """Test time zone validation.""" schema = vol.Schema(cv.time_zone) with pytest.raises(vol.MultipleI
nvalid): schema("America/Do_Not_Exist") schema("America/Los_Angeles") schema("UTC") def test_date(): """Test date validation.""" schema = vol.Schema(cv.date) for value in ["Not a date", "23:42", "2016-11-23T18:59:08"]: with pytest.raises(vol.Invalid): schema(value) ...
from __future__ import division import numpy as np from fatiando.gravmag.euler import Classic, ExpandingWindow, MovingWindow from fatiando.gravmag import sphere, fourier from fatiando.mesher import Sphere from fatiando import utils, gridder model = None xp, yp, zp = None, None, None inc, dec = None, None struct_ind = ...
ExpandingWindow w Classic for sphere model + magnetic data" euler = ExpandingWindow( Classic(x, y, z, field, x
deriv, yderiv, zderiv, struct_ind), center=[1000, 1000], sizes=np.linspace(100, 2000, 20)).fit() assert (base - euler.baselevel_)/base <= precision, \ 'baselevel: %g estimated: %g' % (base, euler.baselevel_) assert np.all((pos - euler.estimate_)/pos <= precision), \ 'position...
#!/usr/bin/env python import os, sys try: from Tkinter import * except: sys.stderr.write('Please install Tkinter!\n\n') sys.exit(1) root = Tk() root.title('Wavelet Demo') wtype = StringVar() wtype.set('b') type_frame = Frame(root,relief=SUNKEN,borderwidth=2) type_frame.pack(side=TOP,fill=X) Label(type_...
IZONTAL, variable=pclip,length=200) scale.pack(side=RIGHT) Label(pclip_frame,text='Threshold\nPercentile').pack(side=RIGHT,anchor=SE) frame = Frame(root) frame.pack(side=TOP,fill=X) quit = Button(frame,text='Quit',background='red',command=sys.exit) quit.pack
(side=RIGHT) def scons(): 'Get parameters from GUI and pass them to SCons' os.system ('scons -Q type=%s pclip=%d view' % (wtype.get(),pclip.get())) cycle = Button(frame,text='Run',background='yellow',command=scons) cycle.pack() root.mainloop()