code
stringlengths
1
199k
from keystone import utils from keystone.common import wsgi import keystone.config as config from keystone.logic.types.tenant import Tenant from . import get_marker_limit_and_url class TenantController(wsgi.Controller): """Controller for Tenant related operations""" def __init__(self, options, is_service_operat...
from operator import attrgetter from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType from pyangbind.lib.yangtypes import RestrictedClassType from pyangbind.lib.yangtypes import TypedListType from pyangbind.lib.yangtypes import YANGBool from pyangbind.lib.yangtypes import YANGListType from pyangbind.lib.ya...
"""Cleanup script.""" from grr.lib import export_utils hunts = aff4.FACTORY.Open("aff4:/hunts/") for hunt in hunts.ListChildren(): aff4.FACTORY.Delete(hunt) for fd in aff4.FACTORY.MultiOpen(export_utils.GetAllClients()): cutoff = rdfvalue.RDFDatetime().Now() - rdfvalue.Duration("2h") if fd.Get(fd.Schema.PING) < c...
from django import forms from django.contrib import admin from django.contrib.admin import ModelAdmin from guardian.admin import GuardedModelAdmin from uploader.projects.models import FileSystem, Project class FileSystemAdminForm(forms.ModelForm): class Meta: model = FileSystem class ProjectAdmin(GuardedMod...
from zoo.orca.automl.model.base_pytorch_model import PytorchModelBuilder from zoo.orca.automl.auto_estimator import AutoEstimator from zoo.chronos.model.Seq2Seq_pytorch import model_creator from .base_automodel import BasePytorchAutomodel class AutoSeq2Seq(BasePytorchAutomodel): def __init__(self, ...
import ambari_helpers as helpers from resource_management import * class Master(Script): def install(self, env): print('Install the CDAP Master') import params # Add repository file helpers.add_repo( params.files_dir + params.repo_file, params.os_repo_dir ...
from collections import OrderedDict from PyQt4 import QtGui from PyQt4.QtCore import Qt from Orange.data import Table from Orange.classification.svm import SVMLearner, NuSVMLearner from Orange.widgets import settings, gui from Orange.widgets.utils.owlearnerwidget import OWBaseLearner class OWBaseSVM(OWBaseLearner): ...
def uniqc(list): rv = [] n = len(list) if (n == 0): return [] curri = 0 nexti = 1 head = list[curri] count = 1 while (curri < n): if (nexti == n): # Last element in the list if (list[curri] == head): rv.append([head, count]) else: ...
""" pygments.lexers.sw ~~~~~~~~~~~~~~~~~~~~~ Lexers for semantic web languages. :copyright: 2007 by Philip Cooper <philip.cooper@openvest.com>. :license: BSD, see LICENSE for more details. Modified and extended by Gerrit Niezen. (LICENSE file described above is missing, wasn't distributed with o...
from flask import render_template from .. import lastuser_ui @lastuser_ui.route('/') def index(): return render_template('index.html.jinja2')
from __future__ import unicode_literals from django.db import migrations, models from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('eventlog', '0002_auto_20170522_1134'), ] operations = [ ...
import pandas as pd from numba import njit @njit def series_rolling_median(): series = pd.Series([4, 3, 5, 2, 6]) # Series of 4, 3, 5, 2, 6 out_series = series.rolling(3).median() return out_series # Expect series of NaN, NaN, 4.0, 3.0, 5.0 print(series_rolling_median())
from __future__ import absolute_import, division, print_function import math import numpy as np from scipy.interpolate import interp1d def _avgdiff(x): dx = np.diff(x) dx2 = np.zeros_like(x) dx2[0], dx2[-1] = dx[0], dx[-1] dx2[1:-1] = 0.5 * (dx[1:] + dx[:-1]) return dx2 def rebalanced_grid( grid...
from distutils.core import setup setup( name='captcha2upload', packages=['captcha2upload'], package_dir={'captcha2upload': 'src/captcha2upload'}, version='0.2', install_requires=['requests'], description='Upload your image and solve captche using the 2Captcha ' 'Service', a...
''' Created on 10 August 2014 @author: vincent ''' import numpy as np import sys from seizures.data.DataLoader_v2 import DataLoader from seizures.evaluation.XValidation import XValidation from seizures.evaluation.performance_measures import accuracy, auc from seizures.features.FeatureExtractBase import FeatureExtractBa...
"""SCons.Tool.sgiar Tool-specific initialization for SGI ar (library archive). If CC exists, static libraries should be built with it, so the prelinker has a chance to resolve C++ template instantiations. There normally shouldn't be any need to import this module directly. It will usually be imported through the gener...
import os import sys current_path = os.path.dirname(os.path.abspath(__file__)) helper_path = os.path.abspath(os.path.join(current_path, os.pardir, os.pardir, os.pardir, 'data', 'launcher', 'helper')) if __name__ == "__main__": default_path = os.path.abspath(os.path.join(current_path, os.pardir)) noarch_lib = os...
""" Usage: db_ext_split.py <src> <dst> <prob> Options: -h --help """ import os import cv2 from glob import glob from docopt import docopt from mscr.split import Split, RandomSplitPredicate from mscr.util import Crop from mscr.data import MyProgressBar PAD = 8 if __name__ == '__main__': args = docopt(__doc__) ...
from biokit.rtools import package import pytest try: import create_dummy_package as dun except: from . import create_dummy_package as dun def test_install_packages(): d = dun.CreateDummy() d() package.install_package('./dummy/dummytest_1.0.0.tar.gz', verbose=True) d._clean() def test_install_pac...
""" @package mi.instrument.nortek.aquadopp.ooicore.test.test_driver @author Rachel Manoni @brief Test cases for ooicore driver USAGE: Make tests verbose and provide stdout * From the IDK $ bin/test_driver $ bin/test_driver -u $ bin/test_driver -i $ bin/test_driver -q * From pyon ...
order = ['','K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'] class Sizes(object): _BASE = 1000. def toSize(self, value, input='', output='K'): """ Convert value in other measurement """ input = order.index(input) output = order.index(output) factor = input - output ...
import sdl2 as sdl class Context(object): def __init__(self, major, minor, msaa=2): self.major = major self.minor = minor self.msaa = msaa self.context = None self._window = None sdl.SDL_GL_SetAttribute(sdl.SDL_GL_DOUBLEBUFFER, 1) sdl.SDL_GL_SetAttribute(sdl.S...
''' TODO (29.05.2012): 1) show 1x, 2x, 3x threshold (as line) 2) auto scale in y axis? (calc and save min & max values of buffer) 3) draw y axis? 4) 'max_nbr_buffers_transmitted' must be 1 and 'framesize' must be 512 otherwise we get in trouble in RT mode. 5) set 'SHIFT_VIEW' in update() and dequeue in 'do_draw'? ...
from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Changing field 'Student.student_id' db.alter_column('publications_student', 'student_id', self.gf(...
from __future__ import unicode_literals import django from account.views import ChangePasswordView, SignupView, LoginView from django.conf.urls import include, url from django.contrib import admin from example_thirdparty.forms import SignupFormWithCaptcha urlpatterns = [ url(r'^admin/', include(admin.site.urls) if ...
import urllib2 import urllib import os, sys from bs4 import * argv = sys.argv[1:] begin = int(argv[0]) count = int(argv[1]) for i in range(begin, begin+count): try: url = 'http://danbooru.donmai.us/posts/' + str(i) request = urllib2.Request(url) response = urllib2.urlopen(request) ht...
""" Clone server Model Four Author: Min RK <benjaminrk@gmail.com """ import zmq from kvsimple import KVMsg class Route: def __init__(self, socket, identity, subtree): self.socket = socket # ROUTER socket to send to self.identity = identity # Identity of peer who requested state sel...
'''abduction.py Base functionality for logical abduction using a knowledge base of definite clauses Andrew S. Gordon ''' import itertools from . import parse from . import unify def abduction(obs, kb, maxdepth, skolemize = True): '''Logical abduction: returns a list of all sets of assumptions that entail the observ...
import redis_url import unittest class RedisUrlTestSuite(unittest.TestCase): def test_redis_parse_localhost(self): self.assertEqual( redis_url.parse('redis://localhost:6379/0?cluster=false'), { 'host': 'localhost', 'port': 6379, 'db': 0...
from linker import Linker import htmlPage import content.index,content.db,content.fincom spbBudgetXlsPath='../spb-budget-xls' if __name__=='__main__': linker=Linker('filelists',{ 'csv':['csv'], 'xls':['xls'], 'db':['zip','sql','xlsx'], }) htmlPage.HtmlPage('index.html','Данные бюджета Санкт-Петербурга',content...
import zmq import signal interrupted = False def signal_handler(signum, frame): global interrupted interrupted = True if __name__ == '__main__': ctx = zmq.Context() rep = ctx.socket(zmq.REP) rep.bind('tcp://*:5555') print 'reply init sucess ...' try: rep.recv() except KeyboardInterrupt: print 'W...
import datetime import logging JRD_TYPES = ('application/json', 'application/xrd+json', 'text/json') XRD_TYPES = ('application/xrd+xml', 'text/xml') logger = logging.getLogger("rd") def _is_str(s): try: return isinstance(s, basestring) except NameError: return isinstance(s, str) def loads(conten...
""" keybump ~~~~~~~ manage your versioning like a boss . :copyright: (c) 2015 by gregorynicholas. :license: MIT, see LICENSE for more details. """ from __future__ import unicode_literals __version__ = '3.0.1'
"""Wrapper script to run arbitrary bash files from GN. This script should be used only when absolutely necessary and never in a cross-platform way (that is, it should only be used for an action on a particular platform, not an platform-independent target). """ import logging import subprocess import sys if __name__ == ...
from south.utils import datetime_utils as 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 'Face.district_id' db.add_column(u'faces_face', 'district_id', ...
""" A module of restricted Boltzmann machine (RBM) modified from the Deep Learning Tutorials (www.deeplearning.net/tutorial/). Copyright (c) 2008-2013, Theano Development Team All rights reserved. Modified by Yifeng Li CMMT, UBC, Vancouver Sep 23, 2014 Contact: yifeng.li.cn@gmail.com """ from __future__ import division...
from __future__ import absolute_import from collections import namedtuple from django.conf import settings from sentry.utils.dates import to_datetime from sentry.utils.services import LazyServiceWrapper from .backends.base import Backend # NOQA from .backends.dummy import DummyBackend # NOQA backend = LazyServiceWrap...
import unittest import numpy as np import rospy import rostest import os from moveit_ros_planning_interface._moveit_move_group_interface import MoveGroupInterface class PythonMoveGroupNsTest(unittest.TestCase): PLANNING_GROUP = "manipulator" PLANNING_NS = "test_ns/" @classmethod def setUpClass(self): ...
""" Tests related to deprecation warnings. Also a convenient place to document how deprecations should eventually be turned into errors. """ from __future__ import division, absolute_import, print_function import datetime import sys import operator import warnings import pytest import shutil import tempfile import nump...
__author__ = 'Bohdan Mushkevych' from bson import ObjectId from threading import RLock from db.model.raw_data import * from db.model.site_statistics import SiteStatistics from synergy.db.manager import ds_manager from synergy.system.decorator import thread_safe class SiteDao(object): """ Thread-safe Data Access Obj...
import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup readme = open('README.rst').read() history = open('HISTORY.rst').read().replace('.. :changelog:', '') requirements = [ # TODO: put package requirements here ] test_requirements = [ # TODO: put pac...
import sys import time import logging import threading import GPy import numpy as np import matplotlib.pyplot as plt import pdb from GPhelpers import * from IPython.display import display from poap.strategy import FixedSampleStrategy from poap.strategy import InputStrategy from poap.tcpserve import ThreadedTCPServer fr...
from . RunnerBase import RunnerBaseClass from .. Analysers.GPUVerify import GPUVerifyAnalyser import logging import os import psutil import re import sys import yaml _logger = logging.getLogger(__name__) class GPUVerifyRunnerException(Exception): def __init__(self, msg): self.msg = msg class GPUVerifyRunner(Runne...
import re from collections import namedtuple from typing import Optional from esteid import settings from esteid.constants import Languages from esteid.exceptions import InvalidIdCode, InvalidParameter from esteid.signing.types import InterimSessionData from esteid.types import PredictableDict from esteid.validators im...
from PyInstaller.utils.hooks import collect_submodules, collect_data_files datas = collect_data_files('vispy')
from typing import Callable, Iterable, List, Optional import os import numpy as np from PIL import Image, ImageFile ImageFile.LOAD_TRUNCATED_IMAGES = True def image_reader(prefix="", pad_w: Optional[int] = None, pad_h: Optional[int] = None, rescale_w: bool = False, ...
import SCPI import time import numpy totalSamples = 10 sampleFreq = 100 dmm = SCPI.SCPI("172.17.5.131") dmm.setInitiate() dmm.setCurrentDC("500mA", "MAX") dmm.setTriggerSource("INT") dmm.setTriggerCount(str(totalSamples)) dmm.setInitiate() time.sleep(1) currentMeasurements = [] while 1: if len(currentMeasurements) ...
from fanstatic import Library, Resource import js.jquery library = Library('jquery.socialshareprivacy', 'resources') css = Resource(library, 'socialshareprivacy/socialshareprivacy.css') socialshareprivacy = Resource(library, 'jquery.socialshareprivacy.js', minified='jquery.socialsharepriva...
import sys, os, cinesync if len(sys.argv) == 1: print >>sys.stderr, 'Usage: %s <file.mov> ...' % sys.argv[0] sys.exit(1) session = cinesync.Session() session.media = [cinesync.MediaFile(path) for path in sys.argv[1:]] cinesync.commands.open_session(session)
__author__ = "Simon Oldfield" import logging from datacube.api import parse_date_min, parse_date_max, Satellite, DatasetType from datacube.api.query import list_cells_as_list, list_tiles_as_list from datacube.api.query import list_cells_vector_file_as_list from datacube.api.query import MONTHS_BY_SEASON, Season from da...
import glob import os import polib from django import VERSION as DJANGO_VERSION from django.core.management.commands.makemessages import ( Command as OriginalMakeMessagesCommand) from django.utils import translation from django.utils.translation.trans_real import CONTEXT_SEPARATOR class Command(OriginalMakeMessages...
from distutils.core import setup import py2exe setup(console=['server.py'])
import logging; logger = logging.getLogger("morse." + __name__) import socket import select import json import morse.core.middleware from functools import partial from morse.core import services class MorseSocketServ: def __init__(self, port, component_name): # List of socket clients self._client_so...
import unittest from autosklearn.pipeline.components.classification.extra_trees import \ ExtraTreesClassifier from autosklearn.pipeline.util import _test_classifier, \ _test_classifier_iterative_fit, _test_classifier_predict_proba import numpy as np import sklearn.metrics import sklearn.ensemble class ExtraTree...
import El, time, random n0 = n1 = 50 numRowsB = 5 numRHS = 1 display = False output = False worldRank = El.mpi.WorldRank() worldSize = El.mpi.WorldSize() def FD2D(N0,N1): A = El.DistSparseMatrix() height = N0*N1 width = N0*N1 A.Resize(height,width) localHeight = A.LocalHeight() A.Reserve(6*localHeight) fo...
from lib.common import helpers class Module: def __init__(self, mainMenu, params=[]): self.info = { 'Name': 'Get-Screenshot', 'Author': ['@obscuresec', '@harmj0y'], 'Description': ('Takes a screenshot of the current desktop and ' 'returns the o...
__docformat__="restructuredtext" from rest import RestClient, Result, ResponseFormats from datetime import datetime class NeocortexRestClient(object): BASE_URL = "http://api.meaningtool.com/0.2/neocortex" __builder__ = None class Builder(RestClient): _functions = {} _params = {} _inp...
from django import test from django.conf import settings from django.contrib.auth import authenticate from django.contrib.auth.models import User from django.core.management import call_command from mock import patch from nose.tools import eq_ class BcryptTests(test.TestCase): def setUp(self): super(BcryptT...
from getpass import getuser from Job import Job from datetime import datetime import os.path import time import re import Database class Upload( object ): @classmethod def CreateUpload( cls, filename=None ): if not filename: filename = Upload.defaultNewFilename() id = Database.execut...
import pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artificial_dataset as art art.process_dataset(N = 1024 , FREQ = 'D', seed = 0, trendtype = "PolyTrend", cycle_length = 0, transform = "Anscombe", sigma = 0.0, exog_count = 20, ar_order = 12);
import csv import osgeo.ogr from osgeo import ogr, osr EPSG_LAT_LON = 4326 def read_tazs_from_csv(csv_zone_locs_fname): taz_tuples = [] tfile = open(csv_zone_locs_fname, 'rb') treader = csv.reader(tfile, delimiter=',', quotechar="'") for ii, row in enumerate(treader): if ii == 0: continue ...
from functools import wraps from django.utils.translation import ugettext as _ from django.contrib.admin.forms import AdminAuthenticationForm from django.contrib.auth.views import login from django.contrib.auth import REDIRECT_FIELD_NAME def staff_member_required(backoffice): def decorate(view_func): """ ...
import contextlib import os import shutil import tempfile import numpy from PIL import Image from kiva.fonttools import Font from kiva.constants import MODERN class DrawingTester(object): """ Basic drawing tests for graphics contexts. """ def setUp(self): self.directory = tempfile.mkdtemp() ...
from django.shortcuts import get_object_or_404, render_to_response from django.http import Http404, HttpResponseRedirect from django.template import RequestContext from django.core.urlresolvers import reverse from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from djan...
def extractNotoriousOnlineBlogspotCom(item): ''' Parser for 'notorious-online.blogspot.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('PRC', 'PRC', 'translated'), ...
import cx_Logging import os import sys import threading if len(sys.argv) > 1: numThreads = int(sys.argv[1]) else: numThreads = 5 if len(sys.argv) > 2: numIterations = int(sys.argv[2]) else: numIterations = 1000 def Run(threadNum): cx_Logging.Debug("Thread-%d: starting", threadNum) iterationsLeft...
""" Prototype demo: python holoviews/ipython/convert.py Conversion_Example.ipynb | python """ import ast from nbconvert.preprocessors import Preprocessor def comment_out_magics(source): """ Utility used to make sure AST parser does not choke on unrecognized magics. """ filtered = [] for line in ...
import os from fabric.api import env, run, cd, sudo, settings from fabric.contrib.files import upload_template def get_env_variable(var_name): """ Get the environment variable or return exception """ try: return os.environ[var_name] except KeyError: error_msg = "Variable %s is not set in the...
""" Includes the HRV stitcher data source class """ import pandas as pd import numpy as np from scipy.io import loadmat from scipy.interpolate import UnivariateSpline from data_source import DataSource from schema import Schema, Or, Optional def _val(x, pos, label_bin): return np.mean(x) def _std(x, pos, label_bin)...
import os from django.template import Context from django.template.engine import Engine from django.test import SimpleTestCase from .utils import ROOT, TEMPLATE_DIR OTHER_DIR = os.path.join(ROOT, 'other_templates') class RenderToStringTest(SimpleTestCase): def setUp(self): self.engine = Engine(dirs=[TEMPLAT...
from django.db import models from machina.models.fields import ExtendedImageField, MarkupTextField RESIZED_IMAGE_WIDTH = 100 RESIZED_IMAGE_HEIGHT = 100 VALIDATED_IMAGE_MIN_WIDTH = 100 VALIDATED_IMAGE_MAX_WIDTH = 120 VALIDATED_IMAGE_MIN_HEIGHT = 100 VALIDATED_IMAGE_MAX_HEIGHT = 120 VALIDATED_IMAGE_MAX_SIZE = 12000 class...
import tests.model_control.test_ozone_custom_models_enabled as testmod testmod.build_model( ['Fisher'] , ['Lag1Trend'] , ['Seasonal_Hour'] , ['LSTM'] );
"""Python binding of UART wrapper of LetMeCreate library.""" import ctypes _LIB = ctypes.CDLL('libletmecreate_core.so') UART_BD_1200 = 1200 UART_BD_2400 = 2400 UART_BD_4800 = 4800 UART_BD_9600 = 9600 UART_BD_19200 = 19200 UART_BD_38400 = 38400 UART_BD_57600 = 57600 def init(): """Initialise UART on all mikrobus. ...
""" A module to contain utility ISO-19115 metadata parsing helpers """ from _collections import OrderedDict from copy import deepcopy from frozendict import frozendict as FrozenOrderedDict from parserutils.collections import filter_empty, reduce_value, wrap_value from parserutils.elements import get_element_name, get_e...
from django.http import HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext from django.core.urlresolvers import reverse from django.contrib import messages from models import UserVote from forms import UserVoteForm def vote(request): if request.method == ...
from django.forms import ModelForm from .models import DistributionRequests class DistributionRequestForm(ModelForm): class Meta: model = DistributionRequests
from django.contrib import admin from django.contrib.sites.models import RequestSite from django.contrib.sites.models import Site from django.utils.translation import ugettext_lazy as _ from .models import RegistrationProfile from opps.core.admin import apply_opps_rules @apply_opps_rules('registration') class Registrat...
import itertools from whylog.config.investigation_plan import Clue from whylog.constraints.exceptions import TooManyConstraintsToNegate from whylog.front.utils import FrontInput class Verifier(object): UNMATCHED = Clue(None, None, None, None) @classmethod def _create_investigation_result(cls, clues_combinat...
from __future__ import unicode_literals import sqlite3 from flask import Flask, render_template, g, current_app, request from flask.ext.paginate import Pagination app = Flask(__name__) app.config.from_pyfile('app.cfg') @app.before_request def before_request(): g.conn = sqlite3.connect('test.db') g.conn.row_fact...
from serial_settings import SerialSettings class AbstractStream(object): def __init__(self, config, name): """ :type name: str """ self.config = config self.name = name def open(self): raise NotImplementedError def close(self): raise NotImplementedErro...
from __future__ import division, print_function, absolute_import import warnings import numpy as np from scipy.special import factorial from scipy.lib.six import xrange __all__ = ["KroghInterpolator", "krogh_interpolate", "BarycentricInterpolator", "barycentric_interpolate", "PiecewisePolynomial", ...
import urllib def command_oraakkeli(bot, user, channel, args): """Asks a question from the oracle (http://www.lintukoto.net/viihde/oraakkeli/)""" if not args: return args = urllib.quote_plus(args) answer = getUrl("http://www.lintukoto.net/viihde/oraakkeli/index.php?kysymys=%s&html=0" % args).getContent(...
import datetime from django.db import models, IntegrityError from django.contrib.auth.models import User from django.contrib.sites.models import Site from django.core.urlresolvers import reverse as django_reverse from django.utils.http import urlquote from django.conf import settings from tower import ugettext as _, ug...
default_app_config = 'allink_apps.locations.apps.AllinkLocationsConfig' __version__ = '0.0.1'
import subprocess import os import sys import commands import numpy as np import pyroms import pyroms_toolbox from remap_bio_woa import remap_bio_woa from remap_bio_glodap import remap_bio_glodap data_dir_woa = '/archive/u1/uaf/kate/COBALT/' data_dir_glodap = '/archive/u1/uaf/kate/COBALT/' dst_dir='./' src_grd = pyroms...
from .utils import bash, filter_python_files DEFAULT = 'off' CHECK_NAME = 'frosted' NO_FROSTED_MSG = ( "frosted is required for the frosted plugin.\n" "`pip install frosted` or turn it off in your tox.ini file.") REQUIRED_FILES = ['tox.ini'] def run(files, temp_folder): "Check frosted errors in the code bas...
from unittest import TestCase import logging log = logging.getLogger(__name__) from formencode import validators, Invalid from nose.tools import * import formencode from coregae.widget.field import * class TestBasefield(TestCase): def test_basefield(self): """ Test for functions of BaseFields ...
import optparse from os import curdir from os.path import abspath import sys from autoscalebot.tasks import start_autoscaler from autoscalebot import version def main(args=sys.argv[1:]): CLI_ROOT = abspath(curdir) sys.path.insert(0, CLI_ROOT) parser = optparse.OptionParser( usage="%prog or type %pro...
AuthorizedException = ( BufferError, ArithmeticError, AssertionError, AttributeError, EnvironmentError, EOFError, LookupError, MemoryError, ReferenceError, RuntimeError, SystemError, TypeError, ValueError )
import numpy from numpy import dot, sqrt def binarize_vector(u): return u > 0 def cosine_distance(u, v, binary=False): """Return the cosine distance between two vectors.""" if binary: return cosine_distance_binary(u, v) return 1.0 - dot(u, v) / (sqrt(dot(u, u)) * sqrt(dot(v, v))) def cosine_dist...
import json from unittest import mock from oauthlib.common import Request from oauthlib.oauth2.rfc6749 import errors from oauthlib.oauth2.rfc6749.grant_types import ( ResourceOwnerPasswordCredentialsGrant, ) from oauthlib.oauth2.rfc6749.tokens import BearerToken from tests.unittest import TestCase class ResourceOwn...
import typing import anyio from starlette.requests import Request from starlette.responses import Response, StreamingResponse from starlette.types import ASGIApp, Receive, Scope, Send RequestResponseEndpoint = typing.Callable[[Request], typing.Awaitable[Response]] DispatchFunction = typing.Callable[ [Request, Reque...
from .fetchers import NUMetadatasFetcher from .fetchers import NUGlobalMetadatasFetcher from bambou import NURESTObject class NUCTranslationMap(NURESTObject): """ Represents a CTranslationMap in the VSD Notes: 1:1 mapping of customer private IPs in customer domain to customer alias (public) IPs ...
from __future__ import unicode_literals from os.path import abspath, basename, dirname, join, normpath from sys import path import markdown """Common settings and globals.""" DJANGO_ROOT = dirname(dirname(abspath(__file__))) SITE_ROOT = dirname(DJANGO_ROOT) SITE_NAME = basename(SITE_ROOT) path.append(DJANGO_ROOT) DEBUG...
from json import loads from collections import defaultdict from qiita_core.util import execute_as_transaction from qiita_core.qiita_settings import r_client from qiita_db.util import generate_analyses_list_per_study from qiita_db.metadata_template.sample_template import SampleTemplate from qiita_db.exceptions import Qi...
from __future__ import unicode_literals from django.utils.encoding import python_2_unicode_compatible """ Model for testing arithmetic expressions. """ from django.db import models @python_2_unicode_compatible class Number(models.Model): integer = models.BigIntegerField(db_column='the_integer') float = models.F...
from django.contrib import admin from achievs.models import Achievement from achievs.models import Level # model=Platinum # model=Gold # model=Silver # model=Bronze class LevelInline(admin.StackedInline): model=Level class AchievementAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': [...
import numpy as np import pytest from pandas import ( DataFrame, Index, Series, ) import pandas._testing as tm import pandas.core.common as com class TestSample: @pytest.fixture(params=[Series, DataFrame]) def obj(self, request): klass = request.param if klass is Series: ...
from functools import reduce class ScopedString (object): def __init__ (self): self._stack = [] def push (self, frame): self._stack.append (frame) def pop (self): frame = self._stack.pop() return frame def __str__ (self): ...
import os from sublime import active_window from sublime import find_resources from sublime import load_settings from sublime import save_settings import sublime_plugin def _load_preferences(): return load_settings('Preferences.sublime-settings') def _save_preferences(): return save_settings('Preferences.sublim...