code
stringlengths
1
199k
def extractErosWorkshop(item): """ # Eros Workshop """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or 'preview' in item['title'].lower(): return None if 'Young God Divine Armaments' in item['tags'] and (chp or vol): return buildReleaseMessageWithType(item, 'Yo...
from __future__ import unicode_literals import logging import random import string import warnings from twisted.internet import reactor, defer from twisted.internet.endpoints import serverFromString from twisted.logger import globalLogBeginner, STDLibLogObserver from twisted.web import http from .http_protocol import H...
"""Orthogonal matching pursuit algorithms """ import warnings import numpy as np from scipy import linalg from scipy.linalg.lapack import get_lapack_funcs from .base import LinearModel from ..base import RegressorMixin from ..utils import array2d from ..utils.arrayfuncs import solve_triangular premature = """ Orthogona...
import matplotlib.pyplot as plt # This example uses matplotlib for plotting. This module is in no way tied to # matplotlib. You may utilize whichever plotting tool you prefer. import rawDataProcessor # The module is called rawDataProcessor. print("==============================") print(" Example Sc...
from __future__ import absolute_import import os import optparse import urllib import base64 import random from twisted.web.server import Site, NOT_DONE_YET from twisted.web.resource import Resource from twisted.web import proxy, http from twisted.internet import reactor, ssl from twisted.internet.task import deferLate...
""" Jutda Helpdesk - A Django powered ticket tracker for small enterprise. (c) Copyright 2008 Jutda. All Rights Reserved. See LICENSE for details. lib.py - Common functions (eg multipart e-mail) """ chart_colours = ('80C65A', '990066', 'FF9900', '3399CC', 'BBCCED', '3399CC', 'FFCC33') try: from base64 import urlsaf...
import datetime from haystack import indexes from celery_haystack.indexes import CelerySearchIndex from models import Question, Answer class AnswerIndex(CelerySearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) author = indexes.CharField(model_attr='author') created_a...
from __future__ import unicode_literals import os from appdirs import AppDirs from cihai.config import Configurator, expand_config dirs = AppDirs("cihai", "cihai team") # appname # app author def test_configurator(tmpdir): c = Configurator() isinstance(c.dirs, AppDirs) assert c def test_expand_config_xdg_...
"""Classical Policy Iteration. Performs Bellman Backup on a given s,a pair given a fixed policy by sweeping through the state space. Once the errors are bounded, the policy is changed. """ from .MDPSolver import MDPSolver from rlpy.Tools import className, deltaT, hhmmss, clock, l_norm from copy import deepcopy from rlp...
import numpy as np import pytest from pandas._libs.tslibs import Timestamp import pandas as pd from pandas import ( Index, Series, ) import pandas._testing as tm from pandas.core.indexes.api import ( Float64Index, Int64Index, NumericIndex, UInt64Index, ) from pandas.tests.indexes.common import N...
""" FeatureResponses and associated functions and classes. These classes implement map and tuning curve measurement based on measuring responses while varying features of an input pattern. $Id$ """ __version__='$Revision$' import time import copy from math import fmod,floor,pi from colorsys import hsv_to_rgb import num...
from __future__ import absolute_import from blockcanvas.app.segy_reader.segy_reader import *
from CellModeller.Signalling.GridDiffusion import GridDiffusion from CellModeller.Integration.CLCrankNicIntegrator import CLCrankNicIntegrator from CellModeller.Integration.ScipyODEIntegrator import ScipyODEIntegrator from CellModeller.Regulation.ModuleRegulator import ModuleRegulator from CellModeller.Biophysics.Bacte...
import tests.model_control.test_ozone_custom_models_enabled as testmod testmod.build_model( ['Fisher'] , ['PolyTrend'] , ['Seasonal_DayOfWeek'] , ['AR'] );
"""Functionality to enumerate and represent starboard ports.""" import logging import os import re import _env # pylint: disable=unused-import from starboard.tools import environment _PLATFORM_FILES = [ 'gyp_configuration.gypi', 'gyp_configuration.py', 'starboard_platform.gyp', 'configuration_public.h'...
import tests.model_control.test_ozone_custom_models_enabled as testmod testmod.build_model( ['BoxCox'] , ['MovingAverage'] , ['Seasonal_Second'] , ['AR'] );
""" Tests that relate to fitting models with quantity parameters """ import numpy as np import pytest from astropy.modeling import models from astropy import units as u from astropy.units import UnitsError from astropy.tests.helper import assert_quantity_allclose from astropy.utils import NumpyRNGContext from astropy.m...
import numpy as np from glumpy import app, collections vertex = """ // Externs // ------------------------------------ // extern vec3 position; // extern float id; // extern vec4 color; // ... user-defined through collection init dtypes // ----------------------------------------------- uniform float rows, cols; var...
from dateutil.relativedelta import relativedelta as relativedelta from nose.tools import raises import numpy as np import pandas as pds import pysat class TestOrbitsUserInterface(): @raises(ValueError) def test_orbit_w_bad_kind(self): info = {'index': 'mlt', 'kind': 'cats'} self.testInst = pysat...
""" test_pysd ---------------------------------- Tests for `pysd` module. """ import unittest from pysd import discovery
import tempfile import unittest from telemetry.internal import story_runner from telemetry.page import page from telemetry.page import page_set from telemetry.page import page_test from telemetry.page import shared_page_state from telemetry import story as story_module from telemetry.unittest_util import options_for_un...
from . import pre from . import set_pos_tags_codes from . import set_ngram_polarity_statement from . import ADJS, ADVS, VERBS, ALL, ADJS_AND_ADVS, ADJS_AND_VERBS, ADVS_AND_VERBS,\ ADJS_AND_BI_ADV_ADJ, ADVS_AND_BI_ADV_ADV, VERBS_AND_BI_ADV_VERB, ALL_NON_GENERAL_BIGRAMS """ ------------------------------ Base functio...
import datetime, os from django.template.context import RequestContext from django.shortcuts import render_to_response, redirect, HttpResponse, Http404 from django.http import HttpResponse from django.contrib.auth import authenticate from django.contrib.auth import login as auth_login from django.contrib.auth.models im...
from __future__ import division __credits__ = ["Daniel McDonald"] from pyqi.core.interfaces.optparse import (OptparseUsageExample, OptparseOption, OptparseResult) from pyqi.core.command import (make_command_in_collection_lookup_f, make_command_ou...
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 'Client' db.create_table('invoicer_client', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_ke...
from datetime import timedelta from decimal import Decimal as D from django.test import TestCase from django.utils import timezone from django.utils.translation import ugettext_lazy as _ import mock from oscar.apps.order.exceptions import ( InvalidOrderStatus, InvalidLineStatus, InvalidShippingEvent) from oscar.app...
from sklearn2sql_heroku.tests.classification import generic as class_gen class_gen.test_model("SVC_linear" , "FourClass_100" , "sqlite")
from corehq.apps.reports.util import get_INFilter_element_bindparam def clean_IN_filter_value(filter_values, filter_value_name): if filter_value_name in filter_values: for i, val in enumerate(filter_values[filter_value_name]): filter_values[get_INFilter_element_bindparam(filter_value_name, i)] =...
import unittest from test.primaires.connex.static.commande import TestCommande from test.primaires.joueur.static.joueur import ManipulationJoueur from test.primaires.scripting.static.scripting import ManipulationScripting class TestContient(TestCommande, ManipulationJoueur, ManipulationScripting, unittest.TestC...
"""Test simple assignment.""" import pytest from matlab2cpp import qcpp, qhpp @pytest.fixture(params=[ "simple_assignment", ]) def cpp_filename(request): return request.param def test_cpp_executables(cpp_filename): """Test basic variable types.""" with open("%s.m" % cpp_filename) as src: source_...
import hashlib import hmac import os from base64 import b64decode, b64encode from kokki import Fail, Environment class SSHKnownHostsFile(object): def __init__(self, path=None): self.hosts = [] self.parse(path) def parse(self, path): self.hosts = [] with open(path, "r") as fp: ...
from pytest import raises from watson.framework.i18n import translate class TestTranslator(object): def test_repr(self): translator = translate.Translator( default_locale='en', package='tests.watson.framework.i18n.locales') assert repr(translator) == '<watson.framework.i18n.t...
import webbrowser import tempfile import shutil import requests import logging import platform import os import configparser from collections import Counter from PyQt5 import QtCore, QtWidgets, Qt, QtGui from ui.Ui_mainwindow import Ui_MainWindow from ui.Ui_aboutwindow import Ui_aboutWindow from ui.Ui_aboutstandard imp...
"""Tests of the pnacl driver. This tests that diagnostic flags work fine, even with --pnacl-* flags. """ import cStringIO import os import unittest from driver_env import env import driver_log import driver_test_utils import driver_tools def exists(substring, list_of_strings): for string in list_of_strings: if su...
import os import sys import pytest os.chdir("../") sys.path.append(os.getcwd() + "../venv/lib/python2.7/site-packages") os.chdir(os.getcwd() + "/tests/") exit(pytest.main(['./']))
"""Module to run the rotation search""" __author__ = "Adam Simpkin & Felix Simkovic" __date__ = "03 June 2020" __version__ = "0.4" import abc import simbad.parsers.mtz_parser ABC = abc.ABCMeta('ABC', (object,), {}) class _RotationSearch(ABC): def __init__(self, mtz, mr_program, tmp_dir, work_dir, max_to_keep=20, sk...
import inspect class FunctionRegistry(dict): def register(self, function): """Register a function in the function registry. The function will be automatically instantiated if not already an instance. """ function = inspect.isclass(function) and function() or function ...
from django.db.models import Q from .models import Team class TeamPermissionsBackend(object): def authenticate(self, username=None, password=None): return None def get_all_permissions(self, user_obj, obj=None): """ Returns a set of permission strings that this user has through his/her ...
""" Script generates statistics for path and function names in projects """ import ast import os import collections import sys from nltk import pos_tag from helpers import * from git import Repo import argparse def is_verb(word): if not word: return False pos_info = pos_tag([word]) return pos_info[0][1] == 'VB' de...
import datetime from django.utils.translation import ugettext_lazy as _ COUNTRIES_LAST_UPDATE = datetime.datetime(2011, 7, 7, 18, 15) COUNTRIES = ( # ( # '<ISO 3166-1 alpha-2 uppercase code>', # _("<official English short name>") # ), ('AF', _("Afghanistan")), ('AL', _("Albania")), ('DZ'...
from alembic import op import sqlalchemy as sa from sqlalchemy.orm import sessionmaker """empty message Revision ID: 40b223faa7d4 Revises: 2126386257ad Create Date: 2018-01-18 14:58:36.140440 """ revision = '40b223faa7d4' down_revision = '2126386257ad' Session = sessionmaker() def update_job_name(session, old, new): ...
import json import warnings import numpy as np import pandas as pd from pandas import DataFrame, Series from pandas.core.accessor import CachedAccessor from shapely.geometry import mapping, shape from shapely.geometry.base import BaseGeometry from pyproj import CRS from geopandas.array import GeometryArray, GeometryDty...
from datetime import datetime import warnings import numpy as np import pytest from pandas.core.dtypes.dtypes import CategoricalDtype import pandas as pd from pandas import ( DataFrame, MultiIndex, Series, Timestamp, date_range, ) import pandas._testing as tm from pandas.tests.frame.common import zi...
from __future__ import unicode_literals from django.db.models import PositiveIntegerField from django.utils.translation import ugettext_lazy as _, pgettext_lazy from shop.models import order class OrderItem(order.BaseOrderItem): """Default materialized model for OrderItem""" quantity = PositiveIntegerField(_("O...
from encdec import RNNEncoderDecoder from encdec import get_batch_iterator from encdec import parse_input from encdec import create_padded_batch from state import\ prototype_state,\ prototype_phrase_state,\ prototype_encdec_state,\ prototype_search_state,\ prototype_search_with_coverage_state
from __future__ import division, print_function, absolute_import import warnings import io import numpy as np from numpy.testing import ( assert_almost_equal, assert_array_equal, assert_array_almost_equal, assert_allclose, assert_equal, assert_) from pytest import raises as assert_raises from scipy.interpolate ...
from __future__ import absolute_import import skimage.segmentation def watershed(image, markers, connectivity=None, offset=None, mask=None): return skimage.segmentation.watershed(image, markers, connectivity, offset, mask)
from django.core.urlresolvers import reverse from rest_framework import status from bluebottle.test.factory_models.redirect import RedirectFactory from bluebottle.test.utils import BluebottleTestCase class RedirectApiTestCase(BluebottleTestCase): def setUp(self): super(RedirectApiTestCase, self).setUp() ...
import logging import os import signal import subprocess import tempfile import unittest import pyauto_functional import pyauto import test_utils class SimpleTest(pyauto.PyUITest): def ExtraChromeFlags(self): """Ensures Chrome is launched with custom flags. Returns: A list of extra flags to pass to Chro...
import numpy as np from smac.utils.constants import MAXINT from smac.runhistory.runhistory import RunKey """Define overall objectives. Overall objectives are functions or callables that calculate the overall objective of a configuration on the instances and seeds it already ran on.""" def _runtime(config, run_history, ...
""" Python Utils for Celery Job Framework """ from generic_utils.config import get_config_value from generic_utils.loggingtools import getLogger from generic_utils.rabbitmq.utils import get_rabbitmq_config_values from generic_utils.redis.utils import get_redis_config_values log = getLogger() class BrokerTypes(object): ...
import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit() readme = open('README.rst').read() history = open('HISTORY.rst').read().replace('.. :changelog:', '') version_fil...
from cerberus import Validator def test_validated_schema_cache(): v = Validator({'foozifix': {'coerce': int}}) cache_size = len(v._valid_schemas) v = Validator({'foozifix': {'type': 'integer'}}) cache_size += 1 assert len(v._valid_schemas) == cache_size v = Validator({'foozifix': {'coerce': int}...
import copy import json import re import time from acertmgr import tools from acertmgr.authority.acme import ACMEAuthority as AbstractACMEAuthority from acertmgr.tools import log class ACMEAuthority(AbstractACMEAuthority): # @brief Init class with config # @param config Configuration data # @param key Accou...
"""Support for Lutron Caseta shades.""" import logging from homeassistant.components.cover import ( ATTR_POSITION, DOMAIN, SUPPORT_CLOSE, SUPPORT_OPEN, SUPPORT_SET_POSITION, SUPPORT_STOP, CoverDeviceClass, CoverEntity, ) from homeassistant.config_entries import ConfigEntry from homeassis...
import math dimensions(8,2) initialRobotLoc(0.5, 0.5, math.pi/12)
def cheeseshop(kind, *arguments, **keywords): """Demonstrates how to use tuple and dictionary as arguments. *arguments is a tuple. **keywords is a dictionary. """ print("-- Do you have any", kind, "?") print("-- I'm sorry, we're are all out of", kind) for arg in arguments: print(arg)...
import sys import numpy as np import pdb class DependencyDecoder: """ Dependency decoder class """ def __init__(self): self.verbose = False def parse_marginals_nonproj(self, scores): """ Compute marginals and the log-partition function using the matrix-tree theorem ""...
"This module is used as a database for KoL item information." import kol.Error as Error from kol.data import Items from kol.manager import FilterManager from kol.util import Report __isInitialized = False __itemsById = {} __itemsByDescId = {} __itemsByName = {} def init(): """ Initializes the ItemDatabase. This...
"""Loose port of the examples in `Kerflyn's Blog / Playing with Scala's pattern matching <http://kerflyn.wordpress.com/2011/02/14/playing-with-scalas-pattern-matching/>`_ """ from __future__ import print_function from pyfpm.matcher import Matcher print('-'*80) toYesOrNo = Matcher([ ('1', lambda: 'yes'), ...
from __future__ import absolute_import; from pymfony.component.system import Object; from pymfony.component.dependency.exception import OutOfBoundsException; from pymfony.component.dependency.exception import InvalidArgumentException; from pymfony.component.dependency.interface import ContainerInterface; """ """ class ...
from Cryptodome.Util.py3compat import * test_data = [ # Test vectors downloaded 2008-09-12 from # http://homes.esat.kuleuven.be/~bosselae/ripemd160.html ('9c1185a5c5e9fc54612808977ee8f548b2258d31', '', "'' (empty string)"), ('0bdc9d2d256b3ee9daae347be6f4dc835a467ffe', 'a'), ('8eb208f7e05d987a9b044...
import fnmatch import os from flask import Flask, redirect, request, send_from_directory from flask_compress import Compress from loguru import logger from flexget.webserver import register_app, register_home logger = logger.bind(name='webui') manager = None debug = False app_base = None ui_base = os.path.dirname(os.pa...
from anvil.entities import KilnProject from anvil.utils import memoized import getpass import json import requests __all__ = ['Anvil'] class Anvil(object): """An Anvil is the main interface object to the Kiln API Example Usage:: >>> anvil = Anvil("https://kiln.yourcompany.com/kiln", False) >>> a...
from time import gmtime, strftime from kritzbot.commandmanager import CommandManager from kritzbot.logger import Logger log = Logger(__name__) class ChatStream: def __init__(self, message, user): self.msg = message self.user = user self.timestamp = strftime("%Y-%m-%d %H:%M:%S", gmtime()) self.msg_length = len(...
import os import unirest import time import json import pprint import logging import argparse unirest.timeout(120) IODAPIKEY = os.environ.get('IODAPIKEY') parser = argparse.ArgumentParser(description='Check the status of an IOD web connector and its associated text index') parser.add_argument('--apikey', default=IODAPI...
from msrest.serialization import Model class SystemService(Model): """Information about a system service deployed in the cluster. Variables are only populated by the server, and will be ignored when sending a request. :param system_service_type: The system service type. Possible values include: 'No...
''' sc_studio.ccd_graph_view Author: Ming Tsang Copyright (c) 2014-2015 HKUST SmartCar Team Refer to LICENSE for details ''' import binascii import logging import time import tkinter from tkinter import Tk, Text from sc_studio import config from sc_studio.view import View class CcdGraphView(View): def __init__(self, p...
from argparse import ArgumentParser import sys from Bio import SeqIO QUALITY_CONVERSION_TYPES = ["fastq-sanger", "fastq-solexa", "fastq-illumina"] def main(in_file, in_format, out_format): with open(in_file, "r") as in_handle: SeqIO.convert(in_handle, in_format, sys.stdout, out_format) if __name__ == "__mai...
import json import demistomock as demisto from CommonServerPython import * """ Use the IvantiHeatCreateIncidentExample script to create a incident object (JSON) in Ivanti Heat. The script gets the arguments required to create the incident, such as category, summary, and so on. It creates the JSON object and sets it ins...
from swgpy.object import * def create(kernel): result = Tangible() result.template = "object/tangible/ship/crafted/weapon/missile/shared_weapon_basic_launcher.iff" result.attribute_template_id = 8 result.stfName("space_crafting_n","weapon_basic_launcher") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS ###...
from apiwrapper.endpoints.endpoint import Endpoint from apiwrapper.endpoints.monetary_account import MonetaryAccount class CashRegister(Endpoint): __endpoint_cash_register = "cash-register" __endpoint_cash_register_qr = "qr-code" __endpoint_cash_register_qr_content = "content" @classmethod def _get_...
import re import datetime import logging import twilio from twilio import TwilioException, TwilioRestException from urllib import urlencode from urlparse import urlparse from twilio.rest.resources.imports import ( parse_qs, json, httplib2 ) from twilio.rest.resources.util import ( transform_params, format_name,...
from .include import * def process (color_in): contours = util.processing.getContours (color_in, 10 * util.input.scale_len, 50 * util.input.scale_area) segments = [ (c[i][0], c[(i + 1) % len (c)][0]) for c in contours for i in xrange (len (c)) ] waypoints = [] def add_waypoint (pt, waypoints...
""" Purpose: -Record and report references to live object instances or subclass (object_ref) Issues: """ from __future__ import print_function import weakref, os, six from collections import defaultdict from time import time from operator import itemgetter NoneType = type(None) live_refs = defaultdict(weakref.WeakKeyDi...
""" /*************************************************************************** LTSDialog A QGIS plugin Computes level of traffic stress ------------------- begin : 2014-04-24 copyright : (C) 2014 by Peyman Noursa...
from __future__ import unicode_literals from uuid import uuid4 from sqlalchemy.dialects.postgresql import UUID from indico.core.db import db from indico.core.db.sqlalchemy import PyIntEnum from indico.util.i18n import L_ from indico.util.locators import locator_property from indico.util.string import format_repr, retur...
''' Created on Mar 20, 2017 @author: nakul ''' import uuid class Category: def __init__(self, guid, name): self.id=str(guid) #UUID self.name=name self.goals=[] def _get_total_number_of_goals(self): return len(self.goals) def _get_all_goals(self): return self.goals ...
from __future__ import absolute_import, division, unicode_literals import logging import Queue import threading import time from datetime import datetime from sqlalchemy.exc import ProgrammingError, OperationalError from flexget.task import TaskAbort log = logging.getLogger('task_queue') class TaskInfo(object): def...
import json import os BASE_DIR = os.path.dirname(os.path.realpath(__file__)) with open( BASE_DIR + "/../../config/config.json", "r" ) as configFile : data = configFile.read( ) data = json.loads( data ) DB_HOST = data['DATABASE']['DB_HOST'] DB_USER = data['DATABASE']['DB_USER'] DB_PASS = data['DATABASE']['DB_PASS'] DB_...
from secret import twitter_instance from json import dump import sys tw = twitter_instance() response = tw.account.verify_credentials( skip_status=True, email=True) dump(response, sys.stdout, ensure_ascii=False, indent=4, sort_keys=True)
""" Provides functionality to notify people. For more details about this component, please refer to the documentation at https://home-assistant.io/components/notify/ """ from functools import partial import logging import os import voluptuous as vol import homeassistant.bootstrap as bootstrap from homeassistant.config ...
from lib import core, vectors, pieces # # ### # # # # # # # # # # # # # # # ##### ### class EngineUI: """The class that handles the UI for the engine.""" def __init__(self): self.history = list() self._symboltopiece = { 'R': pieces.RookPiece, ...
from swgpy.object import * def create(kernel): result = Intangible() result.template = "object/draft_schematic/space/armor/shared_armor_reinforcement_panel_mk3.iff" result.attribute_template_id = -1 result.stfName("string_id_table","") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
__version__ = '0.1'
import unittest import numpy import os import rmgpy from rmgpy.molecule import Molecule from rmgpy.species import Species from rmgpy.reaction import Reaction from rmgpy.kinetics import Arrhenius from rmgpy.thermo import ThermoData from rmgpy.solver.liquid import LiquidReactor from rmgpy.solver.base import TerminationTi...
from theano import tensor from blocks.bricks import Rectifier, MLP # , Softmax from blocks.bricks.conv import (ConvolutionalLayer, ConvolutionalSequence, Flattener) from blocks.initialization import Uniform, Constant x = tensor.tensor4('images') y = tensor.lmatrix('targets') filter_size...
import os import sys if __package__ is None: sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/..") from unittest import main, TestCase import requests import requests_mock from iris_sdk.client import Client from iris_sdk.models.account import Account from iris_sdk.models.tns import Tns XML_RESPONSE_LC...
import glob from sets import Set def get_dict(file_list): dict_set = Set([]) for file_name in file_list: with open(file_name) as file: content = file.read() for word in content.split('\n'): if word: dict_set.add(word) return dict_set def g...
from django.contrib import admin
import imp import os import sys try: virtenv = os.path.join(os.environ.get('OPENSHIFT_PYTHON_DIR','.'), 'virtenv') python_version = "python"+str(sys.version_info[0])+"."+str(sys.version_info[1]) os.environ['PYTHON_EGG_CACHE'] = os.path.join(virtenv, 'lib', python_version, 'site-packages') virtualenv = os.path.j...
""" Agent object Author: Blake LeBaron Date: June 14, 2016 All agents are a single instance of this This is usually put into a single list (as in main program) """ import numpy as np class agent: def __init__(self, sigmaF, sigmaM, sigmaN, kmax, Lmin, Lmax): # set strategy weights # set all positive ...
import pytest @pytest.fixture def list(): from ..indexed_list import IndexedList return IndexedList def test_ctor(list): l = list(['b', 'a']) assert l == ['b', 'a'] assert l.clean is False def test_allow_duplicate_ctor(list): l = list(['b', 'a', 'b']) assert l == ['b', 'a', 'b'] l.append...
import weakref class Element(list): def __init__(self, seq=()): list.__init__(self) self._refs = [] self._dirty = False for x in seq: self.append(x) def _mark_dirty(self, wref): self._dirty = True def flush(self): self._refs = [x for x in self._ref...
import numpy as np from scipy.spatial import distance from sklearn.cluster import DBSCAN from sklearn import metrics def clabels(featureNum): if featureNum == 0: label = "Area" elif featureNum == 1: label = "Perimeter" elif featureNum == 2: label = "Compactness" elif featureNum == 3: label = "As...
"""distutils.command.upload Implements the Distutils 'upload' subcommand (upload package to PyPI).""" import os import socket import platform from urllib2 import urlopen, Request, HTTPError from base64 import standard_b64encode import urlparse import cStringIO as StringIO from hashlib import md5 from distutils.errors i...
import json import requests from azure.cli.core.util import CLIError from azure.cli.command_modules.ams._completers import get_mru_type_completion_list from azure.cli.core.commands.client_factory import get_subscription_id from azure.cli.core.azclierror import BadRequestError _rut_dict = {0: 'S1', 1: 'S2',...
from __future__ import absolute_import from .spec.base import BaseObj import six def default_tree_traversal(root, leaves): """ default tree traversal """ objs = [('#', root)] while len(objs) > 0: path, obj = objs.pop() # name of child are json-pointer encoded, we don't have # to enco...
import re import subprocess import sys import tempfile from textwrap import dedent from bpython import args from bpython.test import (FixLanguageTestCase as TestCase, unittest) try: from nose.plugins.attrib import attr except ImportError: def attr(*args, **kwargs): def identity(func): return...
from collections import defaultdict from rasmus import treelib, svg, util, stats from compbio import phylo def draw_stree(canvas, stree, slayout, yscale=100, stree_width=.8, stree_color=(.4, .4, 1), snode_color=(.2, .2, .4)): # draw stree branches for ...