code
stringlengths
1
199k
from binascii import hexlify import hashlib try: import Crypto.Random.random secure_random = Crypto.Random.random.getrandbits except ImportError: import OpenSSL secure_random = lambda x: long(hexlify(OpenSSL.rand.bytes(x>>3)), 16) class DiffieHellman(object): """ An implementation of the Diffie-...
from __future__ import unicode_literals from django.db import models, migrations from decimal import Decimal class Migration(migrations.Migration): dependencies = [ ('products', '0001_initial'), ('locations', '0001_initial'), ] operations = [ migrations.CreateModel( name=...
from corpustools.gui.config import * def test_preferences(qtbot, settings): dialog = PreferencesDialog(None, settings) qtbot.addWidget(dialog) dialog.accept()
from flask import Blueprint, render_template, request, redirect, url_for, flash, current_app from flask_security.decorators import login_required from flask_security import current_user, roles_accepted from recruit_app.user.models import EveCharacter from recruit_app.recruit.models import HrApplication, HrApplicationCo...
import unittest import IECore import Gaffer import GafferUI import GafferUITest QtGui = GafferUI._qtImport( "QtGui" ) class GridContainerTest( GafferUITest.TestCase ) : def testSimpleSetItem( self ) : c = GafferUI.GridContainer() b1 = GafferUI.Button( "b1" ) b2 = GafferUI.Button( "b2" ) b3 = GafferUI.Button( "...
import El El.Initialize() orders = El.DistMultiVec(El.iTag) orders.Resize(1, 1) orders.Set(0, 0, 1) firstInd = El.DistMultiVec(El.iTag) firstInd.Resize(1, 1) firstInd.Set(0, 0, 0) c = El.DistMultiVec() c.Resize(1, 1) c.Set(0, 0, -1.) h = El.DistMultiVec() h.Resize(1, 1) h.Set(0, 0, 1.) b = El.DistMultiVec() b.Resize(0,...
import sys PY2 = sys.version_info[0] == 2 if PY2: ustr = unicode else: ustr = str if PY2: exec('def reraise(tp, value, tb):\n raise tp, value, tb') else: def reraise(tp, value, tb): raise value.with_traceback(tb) if PY2: exec('def exec_(code, globals_):\n ' 'exec code in globals_') ...
""" Model tests for Microformats Author: Nicholas H.Tollervey """ import datetime from django.test.client import Client from django.test import TestCase from django.contrib.auth.models import User from microformats.models import * class ModelTestCase(TestCase): """ Testing Models """ # R...
import unittest import time from rdkit import Chem from rdkit.Chem import MCS def load_smiles(text): mols = [] for line in text.strip().splitlines(): smiles = line.split()[0] mol = Chem.MolFromSmiles(smiles) assert mol is not None, smiles mols.append(mol) return mols _ignore = object() class MCSTe...
from setuptools import setup, find_packages setup( name='glamkit-blogtools', author='Greg Turner', author_email='greg@interaction.net.au', version='2.0.0', description='Mini framework for making Django blog apps.', url='http://github.com/ixc/glamkit-blogtools', packages=find_packages(), ...
"""Package contenant la commande 'vent' et ses sous-commandes. Dans ce fichier se trouve la commande même. """ from primaires.interpreteur.commande.commande import Commande from .creer import PrmCreer from .detruire import PrmDetruire from .direction import PrmDirection from .force import PrmForce from .info import Prm...
from django.contrib.auth.models import User class EmailOrUsernameModelBackend(object): supports_object_permissions = False supports_anonymous_user = False supports_inactive_user = False def authenticate(self, username=None, password=None): if '@' in username: kwargs = {'email__iexact...
from optparse import OptionParser import os import shutil import subprocess import sys import tempfile import urllib2 g_temp_dirs = [] def RunOrDie(command): rc = subprocess.call(command, shell=True) if rc != 0: raise SystemExit('%s failed.' % command) def TempDir(): """Generate a temporary directory (for dow...
import re from faker import Faker from django.utils.crypto import get_random_string from django_db_sanitizer.exceptions import SanitizerValidationException from django_db_sanitizer.sanitizers.base import BaseSanitizer from django_db_sanitizer.settings import TEXT_LOCALE class EmptyStringSanitizer(BaseSanitizer): ""...
# Copyright (c) Microsoft Corporation. All rights reserved. from __future__ import print_function, with_statement, absolute_import import errno import itertools import json import os import os.path from socket import create_connection import sys import time import traceback from .socket import TimeoutError, convert_eo...
import datetime def parse_value(value): if len(value) == 0 or value == 'None': return ('NoneType', 'None') elif len(value) > 2 and value[0] == 'u' and \ ((value[1] == "'" and value[-1] == "'") or \ (value[1] == '"' and value[-1] == '"')): return ('unicode', value[2:-1]) ...
import json import logging from bson import ObjectId from flask import Blueprint, Response, flash, jsonify, redirect, render_template, request, url_for from flask_login import current_user from werkzeug.datastructures import Headers from scout.constants import ACMG_COMPLETE_MAP, ACMG_MAP, CASEDATA_HEADER, CLINVAR_HEADE...
import pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artificial_dataset as art art.process_dataset(N = 128 , FREQ = 'D', seed = 0, trendtype = "PolyTrend", cycle_length = 7, transform = "Quantization", sigma = 0.0, exog_count = 0, ar_order = 0);
from django.db.backends.base.features import BaseDatabaseFeatures from django.db.utils import InterfaceError from django.utils.functional import cached_property class DatabaseFeatures(BaseDatabaseFeatures): allows_group_by_selected_pks = True can_return_id_from_insert = True can_return_ids_from_bulk_insert ...
""" Logistic Regression """ import numbers import warnings import numpy as np from scipy import optimize, sparse from scipy.misc import logsumexp from scipy.special import expit from .base import LinearClassifierMixin, SparseCoefMixin, BaseEstimator from .sag import sag_solver from ..preprocessing import LabelEncoder, ...
from bisect import bisect from mptypes import mp, mpf, mpmathify from functions import ldexp, nthroot, log, fac from calculus import polyval def ode_taylor(derivs, x0, y0, tol_prec, n): h = tol = ldexp(1, -tol_prec) dim = len(y0) xs = [x0] ys = [y0] x = x0 y = y0 orig = mp.prec try: ...
from .util import cli_run def test_list(client, authorized_user): output = cli_run(client, ['user', 'list']) assert authorized_user.short_id in output def test_update(client, authorized_user): name = authorized_user.name output = cli_run(client, ['user', 'update', '--name',...
from twisted.plugin import IPlugin from txircd.module_interface import IModuleData, ModuleData from txircd.utils import ipAddressToShow from zope.interface import implementer from typing import Callable, List, Tuple @implementer(IPlugin, IModuleData) class SnoConnect(ModuleData): name = "ServerNoticeConnect" def acti...
import numpy as np def iris_data(): """Iris flower dataset. Returns -------- X, y : [n_samples, n_features], [n_class_labels] X is the feature matrix with 150 flower samples as rows, and the 3 feature columns sepal length, sepal width, petal length, and petal width. y is a 1-dime...
""" Copyright (c) 2017 Red Hat, Inc All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. """ import pytest import os from atomic_reactor.plugin import PreBuildPluginsRunner, PluginFailedException from atomic_reactor.plugins import pre_p...
from libtaxii.scripts import TaxiiScript, add_poll_response_args import libtaxii.messages_11 as tm11 import os import sys import dateutil.parser import datetime from libtaxii.common import gen_filename from libtaxii.constants import * class PollClient11Script(TaxiiScript): parser_description = 'The TAXII 1.1 Poll C...
from __future__ import absolute_import import base64 from django.http import HttpRequest from rest_framework.response import Response from sentry.api.base import Endpoint from sentry.api.paginator import GenericOffsetPaginator from sentry.models import ApiKey from sentry.testutils import APITestCase class DummyEndpoint...
from __future__ import absolute_import from django.db import models from users.models import User class Player(models.Model): # Make user nullable because we might want to have computer players, or # guests user = models.ForeignKey(User, null=True) @property def name(self): if self.user is n...
import yaml import json with open("phonondb.yaml", 'r') as stream: data = yaml.load(stream) print("number of materials:",len(data)) with open("phonondb.json", 'w') as stream: json.dump(data,stream,indent=4)
import sys, os cwd = os.getcwd() project_root = os.path.dirname(cwd) sys.path.insert(0, project_root) import doc_test_han extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' project = u'doc_test_han' copyright = u'2014, fingul' version =...
import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Image.default_credit' db.add_column('filer_image', 'default_credit', self.gf('django.db.models.fi...
from django.template import Library from constance import config register = Library() def filer_staticmedia_prefix(): """ Returns the string contained in the setting FILER_STATICMEDIA_PREFIX. """ try: from .. import settings except ImportError: return '' return settings.FILER_STA...
import math import pyglet from pyglet.gl import * class SmoothLineGroup(pyglet.graphics.Group): def set_state(self): glPushAttrib(GL_ENABLE_BIT) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glEnable(GL_LINE_SMOOTH) glLineWidth(2) def unset_state(se...
import getpass if getpass.getuser() == 'brodyh': proj = '/Users/brodyh/Documents/projects/mechturk' dropbox = '/Users/brodyh/Dropbox/projects/mechturk/errors/' trash = '/afs/cs.stanford.edu/u/brodyh/trash/' try: dropbox_access_token = open(proj + '/verification/dropbox_access_token.txt').readlin...
from __future__ import absolute_import from django.db import IntegrityError, transaction from rest_framework import serializers, status from rest_framework.response import Response from sentry.api.base import DocSection from sentry.api.bases.team import TeamEndpoint, TeamPermission from sentry.api.serializers import se...
''' bypass.py: EMANE Bypass model for CORE ''' import sys import string from core.api import coreapi from core.constants import * from .emane import EmaneModel class EmaneBypassModel(EmaneModel): def __init__(self, session, objid = None, verbose = False): EmaneModel.__init__(self, session, objid, verbose) ...
from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from __future__ import print_function import os import tempfile import numpy as np import pandas as pd from sktracker import data from sktracker.io import StackIO from sktracker.io import ObjectsIO from sktrac...
from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ("wagtailcore", "0045_assign_unlock_grouppagepermission"), ("cms", "0024_lettertemplatepage"), ] operations = [ migrations.CreateModel( name="...
class Author(): """Author representation""" def __init__(self): self.name = "hervé" self.email = "herveberaud.pro@gmail.com" class Repos(): """Repository representation""" def __init__(self): self.github = "4383" self.pypi = "4383" self.gitlab = "hberaud" class Pr...
import numpy as np import numpy.testing as npt from sklearn.ensemble import RandomForestRegressor from sklearn.ensemble import BaggingRegressor from sklearn.svm import SVR import forestci as fci def test_random_forest_error(): X = np.array([[5, 2], [5, 5], [3, 3], [6, 4], [6, 6]]) y = np.array([70, 100, 60, 100...
"""home URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based v...
"""Support for Acmeda Roller Blinds.""" from __future__ import annotations from homeassistant.components.cover import ( ATTR_POSITION, SUPPORT_CLOSE, SUPPORT_CLOSE_TILT, SUPPORT_OPEN, SUPPORT_OPEN_TILT, SUPPORT_SET_POSITION, SUPPORT_SET_TILT_POSITION, SUPPORT_STOP, SUPPORT_STOP_TILT,...
""" Translate a maf file containing gap ambiguity characters as produced by 'maf_tile_2.py' to a new file in which "#" (contiguous) is replaced by "-" and all other types are replaces by "*". TODO: This could be much more general, should just take the translation table from the command line. usage: %prog < maf > ...
import logging module_logger = logging.getLogger(__name__) module_logger.addHandler(logging.NullHandler()) class MixsException(Exception): """ Exception for the MIXS Attributes: key (str): The key for the exception. message (str): The error message to provide for when the exception is thrown...
from msrest.serialization import Model class BgpSettings(Model): """BgpSettings. :param asn: The BGP speaker's ASN. :type asn: long :param bgp_peering_address: The BGP peering address and BGP identifier of this BGP speaker. :type bgp_peering_address: str :param peer_weight: The weight added...
"""Add receiving, shipping and inventory_transaction related tables Revision ID: 1b3411739b82 Revises: 7b2d863b105 Create Date: 2015-07-03 21:45:51.072263 """ revision = '1b3411739b82' down_revision = '7b2d863b105' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic ...
'''Skeleton for regular Python programs generating a web page with a template. ''' def main(): ## get data from user's keyboard # pythonVariable = input(yourPrompt) # for each variable ## ... contents = processInput(inputVariables) # REPLACE inputVariables with yours browseLocal(contents) def proces...
import logging import json import redis from django.contrib.auth.models import User from django.conf import settings from django.conf.urls import url from django.shortcuts import get_object_or_404 from django.core.cache import cache from tastypie import fields from tastypie.authorization import DjangoAuthorization from...
"""Unit tests for functions calling combinations of tools externally.""" from pathlib2 import Path import pytest from imfusion.external import compound class TestSortBam(object): """Unit tests for the sambamba_sort function.""" def test_sambamba_call(self, mocker): """Tests call that uses sambamba.""" ...
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 'Coupon' db.create_table('coupons_coupon', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key...
from Defines import * from SubstrateRenderer import * populationFileName = "../../out/Results/GoScalingBasic_T2718/GoScalingBasic_T2718_Euler_Run$RUN_NUMBER$.xml.backup.xml.gz" outputDirName = "../../out/images" CAMERA_SPEED = 5 class HyperNEATVisualizer(object): def __init__(self): # Number of the glut win...
import pygubu import sys, os, yaml from collections import OrderedDict def represent_ordereddict(dumper, data): value = [] for item_key, item_value in data.items(): node_key = dumper.represent_data(item_key) node_value = dumper.represent_data(item_value) value.append((node_key, node_value)) return yaml.nodes.M...
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import Profile from .forms import ProfileCreationForm def deactivate(modeladmin, request, queryset): queryset.update(is_active=True) deactivate.short_description = "Deactivate selected users" class ProfileAdmin(UserAdmin):...
__author__ = 'Rolf Jagerman' import os from PySide import QtGui from loadui import loadUi from config import UI_DIRECTORY from authentication import AuthenticationClient, AuthenticationListener from drawers import Drawers class Welcome(QtGui.QFrame, AuthenticationListener): """ The add delivery form that enable...
import re import time from urlparse import urlparse from textwrap import dedent from browser_settings import SERVER_IP from functionaltest import FunctionalTest, snapshot_on_error class Test_2532_LambdasInCells(FunctionalTest): @snapshot_on_error def test_lambda_in_cell(self): # * Harold logs in to Diri...
from abc import ABCMeta, abstractmethod import zmq from six import add_metaclass, iteritems from fuel.iterator import DataIterator from fuel.server import recv_arrays @add_metaclass(ABCMeta) class AbstractDataStream(object): """A stream of data separated into epochs. A data stream is an iterable stream of examp...
import json import traceback from typing import Dict, List, Union import demistomock as demisto # noqa: F401 from CommonServerPython import * # noqa: F401 def hook(obj: Dict) -> Dict: new_obj = {} for k, v in obj.items(): try: new_obj[k] = json.loads(v) except Exception: ...
version = '5972'
import argparse import re import sys import pybedtools as pbt def filter_sample_clusters(fin, size_cutoff=0, sample="", reformat=True, excluded=pbt.BedTool("", from_string=True), contigs=[], delim="___"): """ Filter clusters for mapq=0 pairs and cluster size...
from enum import Enum, auto class Position: def __init__(self, row, col): self.row = row self.col = col def id(self): """Runtime: O(row + col)""" return str(self.row) + str(self.col) class Direction(Enum): """Enum for cardinal directions""" N = auto() NE = auto() ...
from swgpy.object import * def create(kernel): result = Tangible() result.template = "object/tangible/wearables/jacket/shared_jacket_s13.iff" result.attribute_template_id = 11 result.stfName("wearables_name","jacket_s13") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
from swgpy.object import * def create(kernel): result = Creature() result.template = "object/mobile/shared_warren_teraud_loyalist_cyborg_s02.iff" result.attribute_template_id = 9 result.stfName("npc_name","warren_teraud_loyalist_cyborg") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
"""Master which prepares work for all workers. Evaluation of competition is split into work pieces. One work piece is a either evaluation of an attack on a batch of images or evaluation of a defense on a batch of adversarial images. Work pieces are run by workers. Master prepares work pieces for workers and writes them...
from querybuilder.query import Query from querybuilder.tests.query_tests import QueryTestCase, get_comparison_str class LimitTest(QueryTestCase): def test_limit(self): query = Query().from_table( table='test_table' ).limit(10) query_str = query.get_sql() expected_query = ...
from swgpy.object import * def create(kernel): result = Creature() result.template = "object/mobile/shared_dressed_commoner_naboo_zabrak_male_01.iff" result.attribute_template_id = 9 result.stfName("npc_name","zabrak_base_male") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
from handler.base_plugin import CommandPlugin import datetime class TimePlugin(CommandPlugin): __slots__ = ("delta", "message", "days") def __init__(self, *commands, prefixes=None, strict=False, offseth=3, offsetm=0, message=None): """Answers with current date and time.""" if not commands: ...
""" emailaddress.py An implentation of rfc 5322 email address checking. See http://tools.ietf.org/html/rfc5322 for the full specification. This program implements the grammer for email address validation in sections 3.4 and 3.4.1 and related grammers requird by those sections. This is an example of translating a gramme...
def _name_to_value(name): val = {'A': 0, 'B': 2, 'C': 3, 'D': 5, 'E': 7, 'F': 8, 'G': 10} mod = {'#': 1, 'b': -1} result = val[name[0]] + sum(mod[m] for m in name[1:]) return result % 12 def _value_to_name(value, accidentals='#'): name = {0: 'A', 2: 'B', 3: 'C', 5: 'D', 7: 'E', 8: 'F', 10: 'G'} ...
import haydi as hd def test_immutable_domain(): r = hd.Range(10) a = list(r) b = list(r) assert a == b == range(10) def test_immutable_iterate(): r = hd.Range(10) a = list(r) b = list(r) assert a == b == range(10) def test_immutable_factory(): r = hd.Range(10).filter(lambda x: x % 2 ...
import picamera from time import sleep from PIL import Image camera = picamera.PiCamera() try: #capture at maximum resolution (~5MP) camera.resolution = (1280, 720) camera.framerate = 90 camera.shutter_speed = 1000 camera.iso = 50 camera.vflip = True #allow camera to AWB sleep(1) camera.capture('1_unedited.jpg...
from termcolor import colored import time import sys import ProjectEuler as pe INIT_TIME = time.time() def perf(): # show the performance time millis = time.time() - INIT_TIME print("Performance time: %s" % millis) def error(): # massage if not supported entering print colored("..::Incorrect amount ...
import collections, string import os.path datafile = os.path.join(os.path.split(__file__)[0], 'data.txt') text = ''.join([c for c in open(datafile).read() if c in string.letters]) print text print r'http://www.pythonchallenge.com/pc/def/%s.html' % (text,)
""" The TreeModel for the URL list in the Url Tab. """ from gi.repository import Gtk class WebModel(Gtk.ListStore): """ WebModel derives from the ListStore, defining te items in the list """ def __init__(self, obj_list, dbase): Gtk.ListStore.__init__(self, str, str, str, object) self.db ...
""" Test that no StopIteration is raised inside a generator """ import asyncio class RebornStopIteration(StopIteration): """ A class inheriting from StopIteration exception """ def gen_ok(): yield 1 yield 2 yield 3 def gen_stopiter(): yield 1 yield 2 yield 3 raise StopIteration ...
from pyanaconda.i18n import _ __all__ = ["ERROR_RAISE", "ERROR_CONTINUE", "ERROR_RETRY", "ErrorHandler", "InvalidImageSizeError", "MissingImageError", "MediaUnmountError", "MediaMountError", "ScriptError", "CmdlineError", "errorHandler"] class InvalidImageSizeError(Exception)...
"""Zenodo Dublin Core mapping test.""" from __future__ import absolute_import, print_function, unicode_literals from datetime import datetime, timedelta from zenodo.modules.records.serializers import dc_v1 def test_minimal(app, db, minimal_record_model, recid_pid): """Test identifiers.""" obj = dc_v1.transform_...
"""Discover Philips Hue bridges.""" from . import SSDPDiscoverable class Discoverable(SSDPDiscoverable): """Add support for discovering Philips Hue bridges.""" def get_entries(self): """Get all the Hue bridge uPnP entries.""" return self.find_by_device_description({ "manufacturer": "...
from runtest import TestBase import subprocess as sp import os TDIR='xxx' class TestCase(TestBase): def __init__(self): TestBase.__init__(self, 'openclose', """ 1.088 us [18343] | __monstartup(); 0.640 us [18343] | __cxa_atexit(); [18343] | main() { 89.018 us [18343] | fopen(); 37.32...
"""Utilities for assertion debugging""" import py BuiltinAssertionError = py.builtin.builtins.AssertionError _reprcompare = None def format_explanation(explanation): """This formats an explanation Normally all embedded newlines are escaped, however there are three exceptions: \n{, \n} and \n~. The first tw...
"""pylint ticket #60828""" __revision__ = 0 def reimport(): """docstring""" import os
import sys from mappings import offset2bn, bn2dbpedia frame_type = dict() frequencies = dict() with open(sys.argv[1]) as f: for line in f: s, p, o, _ = line.rstrip().split(' ') if p == '<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>': frame_type[s] = o else: frame ...
import sys import xml.sax import xml.sax.handler class Handler(xml.sax.handler.ContentHandler): """Quick XML ContentHandler""" def __init__(self): self.path = [] self.pathStr = "" self.parentPathStr = "" self.result = dict() def startDocument(self): print '-----' ...
"""Helpers to handle debhelper command line options.""" import os from optparse import OptionParser, SUPPRESS_HELP class DebhelperOptionParser(OptionParser): """Special OptionParser for handling Debhelper options. Basically this means converting -O--option to --option before parsing. """ def parse_a...
import pygtk pygtk.require('2.0') import gobject del gobject del pygtk from _gsf import *
from abiflows.core.testing import AbiflowsTest from abiflows.utils.factors import lowest_nn_gte_mm class TestFactors(AbiflowsTest): def test_lowest_nn_gte_mm(self): ll, exponents = lowest_nn_gte_mm(101, [2, 3, 5]) self.assertEqual(ll, 108) self.assertEqual(exponents, (2, 3, 0)) ll, e...
""" PyroCore - Python Torrent Tools Core Package. Copyright (c) 2010 The PyroScope Project <pyroscope.project@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version ...
from __future__ import division, absolute_import, print_function, unicode_literals from awlsim.common.compat import * from awlsim.common.enumeration import * from awlsim.common.exceptions import * class S7CPUSpecs(object): "STEP 7 CPU Specifications" # Mnemonic identifiers # Note: These numbers are .awlpro file ABI....
from block_tdhs_client import * from exception import response_exception con_num = 1 connect_pool = [] for i in xrange(con_num): connect_pool.append(ConnectionManager("t-wentong", read_code="ab", write_code="cd")) for i in xrange(100000): connect = connect_pool[i % con_num] try: field_types, record...
from __future__ import print_function from __future__ import unicode_literals from sys import __stdout__, version_info class Arguments(object): pass class View(object): args = Arguments() out = None def __init__(self, out=__stdout__): self.out = out def assign(self, key, value): self.args.__dict__[key] = value...
import os extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.mathjax', 'sphinx.ext.ifconfig', 'sphinx.ext.viewcode' ] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' projec...
from openpyxl import Workbook from openpyxl.chart import PieChart, Reference from plugins.abstract.chart_export import AbstractChartExport import StringIO class ExcelExport(AbstractChartExport): def get_content_type(self): return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' def ge...
import datetime import os import os.path from stem import Flag from stem.exit_policy import ExitPolicy from random import random, randint, choice import sys import collections import cPickle as pickle import argparse from models import * import congestion_aware_pathsim import hs_pathsim import hs_short_pathsim import h...
from __future__ import absolute_import, division, print_function import collections from concurrent.futures import CancelledError from tornado_py2 import gen, ioloop from tornado_py2.concurrent import Future, future_set_result_unless_cancelled __all__ = ['Condition', 'Event', 'Semaphore', 'BoundedSemaphore', 'Lock'] cl...
import copy import time from Address import Address import struct class Locator(object): """ take a memoryworker and a type to search then you can feed the locator with values and it will reduce the addresses possibilities """ def __init__(self, mw, type = 'unknown', start = None, en...
import sys, math, types, string, re import pygtk pygtk.require("2.0") import gtk import gtk.keysyms import gobject import psycopg2 import psycopg2.extras class SQLRenderer : def __init__ (self) : pass def begin_render (self, data, filename) : self.f = open(filename, "w") self.sql = DiaSql(data) self.sql.gener...
""" in in_data v d=[] n=1 in in_colors v d=[] n=1 out float_out s """ import bgl import bpy from gpu_extras.batch import batch_for_shader import gpu from sverchok.data_structure import node_id from sverchok.ui import bgl_callback_3dview as v3dBGL self.n_id = node_id(self) v3dBGL.callback_disable(self.n_id...
""" Launches simulations on various remote configurations """ import os import time import subprocess def createId(prefix): t = time.localtime() return prefix + '_' + str(t.tm_year) + '_' + str(t.tm_mon) + '_' + str(t.tm_mday) + '_' + str(t.tm_hour) + '_' + str(t.tm_min) + '_' + str(t.tm_sec) class Launcher: ...
from .ban import BanPacket from .event import EventPacket from .message import MessagePacket from .packet import Packet __all__ = ["BanPacket", "EventPacket", "MessagePacket", "Packet"]
import optparse import os import re import ReadKeyValue import ReadM3U def songs_from_dictionary(dictionary): NAME_NUMBER_RE = re.compile(r"^(?P<name>\D+)(?P<number>\d+)$") songs = [] for file in (name for name in sorted(dictionary.keys()) if name.startswith("file")): name_number = ...
""" - This simulation seeks to emulate the COBAHH benchmark simulations of (Brette et al. 2007) using the Brian2 simulator for speed benchmark comparison to DynaSim. However, this simulation includes CLOCK-DRIVEN synapses, for direct comparison to DynaSim's clock-driven architecture. The synaptic connections ar...