content stringlengths 4 20k |
|---|
# -*- coding:utf8 -*-
from __future__ import print_function
import os
from android_tools import InstallApkTask, CleanAllCacheTask
from builder import CleanBuilder
from gradle_tools import GenerateFileStatTask, BuildBaseResourceTask, get_project_info, GenerateAptFilesStatTask, \
get_gradle_executable
from task imp... |
from unittest import TestCase
from yql.utils import get_http_method
class UtilitiesTest(TestCase):
def test_finds_get_method_for_select_query(self):
self.assertEqual(get_http_method("SELECT foo"), "GET")
def test_finds_get_method_for_select_query_with_leading_space(self):
self.assertEqual(ge... |
#!python
# capture web2py environment before doing anything else
web2py_environment = dict(globals())
__doc__ = """This script is run from the nose command in the
application being tested:
e.g.
python2.6 ./applications/eden/tests/nose.py <nose arguments>
web2py runs a file which:
1. Sets up a plugin. This plugi... |
import hashlib
from social.utils import handle_http_errors
from social.backends.base import BaseAuth
class LastFmAuth(BaseAuth):
"""
Last.Fm authentication backend. Requires two settings:
SOCIAL_AUTH_LASTFM_KEY
SOCIAL_AUTH_LASTFM_SECRET
Don't forget to set the Last.fm callback to somethi... |
import math
from numba import types, utils
from numba.typing.templates import (AttributeTemplate, ConcreteTemplate,
signature, Registry)
registry = Registry()
infer_global = registry.register_global
@infer_global(math.exp)
@infer_global(math.expm1)
@infer_global(math.fabs)
@infer_... |
import random
import six
from oslo_log import log as logging
from designate import exceptions
from designate import utils
from designate.backend import base
LOG = logging.getLogger(__name__)
DEFAULT_MASTER_PORT = 5354
class Bind9Backend(base.Backend):
__plugin_name__ = 'bind9'
__backend_status__ = 'integ... |
class ExceptionFinishBreakpoint(gdb.FinishBreakpoint):
def __init__(self, frame):
gdb.FinishBreakpoint.__init__ (self, frame, internal=1)
self.silent = True
print ("init ExceptionFinishBreakpoint")
def stop(self):
print ("stopped at ExceptionFinishBreakpoint")
re... |
doctests = """
Unpack tuple
>>> t = (1, 2, 3)
>>> a, b, c = t
>>> a == 1 and b == 2 and c == 3
True
Unpack list
>>> l = [4, 5, 6]
>>> a, b, c = l
>>> a == 4 and b == 5 and c == 6
True
Unpack implied tuple
>>> a, b, c = 7, 8, 9
>>> a == 7 and b == 8 and c == 9
True
Unpa... |
"""WSGI script for Nova API
EXPERIMENTAL support script for running Nova API under Apache2 etc.
"""
from oslo_config import cfg
from oslo_log import log as logging
from paste import deploy
from nova import config
from nova import objects
from nova import service # noqa
from nova import utils
CONF = cfg.CONF
conf... |
""" A Hiber file Address Space """
import volatility.addrspace as addrspace
import volatility.obj as obj
import volatility.win32.xpress as xpress
import struct
#pylint: disable-msg=C0111
PAGE_SIZE = 0x1000
page_shift = 12
class Store(object):
def __init__(self, limit = 50):
self.limit = limit
se... |
import os
import sys
import unittest
sys.path.insert(1, os.path.abspath(os.path.join(__file__, "../..")))
import base_test
repo_root = os.path.abspath(os.path.join(__file__, "../../.."))
sys.path.insert(1, os.path.join(repo_root, "tools", "webdriver"))
from webdriver import exceptions, wait
class ClickTest(base_tes... |
"""Algorithms for partial fraction decomposition of rational functions. """
from __future__ import print_function, division
from sympy.polys import Poly, RootSum, cancel, factor
from sympy.polys.polytools import parallel_poly_from_expr
from sympy.polys.polyoptions import allowed_flags, set_defaults
from sympy.polys.p... |
from HTMLParser import HTMLParser as _HTMLParser
import htmlentitydefs
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
from xml.etree import ElementTree
from .iparser import IParser
__all__ = ['HTMLParser']
class HTMLTreeBuilder(_HTMLParser):
def __init__(self, encoding=None)... |
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views import generic
from django.utils import timezone
from polls.models import Choice, Question
class IndexView(generic.ListView):
template_name = 'polls/in... |
'''
Copyright 2012 Will Snook (http://willsnook.com)
Copyright 2015 Chris Kuethe (https://github.com/ckuethe)
MIT License
Utility code for generating antenna geometry files in nec2 card stack format
'''
import math
import copy
# ========================================================================================... |
# Core imports
import time
# Library imports
from mock import patch, MagicMock, PropertyMock
# Package imports
from ..core.USB_Manager import USB_Manager
from ..reconstruction.Buffer import Buffer
from ..zigbee.NTP import NTP
from ..zigbee.RF_Sensor_Physical import RF_Sensor_Physical
from zigbee_rf_sensor import ZigB... |
# -*- coding: utf-8 -*-
"""
XML Test Runner for PyUnit
"""
# Written by Sebastian Rittau <<EMAIL>> and placed in
# the Public Domain. With contributions by Paolo Borelli and others.
from __future__ import unicode_literals
__version__ = "0.2"
import os.path
import re
import sys
import time
import traceback
import u... |
try:
import inspect
except:
try:
from _pydev_imps import _pydev_inspect as inspect
except:
import traceback;traceback.print_exc() #Ok, no inspect available (search will not work)
try:
import re
except:
try:
import sre as re # for older versions
except:
import tr... |
"""Implementation of :class:`QuotientRing` class."""
from sympy.polys.domains.ring import Ring
from sympy.polys.polyerrors import NotReversible, CoercionFailed
from sympy.polys.agca.modules import FreeModuleQuotientRing
# TODO
# - successive quotients (when quotient ideals are implemented)
# - poly rings over quotien... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Ansible module to manage mysql variables
(c) 2013, Balazs Pocze <<EMAIL>>
Certain parts are taken from Mark Theunissen's mysqldb module
This file is part of Ansible
Ansible is free software: you can redistribute it and/or modify
it under the terms of the GNU General Pub... |
import os
import sys
from units.compat import unittest
from ansible.module_utils.hwc_utils import are_different_dicts
class HwcDictComparisonTestCase(unittest.TestCase):
def test_simple_no_difference(self):
value1 = {
'foo': 'bar',
'test': 'original'
}
self.assert... |
from benchmarks import silk_flags
from measurements import rasterize_and_record_micro
import page_sets
from telemetry import benchmark
# RasterizeAndRecord disabled on mac because of crbug.com/350684.
# RasterizeAndRecord disabled on windows because of crbug.com/338057.
@benchmark.Disabled('mac', 'win')
class Rasteri... |
#!/usr/bin/env python
# Python 2/3 compatibility
from __future__ import print_function
import numpy as np
from numpy import pi, sin, cos
import cv2
defaultSize = 512
class TestSceneRender():
def __init__(self, bgImg = None, fgImg = None, deformation = False, noise = 0.0, speed = 0.25, **params):
self... |
import warnings
import sys
import numpy as np
from numpy.testing import *
import unittest
class _GenericTest(object):
def _test_equal(self, a, b):
self._assert_func(a, b)
def _test_not_equal(self, a, b):
try:
self._assert_func(a, b)
passed = True
except Asserti... |
import cv2
import numpy as np
from copy import copy
from ..featurer.hsv_hist import hsv_hist
PARAM_DEFAULT = {
'lower_color_bound': [0.0, 0.0, 0.0],
'upper_color_bound': [255.0, 255.0, 255.0],
'color_channel': [2],
'channel_range': [0, 180],
'bin_nb': [16]
}
def init(cap, param, selection):
l... |
from . import constants
import sys
from .charsetprober import CharSetProber
class CharSetGroupProber(CharSetProber):
def __init__(self):
CharSetProber.__init__(self)
self._mActiveNum = 0
self._mProbers = []
self._mBestGuessProber = None
def reset(self):
... |
from six import BytesIO
from struct import pack, unpack
from thriftpy3.Thrift import TException
class TTransportException(TException):
"""Custom Transport Exception class"""
UNKNOWN = 0
NOT_OPEN = 1
ALREADY_OPEN = 2
TIMED_OUT = 3
END_OF_FILE = 4
def __init__(self, type=UNKNOWN, message=None):
TExc... |
"""
Scraps important semester dates from SVSU registrars calendar webpage
"""
from warnings import warn
from datetime import datetime, timedelta
from string import whitespace
import requests
import bs4
#import unicodedata
from unidecode import unidecode
from dateutil.relativedelta import relativedelta
from daterangepar... |
''' Encapsulate handling of all Bokeh Protocol messages a Bokeh server may
receive.
'''
#-----------------------------------------------------------------------------
# Boilerplate
#-----------------------------------------------------------------------------
import logging # isort:skip
log = logging.getLogger(__name... |
import json, os, sys
from collections import defaultdict
import traceback
import statistics
def addValue(root, chain, filetype, value):
for parser in chain:
if parser not in root:
root[parser] = {'fileType' : defaultdict(list)}
root = root[parser]
root['fileType'][filetype].ap... |
"""Get nova cores quotas."""
import click
from monitorstack import utils
from monitorstack.cli import pass_context
from monitorstack.utils import os_utils as ost
DOC = """Get nova cores quotas."""
COMMAND_NAME = 'os_vm_quota_cores'
@click.command(COMMAND_NAME, short_help=DOC)
@click.option('--config-file',
... |
def main():
n_translations, n_pairs = [int(x) for x in input().split()]
translations = {}
for i in range(26):
translations.update({chr(i+97):[]})
for i in range(n_translations):
fr, to = input().split()
translations.get(fr).append(to)
for i in range(n_pairs):
w_a, ... |
# ICE Revision: $Id$
"""Parse options for the PyFoam-Scripts"""
from optparse import OptionParser,TitledHelpFormatter
import textwrap
from PyFoam import versionString
from PyFoam.FoamInformation import changeFoamVersion
from PyFoam.FoamInformation import oldAppConvention as oldApp
from PyFoam.Error import error,wa... |
import mock
from nova import objects
from nova.scheduler.filters import aggregate_image_properties_isolation as aipi
from nova import test
from nova.tests.unit.scheduler import fakes
@mock.patch('nova.scheduler.filters.utils.aggregate_metadata_get_by_host')
class TestAggImagePropsIsolationFilter(test.NoDBTestCase):
... |
import logging
import sdl2
import sdl2.ext
import select
import sys
import argparse as ap
from slowboy.mmu import MMU
from slowboy.z80 import Z80, State
from slowboy.gpu import SCREEN_WIDTH, SCREEN_HEIGHT, VRAM_START, OAM_START, BACKGROUND_SIZE
from slowboy.util import hexdump, print_lines
class HeadlessUI():
de... |
"""
TestOptionElement is responsible for a block of option. Used by
TestquestionElement.
"""
import logging
from exe.webui import common
from exe.webui.element import TextAreaElement
log = logging.getLogger(__name__)
# ===========================================================================
class TestoptionEleme... |
from subprocess import Popen, PIPE, STDOUT
import numpy as np
SZ = [2, 3, 4, 8, 12, 15, 16, 17, 32, 64, 128, 256, 512, 1024]
def gen_data(dt):
arrays = {}
if dt == np.float128:
pg = './fftw_longdouble'
elif dt == np.double:
pg = './fftw_double'
elif dt == np.float32:
pg = '.... |
# -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Nicole Thomas <<EMAIL>>`
'''
# Import python libs
from __future__ import absolute_import
import logging
# Import Salt Testing Libs
from salttesting import TestCase, skipIf
from salttesting.helpers import ensure_in_syspath
from salttesting.mock import (
MagicMoc... |
# This tests the internal _objects attribute
import unittest
from ctypes import *
from sys import getrefcount as grc
# XXX This test must be reviewed for correctness!!!
"""
ctypes' types are container types.
They have an internal memory block, which only consists of some bytes,
but it has to keep references to other... |
from __future__ import (absolute_import, division, print_function)
from six.moves import (filter, input, map, range, zip) # noqa
from datetime import datetime
import os
import os.path
HEADER = \
'''# (C) British Crown Copyright 2013 - {}, Met Office
#
# This file is part of Iris.
#
# Iris is free software: you c... |
import datetime
import json
import webob
from nova.api.openstack import compute as compute_api
from nova import compute
from nova import context
from nova import exception
from nova import flags
from nova.scheduler import rpcapi as scheduler_rpcapi
from nova import test
from nova.tests.api.openstack import fakes
from... |
from __future__ import unicode_literals
import json
import re
from .common import InfoExtractor
_translation_table = {
'a': 'h', 'd': 'e', 'e': 'v', 'f': 'o', 'g': 'f', 'i': 'd', 'l': 'n',
'm': 'a', 'n': 'm', 'p': 'u', 'q': 't', 'r': 's', 'v': 'p', 'x': 'r',
'y': 'l', 'z': 'i',
'$': ':', '&': '.', '... |
#!/usr/bin/python
import sys
import os
sys.path.append('..')
sys.path.append('lib_gb.')
import platform
from commons.utils import root_path
from PyQt4 import QtGui, QtCore
from gui.mainWindow import *
from time import time, sleep
from PyQt4.QtGui import QApplication, QSplashScreen, QPixmap
from PyQt4.QtC... |
import time
import unittest
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoSuchFrameException
from selenium.common.exceptions import TimeoutException
from selenium.common.exceptions import StaleElementReferenceException
from selenium... |
'''
Created on Oct 31, 2013
@author: uli
'''
import archas, os, tempfile, subprocess, shlex
def _getTimeLapseFiles(lapseDir, startTimeS, rangeBackS):
stopTimeS = startTimeS - rangeBackS
files = []
for filename in os.listdir (lapseDir):
if filename.lower().endswith(".jpg"):
filePath = ... |
import pandas as pd
import pytest
import pytz
from qstrader.system.rebalance.weekly import WeeklyRebalance
@pytest.mark.parametrize(
"start_date,end_date,weekday,pre_market,expected_dates,expected_time",
[
(
'2020-03-11', '2020-05-17', 'MON', False, [
'2020-03-16', '2020-0... |
"""My notes to remember decorators."""
VALIDUSER = "aldenso"
NOTVALIDUSER = "nobody"
def upperme(func):
"""Deco to change the output to uppercase."""
def applyupper(name):
return "{}".format(func(name).upper())
return applyupper
def tagme(tag):
"""Deco to wrap the output with some string."""... |
#! /usr/bin/env python
# $Header$
import sys
try:
from setuptools import setup
hasSetuptools = True
except ImportError:
from distutils.core import setup
hasSetuptools = False
_url = "http://pywebsvcs.sf.net/"
import ConfigParser
cf = ConfigParser.ConfigParser()
cf.read('setup.cfg')
major = cf.getint('... |
import re
import time
from openerp import tools
from openerp.osv import fields, osv
from openerp.tools import float_round, float_is_zero, float_compare
from openerp.tools.translate import _
CURRENCY_DISPLAY_PATTERN = re.compile(r'(\w+)\s*(?:\((.*)\))?')
class res_currency(osv.osv):
def _current_rate(self, cr, ui... |
from django.conf.urls import patterns, url
from django.views.generic import TemplateView
js_info_dict = {
'packages': ('geonode.maps',),
}
urlpatterns = patterns('geonode.maps.views',
url(r'^$', TemplateView.as_view(template_name='maps/map_list.html'), name='maps_browse'),
... |
from __future__ import unicode_literals
# The *_FORMAT strings use the Django date format syntax,
# see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = 'j F Y' # '20 januari 2009'
TIME_FORMAT = 'H:i' # '15:23'
DATETIME_FORMAT = 'j F Y H:i' ... |
from spack import *
class Sparsehash(AutotoolsPackage):
"""Sparse and dense hash-tables for C++ by Google"""
homepage = "https://github.com/sparsehash/sparsehash"
url = "https://github.com/sparsehash/sparsehash/archive/sparsehash-2.0.3.tar.gz"
version('2.0.3', 'd8d5e2538c1c25577b3f066d7a55e99e') |
import decimal
import pint
from horizon.utils import functions
# Mapping of units from Ceilometer to Pint
INFORMATION_UNITS = (
('B', 'byte'),
('KB', 'Kibyte'),
('MB', 'Mibyte'),
('GB', 'Gibyte'),
('TB', 'Tibyte'),
('PB', 'Pibyte'),
('EB', 'Eibyte'),
)
TIME_UNITS = ('ns', 's', 'min', 'hr... |
from django.test import RequestFactory
from bedrock.mozorg.tests import TestCase
from bedrock.redirects.middleware import RedirectsMiddleware
from bedrock.redirects.util import get_resolver, redirect
patterns = [
redirect(r'^dude/already/10th/', '/far/out/'),
redirect(r'^walter/prior/restraint/', '/finishes/... |
import numpy as np
def test_elastic_FE_simulation_3D():
from pymks.datasets.elastic_FE_simulation import ElasticFESimulation
nx = 5
ii = (nx - 1) / 2
X = np.zeros((1, nx, nx, nx), dtype=int)
X[0, :, ii] = 1
model = ElasticFESimulation(elastic_modulus=(1., 10.),
... |
import numpy as np
from math import sin, cos, acos
from cmath import exp as cexp, phase as arg
from mathutils import Vector, Matrix
from sverchok.utils.curve.core import SvCurve
from sverchok.utils.curve.primitives import SvCircle
from sverchok.utils.curve.algorithms import SvConcatCurve, concatenate_curves
class Sv... |
import tarfile
import time
import os
import json
class BackupTool(object):
"""Simple backup utility."""
def __init__(self):
pass
@staticmethod
def backup(openbazaar_installation_path,
backup_folder_path,
on_success_callback=None,
on_error_callback... |
#! /usr/bin/env python
# findlinksto
#
# find symbolic links to a path matching a regular expression
import os
import sys
import re
import getopt
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], '')
if len(args) < 2:
raise getopt.GetoptError('not enough arguments', None)
... |
"""Script that is used by PRESUBMIT.py to run style checks on Java files."""
import os
import subprocess
def RunCheckstyle(input_api, output_api, style_file):
if not os.path.exists(style_file):
file_error = (' Java checkstyle configuration file is missing: '
+ style_file)
return [output_... |
# -*- coding:utf-8 -*-
"""
上海银行间同业拆放利率(Shibor)数据接口
Created on 2014/07/31
@author: Jimmy Liu
@group : waditu
@contact: <EMAIL>
"""
import pandas as pd
import numpy as np
from tushare.stock import cons as ct
from tushare.util import dateu as du
def shibor_data(year=None):
"""
获取上海银行间同业拆放利率(Shibor)
Parameters... |
#! /usr/bin/env python
import argparse as ap
import glob
from astropy.table import Table
from astropy.table import Column
from astropy.io import ascii
import numpy as np
import os
import time
def listdir_fullpath(d):
return [os.path.join(d, f) for f in os.listdir(d)]
def get_row(file_path):
summary = open(fil... |
'''
Copyright 2011 Google Inc.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
'''
import fnmatch
import os
import re
import subprocess
import threading
PROPERTY_MIMETYPE = 'svn:mime-type'
# Status types for GetFilesWithStatus()
STATUS_ADDED = 0x01
S... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
from setuptools import setup, find_packages
version = __import__('shop_wspay').__version__
readme = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
setup(
name='django-shop-wspay',
version=vers... |
"""This file contains different utils and fixtures."""
import os
import pytest
class Scope(dict): # noqa: WPS600
"""This class emulates `globals()`, but does not share state in tests."""
def __init__(self, *args, **kwargs):
"""Adding `__file__` to make things work in `tools.py`."""
super()... |
import os
import unittest
import sys
import IECore
class TestPDCWriter( unittest.TestCase ) :
def testBasics( self ) :
r = IECore.Reader.create( "test/IECore/data/pdcFiles/particleShape1.250.pdc" )
p = r.read()
w = IECore.Writer.create( p, "test/particleShape1.250.pdc" )
w.write()
r = IECore.Reader.crea... |
import mxnet as mx
import os, sys
from collections import namedtuple
ConvExecutor = namedtuple('ConvExecutor', ['executor', 'data', 'data_grad', 'style', 'content', 'arg_dict'])
def get_vgg_symbol(prefix, content_only=False):
# declare symbol
data = mx.sym.Variable("%s_data" % prefix)
conv1_1 = mx.symbol.... |
"""Tests for distutils.command.config."""
import unittest
import os
import sys
from test.test_support import run_unittest
from distutils.command.config import dump_file, config
from distutils.tests import support
from distutils import log
class ConfigTestCase(support.LoggingSilencer,
s... |
import unittest2
import openerp.tests.common as common
class test_search(common.TransactionCase):
def test_00_search_order(self):
registry, cr, uid = self.registry, self.cr, self.uid
# Create 6 partners with a given name, and a given creation order to
# ensure the order of their ID. So... |
import os, re, sys, string
import jsmin
import bz2
def ToCAsciiArray(lines):
result = []
for chr in lines:
value = ord(chr)
assert value < 128
result.append(str(value))
return ", ".join(result)
def ToCArray(lines):
result = []
for chr in lines:
result.append(str(ord(chr)))
return ", ".jo... |
import render
from cStringIO import StringIO
import xml.dom.minidom
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table
from reportlab.lib.units import mm
from reportlab.lib.pagesizes import A4
import reportlab.lib
import copy
class simple(render.render):
def _render(self):
self.r... |
import fnmatch
import os
import pandas as pd
import cPickle as pickle
from scipy import stats
import matplotlib as mpl
import matplotlib.pyplot as plt
from collections import OrderedDict
path = '/Volumes/Seq_data'
result_file_names = ['results_kidney_raw', 'results_liver_raw', 'results_lung_raw']
cell_list =[]
align_d... |
# -*- coding: utf-8 -*-
from openerp.addons.stock.tests.common import TestStockCommon
from openerp.tools import mute_logger, float_round
class TestResupply(TestStockCommon):
def setUp(self):
super(TestResupply, self).setUp()
self.Warehouse = self.env['stock.warehouse']
# create 2 WH, BIG ... |
"""
Ansible inventory script for LXC containers. Requires Python
bindings for LXC API.
In LXC, containers can be grouped by setting the lxc.group option,
which may be found more than once in a container's
configuration. So, we enumerate all containers, fetch their list
of groups, and then build the dictionary in the w... |
from ...utils.tests import base as base
from ...utils.tests import mpi as mpit
# key order: dataset; epsilon; C
__REFERENCE_RESULTS__ = {
"dryrun": {
0.1: {
0.1: {
"accuracy": 1-0.9300,
},
1: {
"accuracy": 1-0.9300,
},
... |
#coding:utf8
"""
proxiex.py
~~~~~~~~~~~~~
该模块包含所有代理服务器列表,提供代理选择功能。
"""
from threadPool import ThreadPool
import requests
#代理服务器列表
proxiex = [
'122.72.112.148:80',
'122.72.112.166:80',
'113.207.124.165:8080',
'222.83.160.45:8080',
'219.130.39.9:3128',
'211.161.152.100:80',
'221.176.14.72:80',
'222.124.147.105:8080... |
#!/usr/bin/env python
# BER encoder
from pyasn1.type import base, tag, univ, char, useful
from pyasn1.codec.ber import eoo
from pyasn1.compat.octets import int2oct, oct2int, ints2octs, null, str2octs
from pyasn1 import debug, error
class Error(Exception): pass
class AbstractItemEncoder:
supportIndefLenMode = 1
... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: bigip_management_route
short_description: Manage system man... |
"""Tests for tensorflow.ctc_ops.ctc_loss_op."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import itertools
import numpy as np
from six.moves import zip_longest
from tensorflow.python.framework import errors
from tensorflow.python.framework import op... |
from oslo_utils import uuidutils
from nova.objects import keypair as keypair_obj
from nova.tests.functional.api_sample_tests import api_sample_base
from nova.tests.unit import fake_crypto
from nova.tests import uuidsentinel as uuids
class KeyPairsSampleJsonTest(api_sample_base.ApiSampleTestBaseV21):
microversion... |
""" E-Commerce API client """
import json
import logging
from django.conf import settings
import jwt
import requests
from requests import Timeout
from rest_framework.status import HTTP_200_OK
from commerce.exceptions import InvalidResponseError, TimeoutError, InvalidConfigurationError
log = logging.getLogger(__nam... |
import libtorrent as lt
from core.util import Utility, SafeQueue
from core.data_producer import DataProducer
from core.exceptions import TorrentListFullException
import logging
import os
class Session(lt.session):
"""
This class represents the main core structure. It is a little "addition"
to libtorrent's... |
from sources import *
from utils import *
import string, re
#
# Regular expressions to detect code sequences. `Code sequences' are simply
# code fragments embedded in '{' and '}', as demonstrated in the following
# example.
#
# {
# x = y + z;
# if ( zookoo == 2 )
# {
# foobar();
# }
# }
... |
from paddle.fluid.optimizer import Optimizer
__all__ = []
class MetaOptimizerBase(Optimizer):
def __init__(self, optimizer):
self.inner_opt = optimizer
self._learning_rate = self.inner_opt._learning_rate
self._learning_rate_map = self.inner_opt._learning_rate_map
self.meta_optimiz... |
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""This module contains Trait classes that we've pulled from the
traits source and fixed due to various bugs. File and Directory are
redefined as the release version had dependencies on TraitsUI, which
we ... |
import os
import shutil
from types import FileType
from jinja2 import Environment, FileSystemLoader
from typedecorator import params, returns
from parser import ClassParser, MethodDoc
import glob
import time
@returns([(str, FileType)])
@params(search_path=str)
def find_class_files(search_path):
"""Find and open a... |
"""
Death Streams Addon
Copyright (C) 2017 Mr.Blamo
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
... |
import os
import unittest
import platform
from test.test_support import TESTFN
def can_symlink():
# cache the result in can_symlink.prev_val
prev_val = getattr(can_symlink, 'prev_val', None)
if prev_val is not None:
return prev_val
symlink_path = TESTFN + "can_symlink"
try:
symlink... |
import os, urllib, logging, datetime, re
from _numbertogp import NumberToGp
from models.ipinfo import IpInfo
from models.order import Order
from models.agent import Agent
from models.promo import Promo
from models.manualpaorder import ManualPaOrder
from models.customer import Customer
from models.stockaccount imp... |
# Install and register pythonxx_d.dll, pywintypesxx_d.dll and pythoncomxx_d.dll
#
# Assumes the _d files can be found in the same directory as this script
# or in the cwd.
import win32api
import _winreg
import sys
import shutil
import os
def usage_and_die(rc):
print
print "This script is designed to copy and ... |
data = (
'ggwem', # 0x00
'ggweb', # 0x01
'ggwebs', # 0x02
'ggwes', # 0x03
'ggwess', # 0x04
'ggweng', # 0x05
'ggwej', # 0x06
'ggwec', # 0x07
'ggwek', # 0x08
'ggwet', # 0x09
'ggwep', # 0x0a
'ggweh', # 0x0b
'ggwi', # 0x0c
'ggwig', # 0x0d
'ggwigg', # 0x0e
'ggwigs', # 0x0f
'gg... |
from test import test_support
import random
import sys
import unittest
verbose = test_support.verbose
nerrors = 0
def check(tag, expected, raw, compare=None):
global nerrors
if verbose:
print " checking", tag
orig = raw[:] # save input in case of error
if compare:
raw.sort(compa... |
import json
from proboscis import SkipTest
from trove.tests.config import CONFIG
from trove.tests.scenario.helpers.test_helper import DataType
from trove.tests.scenario.runners.test_runners import CheckInstance
from trove.tests.scenario.runners.test_runners import InstanceTestInfo
from trove.tests.scenario.runners.te... |
import mock
import uuid
from oslo_policy import policy as oslo_policy
from oslo_serialization import jsonutils
from oslo_utils import timeutils
from six.moves import http_client
import webob
from cinder.api.contrib import volume_image_metadata
from cinder import context
from cinder import db
from cinder import except... |
#coding:utf-8
import unittest2 as unittest
from cactus import ui, Site
from cactus.tests import BaseTestCase
class UITestCase(unittest.TestCase):
def test_coerce_yes_no(self):
self.assertEqual(True, ui._yes_no_coerce_fn("y"))
self.assertEqual(True, ui._yes_no_coerce_fn("Y"))
self.assert... |
"""
Tests for pagination template tags and filters.
"""
from mock import Mock
from django import template
from tests import case
class PaginateTest(case.DBTestCase):
"""Tests for paginate template tag."""
def test_paginate(self):
"""Places Pager object in context with size/num from request."""
... |
import requests
from allauth.socialaccount.providers.globus.provider import GlobusProvider
from allauth.socialaccount.providers.oauth2.views import (
OAuth2Adapter,
OAuth2CallbackView,
OAuth2LoginView,
)
class GlobusAdapter(OAuth2Adapter):
provider_id = GlobusProvider.id
provider_default_url = 'h... |
import sys
import gc
import uos as os
import uerrno as errno
import ujson as json
import uzlib
import upip_utarfile as tarfile
gc.collect()
debug = False
install_path = None
cleanup_files = []
gzdict_sz = 16 + 15
file_buf = bytearray(512)
class NotFoundError(Exception):
pass
def op_split(path):
if path == ... |
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
long_desc = '''
This package contains the phpdomain Sphinx extension.
This extension provides a PHP domain for sphinx
'''
requires = ['Sphinx>=1.0']
setup(
name='sphinxcontrib-phpdomain',
version='0.1.4',
url='http://bitbucket.org/mar... |
import time
import m3.rt_proxy as m3p
import m3.toolbox as m3t
import m3.component_factory as m3f
import os
import sys
import yaml
import m3.trajectory as m3jt
import numpy as nu
import m3.gui as m3g
import m3.toolbox as m3t
import m3.viz as m3v
# #####################################################
def load_vias():
... |
import sys, os
from os.path import exists
from time import sleep
from os import remove
usage = '''dhcpd_edithosts.py mac ip hostname dns gateway nextserver'''
conf_path = "/etc/dhcpd.conf"
file_lock = "/etc/dhcpd.conf_locked"
sleep_max = 20
host_entry = 'host %s { hardware ethernet %s; fixed-address %s; option domain-... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.