content
stringlengths
4
20k
from django.db import models from characters.models import Character from collections import namedtuple class MailFolder(models.Model): """ folders to hold and sort messages Inbox, sent and thrash """ character = models.ForeignKey(Character) name = models.CharField(max_length=31) locked = models.Boolean...
#!/usr/bin/python # # The Python Imaging Library. # $Id$ # # convert image files # # History: # 0.1 96-04-20 fl Created # 0.2 96-10-04 fl Use draft mode when converting images # 0.3 96-12-30 fl Optimize output (PNG, JPEG) # 0.4 97-01-18 fl Made optimize an option (PNG, JPEG) # 0.5 98-12-30 fl ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Configuration This file contains shared constants/dictionaries for the fabfile Created by: Rui Carmo """ # copy our configuration files to a specific location and set permissions # (this is a sample for an old Postgres deployment) skel = { 'postgres': [{ ...
#!/usr/bin/env python """ Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License");...
from smartchangelog import datetools from smartchangelog.commit import Commit from smartchangelog.commitmsg import CommitType from tests.unit import data_file_path class TestCommit: def test_parse(self): # GIVEN with open(data_file_path('one.gitlog'), encoding='utf-8') as log_file: log...
"""SCons.Scanner The Scanner package for the SCons software construction utility. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation file...
from .resource import Resource class NamespaceResource(Resource): """Description of a Namespace resource. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id :vartype id: str :ivar name: Resource name :vartype name: str :ivar ...
# coding: utf-8 from __future__ import unicode_literals from .common import InfoExtractor from ..utils import ( ExtractorError, parse_iso8601, ) class DRTVIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?dr\.dk/tv/se/(?:[^/]+/)*(?P<id>[\da-z-]+)(?:[/#?]|$)' _TEST = { 'url': 'https://www....
from openerp.osv import fields, osv class res_partner(osv.osv): _name = 'res.partner' _inherit = 'res.partner' _columns = { 'property_product_pricelist': fields.property( type='many2one', relation='product.pricelist', domain=[('type','=','sale')], ...
from .sub_resource import SubResource class ApplicationGatewayProbe(SubResource): """Probe of the application gateway. :param id: Resource ID. :type id: str :param protocol: Protocol. Possible values include: 'Http', 'Https' :type protocol: str or ~azure.mgmt.network.v2017_09_01.models.Appli...
import abc import hashlib class CertDB(object): """Database interface for storing X509 certificate information.""" __metaclass__ = abc.ABCMeta @staticmethod def sha256_hash(der_cert): return hashlib.sha256(der_cert).digest() @abc.abstractmethod def store_cert_desc(self, cert_desc, in...
import unittest from xmodule.contentstore.content import StaticContent from xmodule.contentstore.content import ContentStore from xmodule.modulestore import Location class Content: def __init__(self, location, content_type): self.location = location self.content_type = content_type class Content...
""" Tests for docutils.transforms.frontmatter.DocInfo. """ from __init__ import DocutilsTestSupport from docutils.transforms.frontmatter import DocInfo from docutils.parsers.rst import Parser def suite(): parser = Parser() settings = {'language_code': 'en'} s = DocutilsTestSupport.TransformTestSuite( ...
""" This module encapsulates running image segmentation model for inference. Example usage: $ python image_segmentaion.py --input <your JPG image path> """ import argparse import os import numpy as np import mxnet as mx from PIL import Image def make_file_extension_assertion(extension): """Function factory f...
"""Utilities for working with gdb.Types.""" import gdb def get_basic_type(type_): """Return the "basic" type of a type. Arguments: type_: The type to reduce to its basic type. Returns: type_ with const/volatile is stripped away, and typedefs/references converted to the underlyin...
""" This module contains the PMApp singleton object that gives access to the all PacketManipulator functionalities """ import gtk import gobject import os import sys from optparse import OptionParser from umit.pm.core.i18n import _ from umit.pm.core.atoms import Singleton from umit.pm.core.bus import services_boot,...
import numpy as np import sympy as sp def make(obj, exp): for arg in range(obj.args): print(arg.random()) class Addition(object): def __init__(self): self.args = [None] * 2 self.solution = None def __getitem__(self, key): return self.args[key] def __setitem__(self,...
import os from testtools.matchers import ( DirExists, FileExists ) import integration_tests class TarPluginTestCase(integration_tests.TestCase): def test_stage_nil_plugin(self): project_dir = 'simple-zip' self.run_snapcraft('stage', project_dir) expected_files = [ '...
#! /usr/bin/env python from unit_timeside import * from timeside.decoder import * from timeside.analyzer.level import Level class TestAnalyzerLevel(unittest.TestCase): def setUp(self): self.analyzer = Level() def testOnSweep(self): "runs on sweep" self.source = os.path.join (os.path....
import clr clr.AddReference("RevitAPI") from Autodesk.Revit.DB import OpenOptions, SynchronizeWithCentralOptions, DetachFromCentralOption, RelinquishOptions from Autodesk.Revit.DB import TransactWithCentralOptions from Autodesk.Revit.DB import FilePath from Autodesk.Revit.DB import WorksetConfiguration, WorksetConfigur...
# -*- coding: utf-8 -*- from __future__ import absolute_import try: # For Python < 2.6 or people using a newer version of simplejson import simplejson json = simplejson except ImportError: # For Python >= 2.6 import json from .es import ES class River(object): def __init__(self, index_name=N...
""" LLDB Support for WebKit Types Add the following to your .lldbinit file to add WebKit Type summaries in LLDB and Xcode: command script import {Path to WebKit Root}/Tools/lldb/lldb_webkit.py """ import lldb def __lldb_init_module(debugger, dict): debugger.HandleCommand('type summary add --expand...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import json import random from ansible import constants as C from ansible.plugins.action import ActionBase class ActionModule(ActionBase): def run(self, tmp=None, task_vars=None): ''' transfer the given module name,...
#!/usr/bin/env python #coding: utf-8 from gi.repository import Gtk, Gdk class Programa(Gtk.Window): def eventCompInte(self, widget): arquivo = open("desc_exercicios/ComparacaoDeIntervalos", "r") self.texto = arquivo.read() # Altera o texto do widget "descrição" self.descExerc...
import distutils.dir_util import optparse import os import shutil import sys import zipfile from common_function import RemoveUnusedFilesInReleaseMode from xml.dom.minidom import Document XWALK_CORE_SHELL_APK = 'xwalk_core_shell_apk' def AddGeneratorOptions(option_parser): option_parser.add_option('-s', dest='sourc...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import pytest from units.compat.mock import MagicMock from ansible.errors import AnsibleError from ansible.module_utils.six.moves import http_client from ansible.plugins.lookup import conjur_variable import tempfile class TestLo...
try: import boto.ec2 from boto.s3.connection import OrdinaryCallingFormat, Location from boto.exception import BotoServerError, S3CreateError, S3ResponseError HAS_BOTO = True except ImportError: HAS_BOTO = False def compare_bucket_logging(bucket, target_bucket, target_prefix): bucket_log_obj ...
from . import constants import sys from .charsetprober import CharSetProber SAMPLE_SIZE = 64 SB_ENOUGH_REL_THRESHOLD = 1024 POSITIVE_SHORTCUT_THRESHOLD = 0.95 NEGATIVE_SHORTCUT_THRESHOLD = 0.05 SYMBOL_CAT_ORDER = 250 NUMBER_OF_SEQ_CAT = 4 POSITIVE_CAT = NUMBER_OF_SEQ_CAT - 1 #NEGATIVE_CAT = 0 class SingleByteCharSet...
# coding: utf-8 from django.db import models from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Author(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() friends = models.ManyToManyField('self', blank=True) def __str__(self...
"""Tests for tf.layers.base.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import copy from tensorflow.python.framework import ops from tensorflow.python.layers import base as base_layers from tensorflow.python.ops import array_ops from tensorflow.pyt...
from ..objects.exceptions import NotFoundError import re class Tier(): def __init__(self, name, typ, version): self.name = name self.type = typ self.version = version.strip() self.string = self.__str__() def to_struct(self): strct = { 'Name': self.name, ...
from neutron.plugins.common import constants as p_const FLAT_VLAN_ID = -1 LOCAL_VLAN_ID = -2 # Supported VXLAN features VXLAN_NONE = 'not_supported' VXLAN_MCAST = 'multicast_flooding' VXLAN_UCAST = 'unicast_flooding' # Corresponding minimal kernel versions requirements MIN_VXLAN_KVER = {VXLAN_MCAST: '3.8', VXLAN_UC...
''' Created on Apr 29, 2011 @author: Carsten Witzke ''' from de.staticline.tools.libsvmtools import LibsvmFileImporter import math class Always1Predictor(object): ''' A dummy predictor assuming always "1" for each instance. ''' def __init__(self): pass def buildClassifier(self, train...
''' Task Coach - Your friendly task manager Copyright (C) 2004-2013 Task Coach developers <<EMAIL>> Task Coach 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) ...
""" Extended prompt library functions.""" import gdb import os def _prompt_pwd(ignore): "The current working directory." return os.getcwd() def _prompt_object_attr(func, what, attr, nattr): """Internal worker for fetching GDB attributes.""" if attr is None: attr = nattr try: obj =...
from __future__ import absolute_import, division, print_function __metaclass__ = type from abc import ABCMeta, abstractmethod from ansible.module_utils.six import with_metaclass from ansible.module_utils.common.process import get_bin_path from ansible.module_utils.common._utils import get_all_subclasses def get_all...
import unittest import warnings import django from django.test import TestCase, RequestFactory from django.core.urlresolvers import NoReverseMatch from wagtail.wagtailcore.models import Page, Site from wagtail.tests.routablepage.models import OldStyleRoutablePageTest, NewStyleRoutablePageTest, routable_page_external_...
import logging import optparse import os import pkgutil import pydoc import re import sys import telemetry from telemetry.core import util telemetry_dir = util.GetTelemetryDir() docs_dir = os.path.join(telemetry_dir, 'docs') def RemoveAllDocs(): for dirname, _, filenames in os.walk(docs_dir): for filename in f...
import TestGyp test = TestGyp.TestGyp() # The xcode-ninja generator handles gypfiles which are not at the # project root incorrectly. # cf. https://code.google.com/p/gyp/issues/detail?id=460 if test.format == 'xcode-ninja': test.skip_test() test.run_gyp('build/all.gyp', chdir='src') test.relocate('src', 'relocate...
"""TLS Lite + poplib.""" import socket from poplib import POP3, POP3_SSL_PORT from lib.tlslite.tlsconnection import TLSConnection from lib.tlslite.integration.clienthelper import ClientHelper class POP3_TLS(POP3, ClientHelper): """This class extends L{poplib.POP3} with TLS support.""" def __init__(self, host...
__author__ = 'lemontree' from model.contact import Contacts import random import string import os.path import jsonpickle import getopt import sys try: opts, args = getopt.getopt(sys.argv[1:], "n:f:", ["number of contacts", "file"]) except getopt.GetoptError as err: getopt.usage() sys.exit(2) n = 5 f = "da...
import time from openerp.osv import osv from openerp.report import report_sxw class account_statement(report_sxw.rml_parse): def __init__(self, cr, uid, name, context): super(account_statement, self).__init__(cr, uid, name, context=context) self.total = 0.0 self.localcontext.update({ ...
from spack import * class Vegas2(Package): """"VEGAS2 is an extension that uses 1,000 Genomes data to model SNP correlations across the autosomes and chromosome X""" homepage = "https://vegas2.qimrberghofer.edu.au/" url = "https://vegas2.qimrberghofer.edu.au/vegas2v2" version('2', '815d...
import os.path import re import shutil import sys import urllib2 from common import run_local URL = ('https://git.openstack.org/cgit/openstack-infra/project-config/' 'plain/gerrit/projects.yaml') PROJECT_RE = re.compile('^-?\s+project:\s+(.*)$') # Not using an arg libraries in order to avoid module imports th...
from shinken_test import * class TestTemplateLoop(ShinkenTest): def setUp(self): self.setup_with_file('etc/shinken_template_loop.cfg') def test_dummy(self): self.assertFalse(self.conf.conf_is_correct) if __name__ == '__main__': unittest.main()
ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'core'} DOCUMENTATION = r''' --- module: win_command short_description: Executes a command on a remote Windows node version_added: 2.2 description: - The C(win_command) module takes the c...
import numpy as np from numpy.testing import assert_allclose import pytest from distutils.version import LooseVersion import sympy from hyperspy.components1d import Erf pytestmark = pytest.mark.skipif(LooseVersion(sympy.__version__) < LooseVersion("1.3"), ...
import logging import threading import grpc from grpc_testing import _common logging.basicConfig() _LOGGER = logging.getLogger(__name__) class Rpc(object): def __init__(self, handler, invocation_metadata): self._condition = threading.Condition() self._handler = handler self._invocation_...
__author__="Paul H, Horea Christian, Leonor Carcia Gutierrez" import numpy as np import matplotlib import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import AxesGrid def auto_remap(data): start=0 midpoint=0.5 stop=1.0 if np.nanmin(data) >= 0: raise ValueError('You do not need to rescale your cmap to c...
from django.contrib import auth from django.contrib.auth import load_backend from django.contrib.auth.backends import RemoteUserBackend from django.core.exceptions import ImproperlyConfigured from django.utils.functional import SimpleLazyObject def get_user(request): if not hasattr(request, '_cached_user'): ...
import unittest from typ.fakes import test_result_server_fake from typ import Host class TestResultServerFakeTest(unittest.TestCase): def test_basic_upload(self): host = Host() server = None posts = [] try: server = test_result_server_fake.start() url = 'ht...
from __future__ import unicode_literals from frappe import _ def get_data(): return [ { "label": _("General"), "items": [ { "type": "help", "label": _("Navigating"), "youtube_id": "YDoI2DF4Lmc" }, { "type": "help", "label": _("Setup Wizard"), "youtube_id": "oIOf_zCFWK...
import unittest from hearthbreaker.cards import ArgentSquire, DireWolfAlpha, HarvestGolem, BloodfenRaptor, MagmaRager, Wisp, Ysera from hearthbreaker.cards.spells.neutral import TheCoin from tests.agents.trade.test_helpers import TestHelpers from hearthbreaker.agents.trade.possible_play import PossiblePlays from tests....
# tests for slice objects; in particular the indices method. import unittest from test import support from pickle import loads, dumps import sys class SliceTest(unittest.TestCase): def test_constructor(self): self.assertRaises(TypeError, slice) self.assertRaises(TypeError, slice, 1, 2, 3, 4) ...
#!/usr/bin/env python #-*- coding:utf-8 -*- from main import * # 监控中心 # Redis class M_Redis: def GET(self): if getLogin(): sData = getLogin() SID = sData['SID'] ShowName = sData['ShowName'] #print sData #print "ShowName: " + ShowName ...
"""Launcher for an external editor.""" import os import tempfile from PyQt5.QtCore import pyqtSignal, pyqtSlot, QObject, QProcess from qutebrowser.config import config from qutebrowser.utils import message, log from qutebrowser.misc import guiprocess class ExternalEditor(QObject): """Class to simplify editing...
from config.api1_1_config import * from config.amqp import * from modules.logger import Log from on_http_api1_1 import NodesApi as Nodes from on_http_api1_1.rest import ApiException from proboscis.asserts import assert_equal from proboscis.asserts import assert_not_equal from proboscis.asserts import assert_is_not_none...
import os from os.path import exists from os.path import isdir from os.path import join import platform import re import urllib2 def GetSuitePaths(test_root): return [ f for f in os.listdir(test_root) if isdir(join(test_root, f)) ] # Reads a file into an array of strings def ReadLinesFrom(name): lines = [] wi...
from __future__ import print_function import os import pyrax pyrax.set_setting("identity_type", "rackspace") creds_file = os.path.expanduser("~/.rackspace_cloud_credentials") pyrax.set_credential_file(creds_file) imgs = pyrax.images print("This will loop through all current tasks.") tasks = imgs.list_tasks() for tas...
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy import librosa import scipy from scikits.talkbox import lpc from scikits.talkbox.tools import segment_axis from scipy.fftpack import fft,dct def feature_extraction_lp_group_delay(y, fs=44100, statistics=True, lpgd_params=None, win_params=None): eps = num...
import unittest from mantid.kernel import CompositeValidator, CompositeRelation, FloatBoundedValidator from mantid.api import PythonAlgorithm class CompositeValidatorTest(unittest.TestCase): def test_creation_with_add_succeeds_correctly_in_algorithm(self): """ Tests that a composite validator...
import tgl import pprint from functools import partial our_id = 0 pp = pprint.PrettyPrinter(indent=4) binlog_done = False; def on_binlog_replay_end(): binlog_done = True; def on_get_difference_end(): pass def on_our_id(id): our_id = id return "Set ID: " + str(our_id) def msg_cb(success, msg): ...
from datetime import datetime from sqlalchemy import * from migrate import * meta = MetaData() delegateable_table = Table('delegateable', meta, Column('id', Integer, primary_key=True), Column('label', Unicode(255), nullable=False), Column('type', String(50)), Column('create_time', DateTime, default=...
"""Testing utils for writing tests involving Files API.""" __all__ = ['TestFileServiceStub'] from google.appengine.api import apiproxy_stub class TestFileServiceStub(apiproxy_stub.APIProxyStub): """A FileServiceStub to be used with tests. Doesn't perform any kind of file validation and stores all file cont...
#!/usr/bin/env python # encoding: utf-8 ## ============================================== ## GOAL : Format code, Update headers ## ============================================== import argparse import logging import os import re import sys import datetime import subprocess ## ========================================...
import time try: import boto HAS_BOTO = True except ImportError: HAS_BOTO = False try: import boto3 HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False class EcsClusterManager: """Handles ECS Clusters""" def __init__(self, module): self.module = module try: ...
from django.utils.http import http_date, parse_http_date_safe class ConditionalGetMiddleware(object): """ Handles conditional GET operations. If the response has a ETag or Last-Modified header, and the request has If-None-Match or If-Modified-Since, the response is replaced by an HttpNotModified. ...
""" HyperParser =========== This module defines the HyperParser class, which provides advanced parsing abilities for the ParenMatch and other extensions. The HyperParser uses PyParser. PyParser is intended mostly to give information on the proper indentation of code. HyperParser gives some information on the structure ...
#this line prepares IPython for working with matplotlib %matplotlib inline # # this actually imports matplotlib # import numpy as np # import matplotlib.pyplot as plt # x = np.linspace(0, 10, 30) #array of 30 points from 0 to 10 # y = np.sin(x) # z = y + np.random.normal(size=30) * .2 # plt.plot(x, y, 'b+:', lab...
""" Management class for host-related functions (start, reboot, etc). """ from oslo_utils import units from nova.compute import arch from nova.compute import hv_type from nova.compute import vm_mode from nova import exception from nova import utils from nova.virt.vmwareapi import ds_util from nova.virt.vmwareapi impo...
DATE_FORMAT = 'j M Y' # '25 Oct 2006' TIME_FORMAT = 'P' # '2:30 p.m.' DATETIME_FORMAT = 'j M Y, P' # '25 Oct 2006, 2:30 p.m.' YEAR_MONTH_FORMAT = 'F Y' # 'October 2006' MONTH_DAY_FORMAT = 'j F' # '25 October' SHORT_DATE_FORMAT = 'd/m/Y' ...
import logging import os import os.path from django.conf import settings # public variable with the intent of referencing it in templates # and allowing tests to easily adjust the values loaded = {} def install_components(): global loaded root_dir = os.path.dirname(os.path.dirname(__file__)) component_dir = o...
# -*- coding: utf-8 -*- """ *************************************************************************** v_net_distance.py --------------------- Date : December 2015 Copyright : (C) 2015 by Médéric Ribreux Email : medspx at medspx dot fr ********************...
""" >>> from calling_conventions_ext import * >>> f_0__cdecl() 17041 >>> f_1__cdecl(1) 1 >>> f_2__cdecl(1, 2) 21 >>> f_3__cdecl(1, 2, 3) 321 >>> f_4__cdecl(1, 2, 3, 4) 4321 >>> f_5__cdecl(1, 2, 3, 4, 5) 54321 >>> f_6__cdecl(1, 2, 3, 4, 5, 6) 654321 >>> f_7__cdecl(1, 2, 3, 4, 5, 6, 7) 7654321 >>> f_8__cdecl(1, 2, 3, 4, ...
class ObjectionFrame(object): DEFENSE_CHARACTERS = { "Apollo Justice": 60, "Mia Fey": 15, "Miles Edgeworth (Defense)": 690, "Phoenix Wright": 1, } PROSECUTION_CHARACTERS = { "Franziska von Karma": 21, "Godot": 175, "Klavier Gavin": 65, "Manfr...
"""Beam pipeline to convert CC News to shareded TFRecords.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections from absl import app from absl import flags import apache_beam as beam from bert import tokenization import numpy as np from si...
from __future__ import absolute_import from __future__ import division import logging import socket import threading import six from vdsm.common.units import MiB from vdsm.config import config from vdsm import throttledlog from vdsm.common.cpuarch import PAGE_SIZE_BYTES from vdsm.common.time import monotonic_time f...
""" Classes representing uploaded files. """ import os from io import BytesIO from django.conf import settings from django.core.files.base import File from django.core.files import temp as tempfile from django.utils.encoding import smart_str __all__ = ('UploadedFile', 'TemporaryUploadedFile', 'InMemoryUploadedFile',...
from django import template register = template.Library() @register.simple_tag(takes_context=True) def render_sortable_objects(context, objects, sortable_objects_template='adminsortable/shared/objects.html'): context.update({'objects': objects}) tmpl = template.loader.get_template(sortable_o...
""" Unit tests for checking default forum role "Student" of a user when he creates a course or after deleting it creates same course again """ from contentstore.tests.utils import AjaxEnabledTestClient from contentstore.utils import delete_course_and_groups, reverse_url from courseware.tests.factories import UserFactor...
from sqlalchemy import Column, ForeignKey, Integer, String, create_engine from sqlalchemy.orm import Session, relationship, backref,\ joinedload_all from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm.collections import attribute_mapped_collection Base = declara...
"""Implementation of `head.Head` with custom loss and link function.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.learn.python.learn.estimators import head as head_lib from tensorflow.python.framework import dtypes from tensorf...
""" Instagram OAuth2 backend, docs at: http://psa.matiasaguirre.net/docs/backends/instagram.html """ from social.backends.oauth import BaseOAuth2 class InstagramOAuth2(BaseOAuth2): name = 'instagram' AUTHORIZATION_URL = 'https://instagram.com/oauth/authorize' ACCESS_TOKEN_URL = 'https://instagram.com/...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from abc import ABCMeta, abstractmethod, abstractproperty class BaseDag(object): """ Base DAG object that both the SimpleDag and DAG inherit. """ __meta...
from __future__ import unicode_literals from django import forms from django.utils.translation import ugettext_lazy as _ # While this couples the geographic forms to the GEOS library, # it decouples from database (by not importing SpatialBackend). from django.contrib.gis.geos import GEOSException, GEOSGeometry from ....
''' chm - A package to manipulate CHM files The chm package provides four modules: chm, chmlib, extra and _chmlib. _chmlib and chmlib are very low level libraries generated from SWIG interface files, and are simple wrappers around the API defined by the C library chmlib. The extra module adds full-t...
"""Resource display info for the Calliope display module.""" class DisplayInfo(object): """Display info accumulator for priming Displayer. "legacy" logic will be dropped when the incremental Command class refactor is complete. Attributes: _format: The default format string. args.format takes precedence....
import os import sys import unittest from branch_utility import BranchUtility, ChannelInfo from fake_url_fetcher import FakeUrlFetcher from object_store_creator import ObjectStoreCreator class BranchUtilityTest(unittest.TestCase): def setUp(self): self._branch_util = BranchUtility( os.path.join('branc...
""" This module implements the functionality to take any Python expression as a string and fix all numbers and other things before evaluating it, thus 1/2 returns Integer(1)/Integer(2) We use the Python ast module for that, which is in python2.6 and later. It is well documented at docs.python.org. Some tips to und...
from __future__ import absolute_import, division, print_function __all__ = [ "__title__", "__summary__", "__uri__", "__version__", "__author__", "__email__", "__license__", "__copyright__", ] __title__ = "packaging" __summary__ = "Core utilities for Python packages" __uri__ = "https://github.com/pypa/packagin...
from zerorpc import zmq import zerorpc from testutils import teardown, random_ipc_endpoint def test_events_channel_client_side(): endpoint = random_ipc_endpoint() server_events = zerorpc.Events(zmq.ROUTER) server_events.bind(endpoint) server = zerorpc.ChannelMultiplexer(server_events) client_even...
from django.contrib.auth import authenticate from django.utils.translation import ugettext_lazy as _ from rest_framework import exceptions, serializers class AuthTokenSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField(style={'input_type': 'password'}) ...
# # Example: Find the floquet modes and quasi energies for a driven system and # plot the floquet states/quasienergies for one period of the driving. # from qutip import * from pylab import * import time def hamiltonian_t(t, args): """ evaluate the hamiltonian at time t. """ H0 = args[0] H1 = args[1] w...
import subprocess from keypad.api import AttributedString, Cursor from .bourne_model import BourneCodeModel, ShellCompletionResults import logging class GetCompletionsTask: def __init__(self, prefix): self.prefix = prefix def __call__(self, ns): # print(self.prefix) # take advantage ...
""" Django admin dashboard configuration. """ from config_models.admin import ConfigurationModelAdmin, KeyedConfigurationModelAdmin from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from xblock_django.models import XBlockConfiguration, XBlockStudioConfiguration, XBlockStudioConf...
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline ...
#!/usr/bin/env python from __future__ import division import time import logging import cPickle as pickle import sys import argparse sys.path.append('../') import numpy as np from matplotlib import pyplot as plt from wyrm import processing as proc from wyrm.types import BlockBuffer, RingBuffer, Data logger = log...
''' Run this script from the root of the repository to update all translations from transifex. It will do the following automatically: - fetch all translations using the tx tool - post-process them into valid and committable format - remove invalid control characters - remove location tags (makes diffs less noisy)...
# minimal sanity check from __future__ import print_function import sys import os if "--installed" in sys.argv: sys_path_0 = sys.path[0] del sys.path[0] from PIL import Image, ImageDraw, ImageFilter, ImageMath from PIL import features if "--installed" in sys.argv: sys.path.insert(0, sys_path_0) ROOT = ...
from __future__ import absolute_import, unicode_literals, print_function, division import time from queue import Queue, Empty from threading import Lock class _ResourcePoolSession(object): def __init__(self, pool, obj, close_on_exc=False): self.__pool = pool self.__obj = obj self.__close...