code stringlengths 1 199k |
|---|
from django.db.models.loading import get_apps, get_models
from django.contrib.auth import get_permission_codename
PERMISSIONS_LIST = None
def get_permission_choices():
"""
Rather than creating permissions in the datastore which is incredibly slow (and relational)
we just use the permission codenames... |
from __future__ import absolute_import
from sentry.stacktraces import find_stacktraces_in_data
def test_stacktraces_basics():
data = {
'message': 'hello',
'platform': 'javascript',
'sentry.interfaces.Stacktrace': {
'frames': [
{
'abs_path': 'ht... |
from __future__ import print_function
import os
import sys
import Queue
import shutil
import platform
import tempfile
import warnings
import threading
import subprocess
try:
import multiprocessing as mp
multiprocessing_imported = True
except ImportError:
multiprocessing_imported = False
import numpy
import ... |
import skrf as rf
import unittest
import os
import numpy as np
class DeembeddingTestCase(unittest.TestCase):
"""
Testcase for the Deembedding class
Pseudo-netlists for s-parameter files used in these tests
For open-short, open and short de-embedding:
- deemb_ind.s2p
P1 (1 0) port
... |
"""Default variable filters."""
import random as random_module
import re
import types
from decimal import ROUND_HALF_UP, Context, Decimal, InvalidOperation
from functools import wraps
from operator import itemgetter
from pprint import pformat
from urllib.parse import quote
from django.utils import formats
from django.u... |
from __future__ import absolute_import
import os
import site
import sys
_has_setup_vendor_path = False
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
def path(*a):
return os.path.join(BASE_DIR, *a)
def setup_vendor_path():
"""Sets up path and vendor/ stuff"""
global _has_setup_vendor... |
import pytest
import sys
with pytest.suppress(ImportError):
import numpy as np
def test_vector_int():
from pybind11_tests import VectorInt
v_int = VectorInt([0, 0])
assert len(v_int) == 2
assert bool(v_int) is True
v_int2 = VectorInt([0, 0])
assert v_int == v_int2
v_int2[1] = 1
asser... |
"""Apple's Speedometer 2 performance benchmark.
"""
import os
import re
from benchmarks import press
from core import path_util
from telemetry import benchmark
from telemetry import story
from telemetry.timeline import chrome_trace_category_filter
from telemetry.web_perf import timeline_based_measurement
from page_sets... |
"""Gradient Boosted Regression Trees
This module contains methods for fitting gradient boosted regression trees for
both classification and regression.
The module structure is the following:
- The ``BaseGradientBoosting`` base class implements a common ``fit`` method
for all the estimators in the module. Regression a... |
"""
Unit tests for optimization routines from optimize.py and tnc.py
Authors:
Ed Schofield, Nov 2005
Andrew Straw, April 2008
To run it in its simplest form::
nosetests test_optimize.py
"""
from numpy.testing import assert_raises, assert_almost_equal, \
assert_equal, assert_, TestCase, run_module_suite
... |
from test_framework import BitcreditTestFramework
from bitcreditrpc.authproxy import AuthServiceProxy, JSONRPCException
from util import *
def check_array_result(object_array, to_match, expected):
"""
Pass in array of JSON objects, a dictionary with key/value pairs
to match against, and another dictionary w... |
import logging
import traceback
from helpers.cache_clearer import CacheClearer
from helpers.event_helper import EventHelper
from helpers.manipulator_base import ManipulatorBase
from helpers.notification_helper import NotificationHelper
class EventManipulator(ManipulatorBase):
"""
Handle Event database writes.
... |
import warnings
from django.contrib import admin
from django.contrib.sites.models import Site
from django.conf import settings
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from django.contrib.admin.widgets import FilteredSelectMultiple
from opps.core.permissions.admin import... |
"""
Landlab component for overland flow using the kinematic-wave approximation.
Created on Fri May 27 14:26:13 2016
@author: gtucker
"""
from landlab import Component
import numpy as np
class KinwaveOverlandFlowModel(Component):
"""
Calculate water flow over topography.
Landlab component that implements a t... |
__author__ = 'nicking' |
"""Test RPCs related to blockchainstate.
Test the following RPCs:
- gettxoutsetinfo
- getdifficulty
- getbestblockhash
- getblockhash
- getblockheader
- getchaintxstats
- getnetworkhashps
- verifychain
Tests correspond to code in rpc/blockchain.cpp.
"""
from decimal import Decimal
import... |
"""QGIS Unit tests for QgsLabelLineSettings
.. note:: 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 2 of the License, or
(at your option) any later version.
"""
__author__ = 'Nyall Da... |
'''
.. moduleauthor:: Ignacio Vazquez-Abrams <ivazquez@fedoraproject.org>
.. moduleauthor:: Toshio Kuratomi <toshio@fedoraproject.org>
'''
import threading
from fedora.client import FasProxyClient
from django.conf import settings
connection = None
if not connection:
connection = FasProxyClient(
base_url=set... |
from flask import flash as _flash, get_flashed_messages
class Flash(object):
def __call__(self, errors, category):
if not isinstance(errors, list):
errors = [errors]
for msg in errors:
_flash(msg, category)
def render(self):
messages = get_flashed_messages(with_ca... |
import unittest
from webkitpy.common.thread.threadedmessagequeue import ThreadedMessageQueue
class ThreadedMessageQueueTest(unittest.TestCase):
def test_basic(self):
queue = ThreadedMessageQueue()
queue.post("Hello")
queue.post("There")
(messages, is_running) = queue.take_all()
... |
from datetime import datetime
import unittest, uuid
from urllib import urlencode
import transaction
from webob import Response
from webob.multidict import MultiDict
from repoze.bfg.testing import (
DummyModel,
DummyRequest,
cleanUp,
registerUtility,
)
from repoze.folder import Folder
from testfixtur... |
import ctypes
from winui.defs import FILE_SHARE_READ, FILE_SHARE_WRITE, GENERIC_READ, OPEN_EXISTING
IOCTL_STORAGE_EJECT_MEDIA = 0x2D4808
def eject_cd(cd_path):
#platform specific
if not cd_path:
return
create_file = ctypes.windll.kernel32.CreateFileA
cd_handle = create_file(
"\\\\.\\%s" ... |
__all__ = ["BZ1014545_TestCase"]
from . import TestCase, TestCaseComponent
from blivet.size import Size
from pykickstart.errors import KickstartParseError
class BTRFSOnNonBTRFSComponent(TestCaseComponent):
name = "BTRFSOnNonBTRFS"
def __init__(self, *args, **kwargs):
TestCaseComponent.__init__(self, *ar... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'network'}
DOCUMENTATION = '''
---
module: nxos_install_os
extends_documentation_fragment: nxos
short_description: Set boot options like boot, kickstart image and issu.
description:
- Instal... |
from __future__ import with_statement
__license__ = 'GPL v3'
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import sys, os, shutil, plistlib, subprocess, glob, zipfile, tempfile, \
py_compile, stat, operator
abspath, join, basename = os.path.abspath, os.path.join,... |
"""
Tests for the csv export functionality
TODO: Check that when you add or update a decision it is reflected in the output.
"""
from open_consent_test_case import EconsensusFixtureTestCase
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from organizations.models import Organiza... |
import numpy as np
from cvxpy import *
import math
A = np.array(np.mat('-1 -1 0 0 0;\
0 1 -1 -1 0;\
0 0 0 1 1'))
I = Variable(5)
I_entr = Variable(2)
f_0 = -entr(I_entr[0])-I[2] - 26.0 * log(I[2])
f_0 += -entr(I_entr[1])-I[3] - 26.0 * log(I[3])
constraints = []
constraints = [I_entr[0] == I[2] - 26.0, I_entr[1] == I... |
import uuid
from openstack.network.v2 import agent
from openstack.tests.functional import base
class TestAgent(base.BaseFunctionalTest):
AGENT = None
DESC = 'test description'
def validate_uuid(self, s):
try:
uuid.UUID(s)
except Exception:
return False
return ... |
from django.utils.translation import gettext as _
from apiplayground import APIPlayground
class SubscriberAPIPlayground(APIPlayground):
schema = {
"title": _("subscriber"),
"base_url": "http://localhost/api/v1/",
"resources": [
{
"name": "/subscriber/",
... |
import time
from report import report_sxw
import datetime
import pooler
class folio_report(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context):
super(folio_report, self).__init__(cr, uid, name, context)
self.localcontext.update( {
'time': time,
'get_data': self.... |
import sys
from resources.datatables import Options
def setup(core, object):
object.setAttachment('radial_filename', 'object/conversation');
object.setAttachment('conversationFile','junk_dealer')
object.setOptionsBitmask(Options.CONVERSABLE | Options.INVULNERABLE)
object.setStfFilename('mob/creature_names')
object... |
"""
Running or runtime configuration base classes.
"""
from abc import ABCMeta
from abc import abstractmethod
import functools
import numbers
import logging
import uuid
import six
from ryu.services.protocols.bgp.base import add_bgp_error_metadata
from ryu.services.protocols.bgp.base import BGPSException
from ryu.servi... |
from tempest_lib.common.utils import data_utils
from tempest.api.object_storage import base
from tempest import test
class ContainerTest(base.BaseObjectTest):
def setUp(self):
super(ContainerTest, self).setUp()
self.containers = []
def tearDown(self):
self.delete_containers(self.containe... |
'''
Created on May 28, 2010
@author: jnaous
'''
import models
from django.contrib import admin
admin.site.register(models.ExpedientPermission)
admin.site.register(models.ObjectPermission)
admin.site.register(models.PermissionOwnership)
admin.site.register(models.Permittee) |
"""Optimizer that implements cross-shard gradient reduction for TPU."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import ops
from tensorflow.python.ops.losses import losses
from tensorflow.python.platform import tf_loggi... |
from __future__ import absolute_import
import time
from psycopg2.extensions import cursor, connection
def wrapper_execute(self, action, sql, params=()):
start = time.time()
try:
return action(sql, params)
finally:
stop = time.time()
duration = stop - start
self.connection.que... |
import errno
import os
import re
from lxml import etree
from oslo.config import cfg
from oslo_concurrency import processutils
from nova.compute import arch
from nova.i18n import _
from nova.i18n import _LI
from nova.i18n import _LW
from nova.openstack.common import log as logging
from nova import utils
from nova.virt i... |
"""This example deletes custom targeting values for a given custom targeting
key.
To determine which custom targeting keys and values exist, run
get_all_custom_targeting_keys_and_values.py.
The LoadFromStorage method is pulling credentials and properties from a
"googleads.yaml" file. By default, it looks for this file ... |
import six
from sahara import exceptions as ex
from sahara.i18n import _
def check_tenant_for_delete(context, object):
if object.tenant_id != context.tenant_id:
raise ex.DeletionFailed(
_("{object} with id '{id}' could not be deleted because "
"it wasn't created in this tenant").fo... |
import os
import tempfile
import yaml
from oslo_utils import netutils
from trove.common import cfg
from trove.common import utils
from trove.common import exception
from trove.common import instance as rd_instance
from trove.guestagent.datastore.experimental.cassandra import system
from trove.guestagent.datastore impor... |
"""Implements the graph generation for computation of gradients."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.eager import function
from tensorflow.python.eager.backprop import GradientTape
from tensorflow.python.ops.custom_gradie... |
"""The tests for the Met Office sensor component."""
import json
from unittest.mock import patch
from homeassistant.components.metoffice.const import ATTRIBUTION, DOMAIN
from homeassistant.helpers.device_registry import async_get as get_dev_reg
from . import NewDateTime
from .const import (
DEVICE_KEY_KINGSLYNN,
... |
"""Example for using the Google Search Analytics API (part of Search Console API).
A basic python command-line example that uses the searchAnalytics.query method
of the Google Search Console API. This example demonstrates how to query Google
search results data for your property. Learn more at
https://developers.google... |
__author__ = 'arobres'
from collections import deque
from bottle import run, Bottle, request, response
from configuration import MOCK_IP, MOCK_PORT
from commons.constants import MOCK_NOTIFICATION, MOCK_RESET_ERRORS,\
MOCK_RESET_STATS, MOCK_RESPONSE_SAVE, MOCK_SCALE_DOWN, \
MOCK_SCALE_UP, MOCK_STATS, MOCK_NUM_NO... |
"""oAuthlib request validator."""
import six
from keystone.common import dependency
from keystone.contrib.oauth1 import core as oauth1
from keystone import exception
from keystone.openstack.common import log
METHOD_NAME = 'oauth_validator'
LOG = log.getLogger(__name__)
@dependency.requires('oauth_api')
class OAuthValid... |
"""Support for Pilight binary sensors."""
import datetime
import voluptuous as vol
from homeassistant.components import pilight
from homeassistant.components.binary_sensor import PLATFORM_SCHEMA, BinarySensorEntity
from homeassistant.const import (
CONF_DISARM_AFTER_TRIGGER,
CONF_NAME,
CONF_PAYLOAD,
CON... |
from math import tanh
from pysqlite2 import dbapi2 as sqlite
def dtanh(y):
return 1.0-y*y
class searchnet:
def __init__(self,dbname):
self.con=sqlite.connect(dbname)
def __del__(self):
self.con.close()
def maketables(self):
self.con.execute('create table hiddennode(create_key)')
... |
from datetime import datetime
from twisted.internet import task, reactor
from traceback import print_exc, format_list, extract_stack
from sys import stdout
class Timeout(object):
_task = None
_ticks_left = None
_timeout_callback = None
def __init__(self, timeout_callback, interval, ticks = 1, *callback_... |
import logging
from django.conf import settings
from django.utils.translation import ugettext as _
from cache_nuggets.lib import Message
from post_request_task.task import task
from mkt.files.helpers import FileViewer
from mkt.files.models import File
task_log = logging.getLogger('z.task')
@task
def extract_file(file_i... |
import unittest
from webkitpy.common.system.outputcapture import OutputCapture
from webkitpy.common.config.ports import DeprecatedPort
from webkitpy.tool.mocktool import MockOptions, MockTool
from webkitpy.tool import steps
class StepsTest(unittest.TestCase):
def _step_options(self):
options = MockOptions()... |
import csv
import json
import os
import urlparse
from telemetry.page import page as page_module
from telemetry.page import page_set_archive_info
class PageSet(object):
def __init__(self, file_path='', attributes=None):
self.description = ''
self.archive_data_file = ''
self.file_path = file_path
self.c... |
from astropy.utils.tests.test_metadata import MetaBaseTest
import gc
import sys
import copy
from io import StringIO
from collections import OrderedDict
import pickle
import pytest
import numpy as np
from numpy.testing import assert_allclose, assert_array_equal
from astropy.io import fits
from astropy.table import (Tabl... |
from __future__ import absolute_import
from sentry.models import OrganizationOption
from sentry.testutils import TestCase
class OrganizationOptionManagerTest(TestCase):
def test_set_value(self):
OrganizationOption.objects.set_value(self.organization, 'foo', 'bar')
assert OrganizationOption.objects.g... |
r"""
Regression detection in ASV is based on detecting stepwise changes in
the graphs. The assumptions on the data are as follows: the curves are
piecewise constant plus random noise. We don't know the variance of
the noise nor the scaling of the data, but we assume the noise
amplitude is constant in time.
Luckily, ste... |
"""
sphinx.addnodes
~~~~~~~~~~~~~~~
Additional docutils nodes.
:copyright: Copyright 2007-2015 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from docutils import nodes
class toctree(nodes.General, nodes.Element):
"""Node for inserting a "TOC tree"."""
class desc(no... |
default_app_config = "openslides.core.apps.CoreAppConfig" |
# --------------------------------------------------------------------------
import unittest
import subprocess
import sys
import isodate
import tempfile
import json
from datetime import date, datetime, timedelta
import os
from os.path import dirname, pardir, join, realpath, sep, pardir
cwd = dirname(realpath(__file__)... |
"""
pygments.lexers.webmisc
~~~~~~~~~~~~~~~~~~~~~~~
Lexers for misc. web stuff.
:copyright: Copyright 2006-2017 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer import RegexLexer, ExtendedRegexLexer, include, bygroups, \
default, using
... |
from xmlrpc.client import SafeTransport, ServerProxy
import ssl
class VerifyCertSafeTransport(SafeTransport):
def __init__(self, cafile, certfile=None, keyfile=None):
super().__init__()
self._ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
self._ssl_context.load_verify_locations(cafile)
... |
""" Creates a html sniplet foor hypermail directories. v%(version)s
Takes one directory name as argument, writes will create snipplet in
current directory, only if the overviewfile has changed after the snipplet.
USAGE %(progname)s directory_with_path number
"number" speficies how many directory levels of the path shou... |
from ...utils.pascal_voc_clean_xml import pascal_voc_clean_xml
from numpy.random import permutation as perm
from ..yolo.predict import preprocess
from ..yolo.data import shuffle
from copy import deepcopy
import pickle
import numpy as np
import os
def _batch(self, chunk):
"""
Takes a chunk of parsed annotations
... |
"""
MBTiles provider for MapView
============================
This provider is based on .mbfiles from MapBox.
See: http://mbtiles.org/
"""
__all__ = ["MBTilesMapSource"]
from mapview.source import MapSource
from mapview.downloader import Downloader
from kivy.core.image import Image as CoreImage, ImageLoader
import thre... |
"""
Unit tests for handling email sending errors
"""
import json
from itertools import cycle
from smtplib import SMTPConnectError, SMTPDataError, SMTPServerDisconnected
import ddt
from celery.states import RETRY, SUCCESS
from django.conf import settings
from django.core.management import call_command
from django.db imp... |
""" Services to expose the Teams API to XBlocks """
from django.urls import reverse
class TeamsService(object):
""" Functions to provide teams functionality to XBlocks"""
def get_team(self, user, course_id, topic_id):
from . import api
return api.get_team_for_user_course_topic(user, course_id, t... |
from . import model
from . import wizard |
import hashlib
import json
import logging
import requests
import six
log = logging.getLogger(__name__)
dateformat = '%Y%m%d%H%M%S'
XQUEUE_METRIC_NAME = 'edxapp.xqueue'
XQUEUE_TIMEOUT = 35 # seconds
CONNECT_TIMEOUT = 3.05 # seconds
READ_TIMEOUT = 10 # seconds
def make_hashkey(seed):
"""
Generate a string key ... |
"""
Interpolate OpenType Layout tables (GDEF / GPOS / GSUB).
"""
from fontTools.ttLib import TTFont
from fontTools.varLib import models, VarLibError, load_designspace, load_masters
from fontTools.varLib.merger import InstancerMerger
import os.path
import logging
from copy import deepcopy
from pprint import pformat
log ... |
from nipype.testing import assert_equal
from nipype.interfaces.slicer.quantification.changequantification import IntensityDifferenceMetric
def test_IntensityDifferenceMetric_inputs():
input_map = dict(args=dict(argstr='%s',
),
baselineSegmentationVolume=dict(argstr='%s',
position=-3,
),
baseline... |
import os
import PythonQt
from PythonQt import QtCore, QtGui, QtUiTools
from director.timercallback import TimerCallback
import director.objectmodel as om
from director import lcmUtils
from director import cameraview
from director import vtkAll as vtk
import json
import drc as lcmdrc
CAPTURE_CHANNEL = 'DECKLINK_VIDEO_C... |
from django.conf.urls import include, url
from django.urls import reverse
from django.utils.html import format_html
from django.utils.translation import ugettext as _
import wagtail.admin.rich_text.editors.draftail.features as draftail_features
from wagtail.admin.rich_text import HalloPlugin
from wagtail.core import ho... |
""":func:`~pandas.eval` parsers
"""
import ast
import operator
import sys
import inspect
import tokenize
import datetime
from functools import partial
import pandas as pd
from pandas import compat
from pandas.compat import StringIO, lmap, zip, reduce, string_types
from pandas.core.base import StringMixin
from pandas.co... |
import xbmc, xbmcaddon, xbmcgui, xbmcplugin, os, sys, xbmcvfs, glob
import shutil
import urllib2,urllib
import re
import uservar
import time
try: from sqlite3 import dbapi2 as database
except: from pysqlite2 import dbapi2 as database
from datetime import date, datetime, timedelta
from resources.libs import wizard as... |
import decimal
from unittest import TestCase
import simplejson as S
class TestDecode(TestCase):
def test_decimal(self):
rval = S.loads('1.1', parse_float=decimal.Decimal)
self.assert_(isinstance(rval, decimal.Decimal))
self.assertEquals(rval, decimal.Decimal('1.1'))
def test_float(self):... |
_MIPS_ISA_MIPS1 = 1
_MIPS_ISA_MIPS2 = 2
_MIPS_ISA_MIPS3 = 3
_MIPS_ISA_MIPS4 = 4
_MIPS_SIM_ABI32 = 1
_MIPS_SIM_NABI32 = 2
_MIPS_SIM_ABI64 = 3
P_MYID = (-1)
P_MYHOSTID = (-1)
ONBITSMAJOR = 7
ONBITSMINOR = 8
OMAXMAJ = 0x7f
OMAXMIN = 0xff
NBITSMAJOR = 14
NBITSMINOR = 18
MAXMAJ = 0x1ff
MAXMIN = 0x3ffff
OLDDEV = 0
NEWDEV = 1... |
"""MySQL Connector/Python version information
The file version.py gets installed and is available after installation
as mysql.connector.version.
"""
VERSION = (2, 0, 4, '', 0)
if VERSION[3] and VERSION[4]:
VERSION_TEXT = '{0}.{1}.{2}{3}{4}'.format(*VERSION)
else:
VERSION_TEXT = '{0}.{1}.{2}'.format(*VERSION[0:3... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = '''
inventory: script
version_added: "2.4"
short_description: Executes an inventory script that returns JSON
options:
cache:
description: Toggle the usage of the configured Cache plugin.... |
print 'crap'
def runpix():
x = 1
x = 's'
t = (x,) |
from openerp.osv import orm, fields
from datetime import datetime
from openerp.tools.translate import _
from log import *
class csb_34_01(orm.Model):
_name = 'csb.3401'
_auto = False
def _start_34(self, cr, uid, context):
converter = self.pool.get('payment.converter.spain')
return converter.... |
from __future__ import absolute_import
from ruamel.yaml.error import * # NOQA
from ruamel.yaml.tokens import * # NOQA
from ruamel.yaml.events import * # NOQA
from ruamel.yaml.nodes import * # NOQA
f... |
"""
Baremetal IPMI power manager.
"""
import os
import stat
import tempfile
from oslo.config import cfg
from nova import exception
from nova.openstack.common.gettextutils import _
from nova.openstack.common import log as logging
from nova.openstack.common import loopingcall
from nova import paths
from nova import utils... |
"""Tests for Calibrator."""
from absl.testing import parameterized
import numpy as np
from six.moves import range
from tensorflow.lite.python.optimize import calibrator as _calibrator
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import test_util
from tensorflow.python.platform import ... |
"""Test the zerproc lights."""
from unittest.mock import MagicMock, patch
import pytest
import pyzerproc
from homeassistant import setup
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_COLOR_MODE,
ATTR_HS_COLOR,
ATTR_RGB_COLOR,
ATTR_SUPPORTED_COLOR_MODES,
ATTR_XY_COLOR,
CO... |
from tempest.api.database import base
from tempest.lib import exceptions as lib_exc
from tempest import test
class DatabaseFlavorsNegativeTest(base.BaseDatabaseTest):
@classmethod
def setup_clients(cls):
super(DatabaseFlavorsNegativeTest, cls).setup_clients()
cls.client = cls.database_flavors_cl... |
from __future__ import division
import warnings
import numpy as np
import scipy.sparse as sp
from sklearn.metrics import euclidean_distances
from sklearn.random_projection import (
johnson_lindenstrauss_min_dim,
gaussian_random_matrix,
sparse_random_matrix,
SparseRandomProjection,
GaussianRandomProj... |
from sqlalchemy.test.testing import eq_, assert_raises, \
assert_raises_message
from sqlalchemy.ext import declarative as decl
from sqlalchemy import exc
import sqlalchemy as sa
from sqlalchemy.test import testing
from sqlalchemy import MetaData, Integer, String, ForeignKey, \
ForeignKeyConstraint, asc, Index
f... |
import warnings
from pilkit.processors.crop import *
warnings.warn('imagekit.processors.crop is deprecated use imagekit.processors instead', DeprecationWarning)
__all__ = ['TrimBorderColor', 'Crop', 'SmartCrop'] |
from PySide.QtCore import *
from PySide.QtGui import *
import Queue
import hashlib
from datetime import datetime
import traceback
class AsyncThreads(QObject):
"""
AsyncThreads: A class to generate threads for whenever something can't run in the main process.
"""
def __init__(self, max_threads, debug=Fal... |
"""
werkzeug.exceptions
~~~~~~~~~~~~~~~~~~~
This module implements a number of Python exceptions you can raise from
within your views to trigger a standard non-200 response.
Usage Example
-------------
::
from werkzeug import BaseRequest, responder
from werkzeug.exceptions im... |
"""
Unit tests for nltk.metrics.aline
"""
from __future__ import unicode_literals
import unittest
from nltk.metrics import aline
class TestAline(unittest.TestCase):
"""
Test Aline algorithm for aligning phonetic sequences
"""
def test_aline(self):
result = aline.align('θin', 'tenwis')
ex... |
import os
import matplotlib as mpl
mpl.use('TkAgg')
import pandas as pd;
import numpy as np;
import seaborn as sns
np.set_printoptions(linewidth=200, precision=5, suppress=True)
import pandas as pd;
from matplotlib.backends.backend_pdf import PdfPages
pd.options.display.max_rows = 50;
pd.options.display.expand_frame_re... |
"""
本包包含某些功能的示例使用方法
""" |
from __future__ import unicode_literals
from ..util import get_doc
def test_issue599(en_vocab):
doc = get_doc(en_vocab)
doc.is_tagged = True
doc.is_parsed = True
doc2 = get_doc(doc.vocab)
doc2.from_bytes(doc.to_bytes())
assert doc2.is_parsed |
from autotest_lib.client.common_lib import error
from autotest_lib.client.bin import test
class error_test_error(test.test):
version = 1
def execute(self):
raise error.TestError("This test always causes an error.") |
"""WebLinkback - Web Interface"""
from six import iteritems
from invenio.base.i18n import gettext_set_language
from invenio.ext.legacy.handler import wash_urlargd, WebInterfaceDirectory
from invenio.legacy.webuser import getUid, collect_user_info, page_not_authorized
from invenio.legacy.weblinkback.api import check_use... |
from django import template
from pootle.core.delegate import upstream
register = template.Library()
@register.inclusion_tag('includes/upstream_link.html')
def upstream_link(project):
upstream_provider = None
if project.config.get("pootle.fs.upstream"):
upstream_providers = upstream.gather(project.__clas... |
from random import randint
from odoo import fields, models
class MeetingType(models.Model):
_name = 'calendar.event.type'
_description = 'Event Meeting Type'
def _default_color(self):
return randint(1, 11)
name = fields.Char('Name', required=True)
color = fields.Integer('Color', default=_def... |
'''Autogenerated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
from OpenGL.raw.GL import _types as _cs
from OpenGL.raw.GL._types import *
from OpenGL.raw.GL import _errors
from OpenGL.constant import Constant as _C
import ctypes
_EXTENSION_NAME = 'GL_ARB_tessellation_shader'
def _f( ... |
'''OpenGL extension NV.blend_equation_advanced_coherent
This module customises the behaviour of the
OpenGL.raw.GL.NV.blend_equation_advanced_coherent to provide a more
Python-friendly API
The official definition of this extension is available here:
http://www.opengl.org/registry/specs/NV/blend_equation_advanced_coheren... |
"""Tests for tf.contrib.tensor_forest.ops.finished_nodes_op."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow # pylint: disable=unused-import
from tensorflow.contrib.tensor_forest.python.ops import training_ops
from tensorflow.python.fram... |
"""This file contains unit tests for the merge_manifests script."""
import re
import unittest
import xml.dom.minidom
from tools.android import merge_manifests
FIRST_MANIFEST = """<?xml version='1.0' encoding='utf-8'?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.google.andro... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.