code
stringlengths
1
199k
from base import * from test_create_virtual_machine import * from test_destroy_virtual_machine import * from test_provider import *
import collections from functools import reduce class DiffObject: def __init__(self): self.compartments = {} self.add_compartment("NONE") self.events = [] # should probably be moved into compartment ? self.param_nodes = [] def add_compartment(self, compartment_id): self....
from __future__ import absolute_import import json import os import tempfile import shutil import numpy as np import pandas as pd from pandas.util.testing import assert_frame_equal from shapely.geometry import Point, Polygon import fiona from geopandas import GeoDataFrame, read_file, GeoSeries from geopandas.tests.util...
import warnings from paste.fixture import TestApp from paste.registry import RegistryManager import pylons from pylons import Response from pylons.decorators import jsonify from pylons.controllers import Controller, WSGIController, XMLRPCController from __init__ import TestWSGIController, SetupCacheGlobal, ControllerWr...
import pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artificial_dataset as art art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "LinearTrend", cycle_length = 30, transform = "Quantization", sigma = 0.0, exog_count = 100, ar_order = 0);
import sys from .codes import codes if sys.version_info[0] >= 3: unichr = chr def build_8859_translation(codes): codes_8859 = {} for code in codes: translation = codes[code] tr_8859 = translation try: tr_8859 = unichr(code).encode('iso-8859-1') except UnicodeEncod...
""" byceps.blueprints.admin.ticketing.category.views ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from flask import abort, request from flask_babel import gettext from .....permissions.ticketing import TicketingPer...
from kivy.core.window import Window from kivy.uix.floatlayout import FloatLayout from kivy.uix.label import Label from constants import * class Game(FloatLayout): def __init__(self, **kwargs): FloatLayout.__init__(self, **kwargs) self.android = kwargs['android'] if 'levels' in kwargs and kwa...
""" forms.py :copyright: (c) 2014 by Openlabs Technologies & Consulting (P) Limited :license: BSD, see LICENSE for more details. """ from flask_wtf import Form from wtforms import TextField, TextAreaField, SelectField, DecimalField, \ validators from wtforms.validators import ValidationError from nereid...
from __future__ import absolute_import, division, unicode_literals import param from .chart import ScatterPlot class LabelPlot(ScatterPlot): xoffset = param.Number(default=None, doc=""" Amount of offset to apply to labels along x-axis.""") yoffset = param.Number(default=None, doc=""" Amount of offse...
import numpy as np from deli.demo_utils.js_view import JSView from deli.graph import Graph from deli.artist.line_artist import LineArtist class Demo(JSView): def setup_graph(self): graph = Graph() graph.title.text = "Line Artist" x = np.linspace(0, 10) y = np.sin(x) artist = ...
from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic from django.db import models from django.utils.translation import ugettext_lazy as _ class CriteriaObjects(models.Model): """Assigns arbitrary criteria to arbitrary content objects. """ class Meta: ...
import errno import os import selectors import signal import socket import struct import sys import threading from . import connection from . import process from . import reduction from . import semaphore_tracker from . import spawn from . import util from .compat import spawnv_passfds __all__ = ['ensure_running', 'get...
from __future__ import absolute_import, unicode_literals import os import re import datetime try: from urllib.parse import urljoin except ImportError: # Python 2 from urlparse import urljoin from django.conf import settings, global_settings from django.core import mail from django.core.exceptions import Suspic...
import os import sys try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup, find_packages readme = open('README.rst').read() requirements = [ 'django>=1.7', 'django-model-utils>=2.2', 'phabricator', 'pytz', ] extras = { 'develop': ['mock'], } s...
from __future__ import absolute_import from django.conf import settings from django.core.exceptions import ObjectDoesNotExist, ValidationError from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.auth.decorators import user_passes_test from django.shortcuts import ...
from sentry.utils.locking.lock import Lock class LockManager(object): def __init__(self, backend): self.backend = backend def get(self, key, duration, routing_key=None): """ Retrieve a ``Lock`` instance. """ return Lock(self.backend, key, duration, routing_key)
from sklearn_explain.tests.skl_datasets import skl_datasets_test as skltest skltest.test_class_dataset_and_model("digits" , "SVC_poly_8")
import numpy as np from numpy.testing import assert_array_equal from metpy.calc.tools import resample_nn_1d def test_resample_nn(): 'Test 1d nearest neighbor functionality.' a = np.arange(5.) b = np.array([2, 3.8]) truth = np.array([2, 4]) assert_array_equal(truth, resample_nn_1d(a, b))
import pytest from datetime import datetime, timedelta from numpy import nan import numpy as np import pandas as pd import pandas._libs.index as _index from pandas.core.dtypes.common import is_integer, is_scalar from pandas import (Index, Series, DataFrame, isna, date_range, NaT, MultiIndex, ...
import unittest import torch from fairseq.data import LanguagePairDataset, TokenBlockDataset from fairseq.data.concat_dataset import ConcatDataset from tests.test_train import mock_dict class TestConcatDataset(unittest.TestCase): def setUp(self): d = mock_dict() tokens_1 = torch.LongTensor([1]).view...
"""Harvest process for the HackerNews Source.""" import itertools import logging from collections import defaultdict from remotes.decorators import periodically from .hackernews_wrapper import HackerHarvest logger = logging.getLogger(__name__) class Harvester(object): """Simple Harvester to gather hackernews posts....
import sys import os sys.path.insert(0, os.path.abspath('transform.py')) extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.mathjax', ] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'ind...
import numpy as np from bokeh.io import output_file, show from bokeh.models import ColumnDataSource, HoverTool from bokeh.plotting import figure from bokeh.sampledata.stocks import AAPL output_file("tools_hover_tooltip_formatting.html") def datetime(x): return np.array(x, dtype=np.datetime64) source = ColumnDataSou...
from setuptools import setup setup( name = 'WikiTableMacro', author = 'Martin Aspeli', author_email = 'optilude@gmail.com', maintainer = 'Ryan J Ollos', maintainer_email = 'ryano@physiosonics.com', description = 'Trac plugin for drawing a table from a SQL query in a wiki page', url = 'http:/...
from django.core.urlresolvers import reverse, NoReverseMatch from django.db.models.query import QuerySet from cyder.base.constants import ACTION_UPDATE from cyder.base.helpers import cached_property import json class Tablefier: def __init__(self, objects, request=None, extra_cols=None, users=False,...
r""" The potential fields of a homogeneous triaxial ellipsoid. """ from __future__ import division import numpy as np from scipy.special import ellipeinc, ellipkinc from ..constants import SI2MGAL, G, CM, T2NT, SI2EOTVOS, PERM_FREE_SPACE from .. import utils from .._our_duecredit import due, Doi due.cite(Doi("XXXXXXXXX...
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 'Contacts.fax' db.add_column('sitecontacts_contacts', 'fax', self.gf('django.db.models.fields.CharField')(default=0, max...
class BadRequestError(Exception): """ For catching client-side errors. Views should catch and return HTTP400 or similar """ pass class UnsupportedSavedReportError(Exception): """ For unknown (discontinued/legacy) saved-reports """ pass class UnsupportedScheduledReportError(Exception)...
from survey.features.page_objects.base import PageObject from nose.tools import assert_equals class BatchQuestionsListPage(PageObject): def __init__(self, browser, batch): self.browser = browser self.batch = batch self.url = '/batches/%d/questions/' % batch.id def validate_fields(self): ...
import os import json import pytest from click.testing import CliRunner from cookiecutter.cli import main from cookiecutter.main import cookiecutter from cookiecutter import utils, config runner = CliRunner() @pytest.fixture def remove_fake_project_dir(request): """ Remove the fake project directory created dur...
from celery import current_app from celery.utils import deprecated send_task = current_app.send_task @deprecated(removal="2.3", alternative="Use task.apply_async() instead.") def apply_async(task, *args, **kwargs): """*[Deprecated]* Use `task.apply_async()`""" return task.apply_async(*args, **kwargs) @deprecate...
"""Super state machine - package that helps creating state machines.""" __author__ = 'Szczepan Cieślik' __email__ = 'szczepan.cieslik@gmail.com' __version__ = '2.0.2'
import os import sys import json def setup(i): """ Input: { cfg - meta of this soft entry self_cfg - meta of module soft ck_kernel - import CK kernel module (to reuse functions) host_os_uoa - host OS UOA host...
import numpy as np import os, os.path from glob import glob def generate_big_data(l=200, t=20): x, y, z = np.mgrid[0:5:l*1j, 0:5:l*1j, 0:5:l*1j] if os.path.exists('data'): [os.remove(filename) for filename in glob('data/data*.npy')] else: os.mkdir('data') for t in np.linspace(0, 1, t + 1...
from __future__ import unicode_literals from django.db import models from django.contrib.localflavor.us.models import USStateField class Group(models.Model): name = models.CharField(max_length=20) def __unicode__(self): return '%s(%d)' % (self.name, self.pk) class User(models.Model): username = mod...
""" Unified interfaces to minimization algorithms. Functions --------- - minimize : minimization of a function of several variables. - minimize_scalar : minimization of a function of one variable. """ from __future__ import division, print_function, absolute_import __all__ = ['minimize', 'minimize_scalar'] from warning...
""" Contains tests for the base metric class. """ from statsite.metrics import Metric class TestMetric(object): def test_fold_basic(self): """Tests folding over a normal metric returns the key/value using the flag as the timestamp.""" metrics = [Metric("k", 27, 123456)] assert [("k",...
from unittest import TestCase, main from mock import patch from itty import Request, Response from simplejson import dumps from publisher.errors import (bad_syntax, unauthorized, forbidden, not_found, internal_error) from publisher.utils import (JsonBadSyntax, JsonUnauthorized, JsonForbidd...
from __future__ import division import copy import math import os import uuid from PyQt4 import QtCore, QtGui import vistrails.core.analogy from vistrails.core.configuration import get_vistrails_configuration from vistrails.core.data_structures.graph import Graph from vistrails.core import debug import vistrails.core.d...
import sys import os import shutil import subprocess script_dir = os.path.normpath(os.path.dirname(os.path.abspath(__file__))) o3d_dir = os.path.dirname(os.path.dirname(script_dir)) src_dir = os.path.dirname(o3d_dir) third_party_dir = os.path.join(o3d_dir, 'third_party') internal_dir = os.path.join(src_dir, 'o3d-intern...
import collections.abc import difflib import functools import inspect import io import mmap import os import os.path import platform import textwrap import warnings from typing import ( Any, BinaryIO, Callable, cast, Collection, Iterable, Iterator, Mapping, NoReturn, Sequence, ...
from StringIO import StringIO def jsmin(js): ins = StringIO(js) outs = StringIO() JavascriptMinify().minify(ins, outs) str = outs.getvalue() if len(str) > 0 and str[0] == '\n': str = str[1:] return str def isAlphanum(c): """return true if the character is a letter, digit, underscore,...
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 = "Logit", sigma = 0.0, exog_count = 0, ar_order = 0);
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 = "Lag1Trend", cycle_length = 30, transform = "Fisher", sigma = 0.0, exog_count = 20, ar_order = 0);
from lettuce import step, world @step(r'(?:visit|access|open) the url "([^"]*)"$') def go_to_the_url(step, url): world.response = world.browser.visit(url) @step(r'go back(?: a page)?$') def go_back(step): world.browser.back() @step(r'go forward(?: a page)?$') def go_forward(step): world.browser.forward() @s...
import sys try: from mpi4py import MPI except: pass from ..fend import Fend from ..hic_data import HiCData from ..hic import HiC def run(args): if 'mpi4py' in sys.modules.keys(): comm = MPI.COMM_WORLD rank = comm.Get_rank() num_procs = comm.Get_size() else: comm = None ...
from __future__ import absolute_import from sentry.eventstore.processing import event_processing_store def write_event_to_cache(event): cache_data = event.data cache_data["event_id"] = event.event_id cache_data["project"] = event.project_id return event_processing_store.store(cache_data)
"""The ants module provides basic functions for interfacing with ants functions. Change directory to provide relative paths for doctests >>> import os >>> filepath = os.path.dirname( os.path.realpath( __file__ ) ) >>> datadir = os.path.realpath(os.path.join(filepath, '../../testing/data')) >>> os.chdir(d...
"""Class capturing a command invocation as data.""" import toolchain_env import multiprocessing import os import sys import file_tools SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) NACL_DIR = os.path.dirname(SCRIPT_DIR) def FixPath(path): """Convert to msys paths on windows.""" if sys.platform != 'win32':...
def partitiion(int_list, left, right: right = right+1 while(left <= right) while(int_list[right] > pivot): left-=1 while(int_list[left] < pivot): right+=1 i return right def quicksort(int_list, right, left): if begin != end: pivot = partition(int_list, ri...
from __future__ import print_function import numpy as np import scipy.sparse as sp import warnings from abc import ABCMeta, abstractmethod from . import libsvm, liblinear from . import libsvm_sparse from ..base import BaseEstimator, ClassifierMixin from ..preprocessing import LabelEncoder from ..utils import atleast2d_...
""" Copyright (c) 2015 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. Exceptions raised by OSBS """ from traceback import format_tb class OsbsException(Exception): def __init__(self, message=None, cause=None, trac...
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def vmDetect(): strComputer = "." objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator") objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2") colItems = objSWbemServices.ExecQuery("SELECT * FROM Win32_ComputerSyste...
import json from django.http import HttpResponse from django.views.generic.base import View from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.views.generic.list import ListView from mediacontent.models import MediaContent class AjaxableResponseMixin(object): def render_to_json_res...
""" Configure urls for the jobs app. The default base for these urls is /jobs/ """ from django.conf.urls import url from .views import (JobListView, JobDetailView, PostListView, PostActionView, UserJobListView, UserJobActionView, UserJobRedirectView) urlpatterns = [ url(r'^my-opportunities/$', U...
from django.utils.translation import ugettext as _ FORTUNE_DELIMITER = _(u'%') FORTUNE_DELIMITER_BY = _(u'%% by %s') FORTUNE_COMMENT_TEMPLATE = _(u'- %s') ORIGIN_IMPORTED_STR = _(u'Importado') ORIGIN_SUBMITTED_STR = _(u'Enviado') FORTUNE_MODEL = _(u'Chicha fortune') FORTUNE_MODEL_PLURAL = _(u'Chicha fortunes') BODY_FOR...
from modulefinder import ModuleFinder f = ModuleFinder() f.run_script('/home/pro_knight/PycharmProjects/ArDicSenti-Flask/myapp.py') names = list(f.modules.keys()) basemods = sorted(set([name.split('.')[0] for name in names])) print ("\n".join(basemods))
import sonicbitly arguments = ["self", "info", "args"] helpstring = "bitly <shorten|expand|clicks> <url>" minlevel = 2 api = sonicbitly.Api(login="sonicrules1234", apikey="R_919d42a0ee9fd225e339d73c7d54d0f9") def main(connection, info, args) : if args[1] == "shorten" : connection.msg(info["channel"], "%(sen...
APP_REDIS_KEY = "redis" APP_STORAGE_KEY = "storage"
SINGLE_SMS_URL = 'http://103.16.59.36/MtSendSMS/SingleSMS.aspx' LONG_TEXT_MSG_TYPE = '4' LONG_UNICODE_MSG_TYPE = '5' SUCCESS_RESPONSE_REGEX = r'^\d+-\d+(,\d+-\d+)*$' UNRETRYABLE_ERROR_MESSAGES = [ 'Invalid UserName', 'Invalid Password', 'Account Blocked', 'Please Validate IP', 'Insufficient Funds', ...
from __future__ import unicode_literals import datetime from decimal import Decimal from django.conf import settings from django.core.urlresolvers import reverse from django.core.validators import MinValueValidator, RegexValidator from django.db import models from django.db.models import Q, Manager from django.utils.en...
"""Ce fichier contient la classe PotionsVente, détaillée plus bas.""" from abstraits.obase import BaseObj from .potion_vente import PotionVente class PotionsVente(BaseObj): """Classe enveloppe de toutes les potions en vente. Cette classe est un dictionnaire fictif contenant des PotionVente (voir ./potion_ve...
import os import sys sys.path.insert(0, os.getcwd()) sys.path.insert(0, os.path.join(os.getcwd(), os.pardir)) from cyme.bin.base import app, Env from cyme.utils import cached_property, Path, uuid from eventlet.event import Event from nose import SkipTest from .utils import unittest CYME_PORT = int(os.environ.get("CYME_...
import os from setuptools import setup install_requires = [ 'Flask', 'Flask-Babel', ] if os.path.exists('README'): with open('README') as f: readme = f.read() else: readme = None setup( name='Flask-Table', packages=['flask_table'], version='0.5.0', author='Andrew Plummer', au...
from sklearn2sql_heroku.tests.classification import generic as class_gen class_gen.test_model("SVC_rbf" , "digits" , "postgresql")
import os.path import operator import itertools GTFS_BEAN = "org.opentripplanner.graph_builder.model.GtfsBundle" GTFS_PROP_PATH = "path" GTFS_PROP_BIKES = "defaultBikesAllowed" GTFS_PROP_AGENCY_ID = "defaultAgencyId" MODE_ALLOW_BIKES = { 'train': 'true', 'tram': 'false', 'bus': 'false', 'bus-mway': 'fal...
from __future__ import division, print_function import math import os DYNAMIC_RANGE = 0x100 ORIGIN = DYNAMIC_RANGE >> 1 MAX_OFFSET = 0x7F WAVE_LENGTH = 0x100 TAU = math.pi * 2 # The useful circle constant! def zero_wave(): """ A flat line about the origin. """ return [0] * WAVE_LENGTH def sine_wave(): ...
import random def pick_a_card(): suits = ["Hearts", "Spades", "Clubs", "Diamonds"] ranks = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"] rank_drawn = suits[random.randint(0,3)] card_drawn = cards[random.randint(0,12)] card = rank_drawn + " of " + suit_drawn return card i=0 while (...
from __future__ import division import sys import pytest import itertools from gmpy_cffi import mpq, mpz, mpfr from math import sqrt PY3 = sys.version.startswith('3') if PY3: long = int floats = [0.0, 1.0, 1.5, 1e15 + 0.9, -1.5e15 + 0.9] invalids = [(), [], set(), dict(), lambda x: x**2] ints = [1, -1, 2, -123, 456...
""" Testing field subclasses in different layers. """ from simkit.core import UREG, Parameter from simkit.core.data_sources import DataSource, DataParameter from simkit.contrib.readers import ArgumentReader class VelocityData(DataSource): distance = DataParameter(units='m', isconstant=True, uncertainty=0.01, ...
"""Javascript minifier""" import re def minify(src): _res, pos = '', 0 while pos < len(src): if src[pos] in ('"', "'", '`') or \ (src[pos] == '/' and src[pos - 1] == '('): # the end of the string is the next quote if it is not # after an odd number of backslashes ...
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('contenttypes', '0001_initial'), ] operations = [ migrations.CreateModel( name='Tag', fields=[ ('id', models.AutoF...
"""Secondary mirror focus control. History: 2004-01-09 ROwen first draft 2004-02-23 ROwen Modified to play cmdDone/cmdFailed for commands. 2004-03-11 ROwen Bug fix: assumed the secondary mirror would start moving within 10 seconds (a poor assumption if others are moving ...
from settings.dependencies.base_settings import * SUIT_CONFIG = { # header 'ADMIN_NAME': 'Funky Dashboard', # 'HEADER_DATE_FORMAT': 'l, j. F Y', # 'HEADER_TIME_FORMAT': 'H:i', # forms 'SHOW_REQUIRED_ASTERISK': True, # Default True 'CONFIRM_UNSAVED_CHANGES': True, # Default True # menu ...
from sqlalchemy import create_engine, MetaData from sqlalchemy.orm import sessionmaker, scoped_session from system.config import config engine = create_engine('postgresql://'+config.get('Database','username')+':'+config.get('Database','password')+'@'+config.get('Database','host')+':'+config.get('Database','port')+'...
from django.db import models from django.db.models.fields import Field class TimeStampedModel(models.Model): """ A abstract model that provides self-updating (created) and modified fields. """ created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) class ...
""" .. todo:: WRITEME """ import numpy as np from pylearn2.datasets.semi_supervised import SemiSupervised from pylearn2.datasets import dense_design_matrix from pylearn2.utils.serial import load from pylearn2.utils.rng import make_np_rng from pylearn2.utils import contains_nan class TFDSemi(SemiSupervised): """...
import sys, os, urllib, cStringIO, traceback, cgi, binascii, gzip import time, random, smtplib, base64, email, types, urlparse import re, zipfile, shutil, Cookie, subprocess, hashlib import logging from zope.pagetemplate.pagetemplatefile import PageTemplateFile from distutils.util import rfc822_escape from distutils2.m...
from __future__ import print_function import cPickle as pickle import json import pandas as pd import numpy as np from rq.job import Status from kitchensink.testutils.testrpc import make_rpc, dummy_add from kitchensink.serialization import (json_serialization, pickle_serialization...
from code_generator import * class BenchmarkGenerator: """ Class responsible for generating benchmarks of the different functions. """ def __init__(self, name, arguments): self.name = name self.arguments = arguments self.input_arrs = [ arg for arg in self.arguments if arg.is_poin...
import tensorflow as tf slim = tf.contrib.slim def concordance_cc2(prediction, ground_truth): """Defines concordance metric for model evaluation. Args: prediction: prediction of the model. ground_truth: ground truth values. Returns: The concordance value. """ names_to_values, na...
from oauth2client.client import GoogleCredentials from oauth2client.client import AccessTokenRefreshError import httplib2 from argparse import ArgumentParser import os, sys, tempfile, subprocess import getpass import json global_error_message = """ ********************************************************************...
import os import numpy as np import pandas as pd import xarray as xr import rampwf as rw problem_title = 'El Nino forecast' Predictions = rw.prediction_types.make_regression() workflow = rw.workflows.ElNino(check_sizes=[13], check_indexs=[13]) score_types = [ rw.score_types.RMSE(name='rmse', precision=3), ] cv = rw...
""" The `bapsflib` package is an open-source Python packaged designed by the Basic Plasma Science Facility (BaPSF) group at the University of California, Los Angeles (UCLA). It is a toolkit for reading, manipulating, and analyzing data collected at BaPSF. """ __all__ = ["lapd"] import pkg_resources from bapsflib impor...
from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext sourcefiles = ['ketama.pyx', 'ketama_lib.c', 'md5.c'] setup( cmdclass = {'build_ext': build_ext}, ext_modules = [Extension("ketama", sourcefiles)] )
import markdown import re from fenced_code_plus import FencedCodePlusExtension import unittest import pytest unadorned_code_block_md = """\ ``` def foo(): bar = 4 return 8 ``` """ unadorned_code_block_html = """\ <pre><code>def foo(): bar = 4 return 8 </code></pre>""" only_language_md = """\ ``` python ...
import unittest import os import comm class TestCrosswalkApptoolsFunctions(unittest.TestCase): def test_setting_value(self): comm.setUp() os.chdir(comm.XwalkPath) comm.clear("org.xwalk.test") os.mkdir("org.xwalk.test") os.chdir('org.xwalk.test') cmd = comm.HOST_PREFIX...
import resource import sys from ConfigSpace.configuration_space import ConfigurationSpace from ConfigSpace.conditions import EqualsCondition, InCondition from ConfigSpace.hyperparameters import UniformFloatHyperparameter, \ UniformIntegerHyperparameter, CategoricalHyperparameter, \ UnParametrizedHyperparameter ...
''' sequential ~~~~~~~~~~~~~~~~~~~~~~~~ .. autofunction:: sequential ActorTestMixin ~~~~~~~~~~~~~~~~~~~~~~~~ .. autoclass:: ActorTestMixin :members: :member-order: bysource AsyncAssert ~~~~~~~~~~~~~~~~~~~~~~~~ .. autoclass:: AsyncAssert :members: :member-order: bysource check server ~~~~~~~~~~~~~~~~~~ .. au...
from __future__ import unicode_literals from django.db import models, migrations import sorl.thumbnail.fields import millionmilestogether.models.child import django.utils.timezone from django.conf import settings import django.core.validators class Migration(migrations.Migration): dependencies = [ ('auth', ...
import inspect import importlib from rest_framework.fields import Field from rest_framework.serializers import BaseSerializer def _signature_parameters(func): try: inspect.signature except AttributeError: # Python 2.x return inspect.getargspec(func).args else: # Python 3.x ...
"""private module containing functions used for copying data between instances based on join conditions. """ from sqlalchemy import schema, exceptions, util from sqlalchemy.sql import visitors, operators, util as sqlutil from sqlalchemy import logging from sqlalchemy.orm import util as mapperutil from sqlalchemy.orm.in...
usage = """%prog -- map py-cfg parse trees to words Version of 17th August, 2010 (c) Mark Johnson usage: %prog [options] """ import lx, tb import optparse, re, sys def tree_string(tree): def simplify_terminal(t): if len(t) > 0 and t[0] == '\\': return t[1:] else: return t ...
import string class Solution(object): def convertToTitle(self, n): """ :type n: int :rtype: str """ alphabet = string.uppercase ret = '' while n > 0: ret = alphabet[(n - 1) % 26] + ret n = (n - 1) / 26 return ret
import doctest import pickle import unittest from genshi import core from genshi.core import Markup, Attrs, Namespace, QName, escape, unescape from genshi.input import XML, ParseError from genshi.compat import StringIO, BytesIO class StreamTestCase(unittest.TestCase): def test_render_utf8(self): xml = XML('...
""" The v1 Authorization "service" that enables developers to retrieve a temporary access token """ from watson_developer_cloud.watson_developer_cloud_service import WatsonDeveloperCloudService try: import urllib.parse as urlparse # Python 3 except ImportError: import urlparse # Python 2 class AuthorizationV1...
""" =========================================== OT mapping estimation for domain adaptation =========================================== This example presents how to use MappingTransport to estimate at the same time both the coupling transport and approximate the transport map with either a linear or a kernelized mappin...
import unittest import numpy import chainer from chainer.backends import cuda from chainer import links from chainer import testing from chainer.testing import attr class TestInceptionBNBase(unittest.TestCase): in_channels = 3 out1, proj3, out3, proj33, out33, proj_pool = 3, 2, 3, 2, 3, 3 pooltype = 'max' ...
import random import string from decimal import Decimal import tempfile from datetime import datetime, timedelta import uuid from django.conf import settings from django.core.management.base import BaseCommand from django.db import transaction from django.utils import translation from membership.billing import pdf from...