code stringlengths 1 199k |
|---|
from AlgorithmImports import *
class IndexOptionPutITMExpiryRegressionAlgorithm(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2021, 1, 4)
self.SetEndDate(2021, 1, 31)
self.spx = self.AddIndex("SPX", Resolution.Minute).Symbol
# Select a index option expiring ITM, and adds it t... |
from flask.ext.wtf import Form, TextField, Required, PasswordField, BooleanField, ValidationError, validators
from labmanager.babel import gettext, lazy_gettext
class RetrospectiveForm(Form):
def get_field_names(self):
field_names = []
for field in self:
if 'csrf' not in str(type(field))... |
import numpy as np
from numpy.testing import (assert_equal,
assert_almost_equal,
assert_raises)
import skimage
from skimage import data
from skimage._shared._warnings import expected_warnings
from skimage.filters.thresholding import (threshold_adaptive,
... |
from os.path import join
from setuptools import setup, find_packages
import pygithub3
try:
import multiprocessing
import logging
except ImportError:
pass
setup(
name=pygithub3.__name__,
version=pygithub3.__version__,
author=pygithub3.__author__,
author_email=pygithub3.__email__,
url='htt... |
"""Print SBML model species and PySB model species for 1-1 comparison."""
from __future__ import division
import difflib
import re
import argparse
import sys
import rasmodel.chen_2009
import rasmodel.chen_2009.original_sbml
import pysb
from pysb.bng import generate_equations
def get_pysb_species():
"""Return specie... |
try:
from array import array
except ImportError:
import sys
print("SKIP")
sys.exit()
print(array('b', (1, 2)))
print(array('h', [1, 2]))
print(array('h', b'22')) # should be byteorder-neutral
print(array('h', bytearray(2)))
print(array('i', bytearray(4)))
print(array('H', array('b', [1, 2])))
print(arr... |
"""
homeassistant.util
~~~~~~~~~~~~~~~~~~
Helper methods for various modules.
"""
import collections
from itertools import chain
import threading
import queue
from datetime import datetime
import re
import enum
import socket
import random
import string
from functools import wraps
from .dt import datetime_to_local_str, ... |
"""
Generate trace/generated-helpers-wrappers.h.
"""
__author__ = "Lluís Vilanova <vilanova@ac.upc.edu>"
__copyright__ = "Copyright 2012-2016, Lluís Vilanova <vilanova@ac.upc.edu>"
__license__ = "GPL version 2 or (at your option) any later version"
__maintainer__ = "Stefan Hajnoczi"
__email__ = "stefanha@l... |
from dasbus.server.interface import dbus_interface
from dasbus.server.property import emits_properties_changed
from dasbus.typing import * # pylint: disable=wildcard-import
from pyanaconda.modules.common.base import KickstartModuleInterfaceTemplate
from pyanaconda.modules.common.constants.objects import DISK_SELECTION... |
"""Module to provide skill recommendations and non-linear course navigation."""
__author__ = 'Boris Roussev (borislavr@google.com)'
class BaseSkillRecommender(object):
"""Base class to model the behavior of a skill recommendation algorithm."""
def __init__(self, skill_map):
self._skill_map = skill_map
... |
import time
import sys
import pygame
import pygame.image
import pygasus
def main():
pygame.init()
hScreen=pygame.display.set_mode((256,240))
pygasus.read_ines(sys.argv[1])
pygasus.pReset()
pygasus.setkeys({
'q': pygame.K_q, 'w': pygame.K_w, 'a': pygame.K_a, 's': pygame.K_s,
'UP': pyg... |
from os import path, makedirs, walk
from subprocess import Popen
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
from threading import Thread
from datetime import datetime
from Queue import Queue
from time import sleep
from sys import exit, stdout, exc_info
from pprint import pprint
import logging
fr... |
""" *==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
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 yo... |
from odoo import _, api, models
from odoo.exceptions import UserError
class AccountTax(models.Model):
_inherit = 'account.tax'
def write(self, vals):
forbidden_fields = set([
'amount_type', 'amount', 'type_tax_use', 'tax_group_id', 'price_include',
'include_base_amount'
]... |
"""Model code for the Transaction Log."""
import calendar
import json
import os
from functools import wraps
from storm.expr import Join, LeftJoin
from storm.locals import Int, DateTime, Enum, Store, Unicode
from storm.store import AutoReload
from config import config
from backends.filesync.data.dbmanager import get_sha... |
"""
Demographics API URLs.
"""
from django.conf.urls import include, url
from .v1 import urls as v1_urls
app_name = 'openedx.core.djangoapps.demographics'
urlpatterns = [
url(r'^v1/', include(v1_urls))
] |
from __future__ import absolute_import
from __future__ import print_function
from .._abstract.abstract import BaseAGSServer
import json
class MobileServiceLayer(BaseAGSServer):
"""
Represents a single mobile service layer
"""
_url = None
_proxy_url = None
_proxy_port = None
_securityHandler ... |
from eventlet import Timeout
import swift.common.utils
class MessageTimeout(Timeout):
def __init__(self, seconds=None, msg=None):
Timeout.__init__(self, seconds=seconds)
self.msg = msg
def __str__(self):
return '%s: %s' % (Timeout.__str__(self), self.msg)
class SwiftException(Exception):... |
import datetime
import pendulum
import pytest
from airflow.example_dags.plugins.workday import AfterWorkdayTimetable
from airflow.settings import TIMEZONE
from airflow.timetables.base import DagRunInfo, DataInterval, TimeRestriction, Timetable
START_DATE = pendulum.DateTime(2021, 9, 4, tzinfo=TIMEZONE) # This is a Sat... |
"""Tests for cloud_lib."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import unittest
import mock
import requests
from official.utils.logs import cloud_lib
class CloudLibTest(unittest.TestCase):
@mock.patch("requests.get")
def test_on_gcp(self, mock_... |
import numpy as np
from dipy.data import get_sphere, get_3shell_gtab, get_isbi2013_2shell_gtab
from dipy.reconst.shore import ShoreModel
from dipy.reconst.shm import QballModel, sh_to_sf
from dipy.direction.peaks import gfa, peak_directions
from numpy.testing import (assert_equal,
assert_almo... |
"""Remove ditchchart waffle flag from Flag model data"""
from __future__ import unicode_literals
from django.db import migrations
def remove_ditchchart_waffle(apps, schema_editor):
Flag = apps.get_model('waffle', 'Flag')
Flag.objects.filter(name='ditchchart').delete()
def add_ditchchart_waffle(apps, schema_edit... |
__all__ = ('pre_init', 'post_init', 'pre_save', 'pre_save_post_validation',
'post_save', 'pre_delete', 'post_delete')
signals_available = False
try:
from blinker import Namespace
signals_available = True
except ImportError:
class Namespace(object):
def signal(self, name, doc=None):
... |
import unittest
import numpy as np
import theano
from keras.utils.theano_utils import ndim_tensor
from keras.layers.core import *
from keras.layers.convolutional import *
from keras.layers.recurrent import SimpleRNN
def check_layer_output_shape(layer, input_data):
ndim = len(input_data.shape)
layer.input = ndim... |
import bs4 as BeautifulSoup
from DOM.W3C import w3c
from OS.Windows import security_sys
from DOM.W3C.NamedNodeMap import NamedNodeMap
import logging
log = logging.getLogger("Thug")
def loadXML(self, bstrXML):
self.xml = w3c.parseString(bstrXML)
#self.attributes = NamedNodeMap(self.xml._node)
if "res://" not... |
"""
rv_smartcard.py - Testing software smartcards using remote-viewer
Requires: connected binaries remote-viewer, Xorg, gnome session
The test also assumes that the guest is setup with the correct
options to handle smartcards.
"""
import logging
from autotest.client.shared import error
def run(test, params, env):
"... |
from freestyle.chainingiterators import ChainSilhouetteIterator
from freestyle.predicates import (
AndUP1D,
NotUP1D,
QuantitativeInvisibilityUP1D,
TrueUP1D,
pyIsInOccludersListUP1D,
)
from freestyle.shaders import (
ConstantColorShader,
ConstantThicknessShader,
SamplingShader,
)
... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os.path
import re
import shutil
import sys
import time
import yaml
from jinja2 import Environment, FileSystemLoader
import ansible.constants as C
from ansible import context
from ansible.cli import CLI
from ansible.cli.argume... |
import re
import urllib
import base64
from boto.connection import AWSAuthConnection
from boto.exception import BotoServerError
from boto.regioninfo import RegionInfo
import boto
import boto.jsonresponse
from boto.ses import exceptions as ses_exceptions
class SESConnection(AWSAuthConnection):
ResponseError = BotoSer... |
MPL = """\
This Source Code Form is subject to the terms of the Mozilla Public \
License, v. 2.0. If a copy of the MPL was not distributed with this \
file, You can obtain one at http://mozilla.org/MPL/2.0/.\
"""
APACHE = """\
Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or \
http://www.apache.org/lic... |
from translate.lang import factory
def test_punctranslate():
"""Tests that we can translate punctuation."""
language = factory.getlanguage('ne')
assert language.punctranslate(u"") == u""
assert language.punctranslate(u"abc efg") == u"abc efg"
assert language.punctranslate(u"abc efg.") == u"abc efg ।... |
"""Base class for UniFi clients."""
import logging
from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC
from .unifi_entity_base import UniFiBase
LOGGER = logging.getLogger(__name__)
class UniFiClient(UniFiBase):
"""Base class for UniFi clients."""
def __init__(self, client, controller) -> No... |
class A(B):
def __init__(self):
<warning descr="Python version 2.7 does not support this syntax. super() should have arguments in Python 2">super()</warning>
<warning descr="Python versions 3.5, 3.6, 3.7, 3.8, 3.9, 3.10 do not have method cmp">cmp()</warning>
<warning descr="Python versions 3.5, 3.6, 3.7, 3... |
"""
This module's purpose is to enable us to present internals of objects
in well-defined way to operator. To do this we can define "views"
on some objects. View is a definition of how to present object
and relations to other objects which also have their views defined.
By using views we can avoid making all interestin... |
"""Test for the estimate_pi example."""
import logging
import unittest
from apache_beam.examples.complete import estimate_pi
from apache_beam.testing.test_pipeline import TestPipeline
from apache_beam.testing.util import assert_that
from apache_beam.testing.util import BeamAssertException
def in_between(lower, upper):
... |
"""
Support for Proliphix NT10e Thermostats.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/climate.proliphix/
"""
import voluptuous as vol
from homeassistant.components.climate import (
PRECISION_TENTHS, STATE_COOL, STATE_HEAT, STATE_IDLE,
Climat... |
"""
:mod:`nova` -- Cloud IaaS Platform
===================================
.. automodule:: nova
:platform: Unix
:synopsis: Infrastructure-as-a-Service Cloud platform.
.. moduleauthor:: Jesse Andrews <jesse@ansolabs.com>
.. moduleauthor:: Devin Carlen <devin.carlen@gmail.com>
.. moduleauthor:: Vishvananda Ishaya <... |
import os
import time
from graphite.node import LeafNode, BranchNode
from graphite.intervals import Interval, IntervalSet
from graphite.carbonlink import CarbonLink
from graphite.logger import log
from django.conf import settings
try:
import whisper
except ImportError:
whisper = False
try:
import rrdtool
except I... |
"""Test runner for typeshed.
Depends on mypy being installed.
Approach:
1. Parse sys.argv
2. Compute appropriate arguments for mypy
3. Stuff those arguments into sys.argv
4. Run mypy.main('')
5. Repeat steps 2-4 for other mypy runs (e.g. --py2)
"""
import os
import re
import sys
import argparse
parser = argparse.Argume... |
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('zerver', '0102_convert_muted_topic'),
]
operations = [
migrations.RemoveField(
model_name='userprofile',
name='muted_topics',
),
] |
from django import template
register = template.Library()
@register.inclusion_tag('rapidsms/templatetags/form.html')
def render_form(form):
return {"form": form} |
from time import time
import argparse
import os
from pprint import pprint
import numpy as np
from threadpoolctl import threadpool_limits
import sklearn
from sklearn.model_selection import train_test_split
from sklearn.experimental import enable_hist_gradient_boosting # noqa
from sklearn.ensemble import HistGradientBoo... |
import time
from datetime import datetime
from math import floor
from django.conf import settings
from django.test import RequestFactory
from django.test.utils import override_settings
from django.utils.http import parse_http_date
from bedrock.base.urlresolvers import reverse
from mock import patch
from nose.tools impo... |
"""Insteon base entity."""
import logging
from pyinsteon import devices
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import (
async_dispatcher_connect,
async_dispatcher_send,
)
from homeassistant.helpers.entity import Entity
from .const import (
DOMAIN,
SIGNAL_ADD_DEFAUL... |
"""
Produces contiguous completed ranges of recurring tasks.
See RangeDaily and RangeHourly for basic usage.
Caveat - if gaps accumulate, their causes (e.g. missing dependencies) going
unmonitored/unmitigated, then this will eventually keep retrying the same gaps
over and over and make no progress to more recent times.... |
from __future__ import print_function
import sys, optparse, time
import logging
from proton import *
try:
long()
except:
long = int
usage = """
Usage: msgr-send [OPTIONS]
-a <addr>[,<addr>]* \tThe target address [amqp[s]://domain[/name]]
-c # \tNumber of messages to send before exiting [0=forever]
-b # \tSiz... |
"""
.. module: lemur.authorities.service
:platform: Unix
:synopsis: This module contains all of the services level functions used to
administer authorities in Lemur
:copyright: (c) 2015 by Netflix Inc., see AUTHORS for more
:license: Apache, see LICENSE for more details.
.. moduleauthor:: Kevin Glis... |
"""Tests for record_input_op."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from tensorflow.python.lib.io import tf_record
from tensorflow.python.ops import data_flow_ops
from tensorflow.python.platform import test
class RecordInputOpTest(test.... |
import copy
import mock
from oslo_config import cfg
import webob
from nova.api.openstack.compute.legacy_v2.contrib import os_tenant_networks \
as networks
from nova.api.openstack.compute import tenant_networks \
as networks_v21
from nova import exception
from nova import test
from nova.tests.unit.api.op... |
"""Ragged operations for working with string Tensors."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.pyt... |
from rosbridge_library.internal.ros_loader import get_service_class
from rosbridge_library.internal import message_conversion
from rosbridge_library.capability import Capability
import rospy
import time
class AdvertisedServiceHandler():
id_counter = 1
responses = {}
def __init__(self, service_name, service_... |
"""Token-related utilities"""
from __future__ import absolute_import, print_function
from collections import namedtuple
from io import StringIO
from keyword import iskeyword
from . import tokenize2
from .py3compat import cast_unicode_py2
Token = namedtuple('Token', ['token', 'text', 'start', 'end', 'line'])
def generat... |
import ctypes
from . import copy_ctypes_list
from .arm64_const import *
class Arm64OpMem(ctypes.Structure):
_fields_ = (
('base', ctypes.c_uint),
('index', ctypes.c_uint),
('disp', ctypes.c_int32),
)
class Arm64OpShift(ctypes.Structure):
_fields_ = (
('type', ctypes.c_uint),
... |
import mock
import unittest
from boto.ec2.address import Address
class AddressTest(unittest.TestCase):
def setUp(self):
self.address = Address()
self.address.connection = mock.Mock()
self.address.public_ip = "192.168.1.1"
def check_that_attribute_has_been_set(self, name, value, attribute... |
import traceback
try:
import ovirtsdk4.types as otypes
except ImportError:
pass
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ovirt import (
BaseModule,
check_sdk,
equal,
create_connection,
ovirt_full_argument_spec,
)
ANSIBLE_METADATA = {'status': 'preview',
... |
"""NOTE: copied/adapted from SQLAlchemy master for backwards compatibility;
this should be removable when Alembic targets SQLAlchemy 1.0.0
"""
import operator
from .plugin.plugin_base import SkipTest
from sqlalchemy.util import decorator
from . import config
from sqlalchemy import util
from ..util import compat
imp... |
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2015, Kovid Goyal <kovid at kovidgoyal.net>'
import errno, socket, select, os
from Cookie import SimpleCookie
from contextlib import closing
from urlparse import parse_qs
... |
from math import fabs, ceil
import traceback
import re
from CodernityDB.database import RecordNotFound
from couchpotato import get_db
from couchpotato.api import addApiView
from couchpotato.core.event import addEvent, fireEvent
from couchpotato.core.helpers.encoding import toUnicode, ss
from couchpotato.core.helpers.va... |
"""
This module tests capnp serialization of HTMPredictionModel.
"""
import copy
import datetime
import numpy.random
import numpy.testing
import unittest
try:
# NOTE need to import capnp first to activate the magic necessary for
# PythonDummyRegion_capnp, etc.
import capnp
except ImportError:
capnp = None
else:... |
from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import (
int_or_none,
try_get,
unified_timestamp,
)
class EggheadCourseIE(InfoExtractor):
IE_DESC = 'egghead.io course'
IE_NAME = 'egghead:course'
_VALID_URL = r'https://egghead\.io/courses/(?P<id>[^/?#&]+)'
... |
"""Sampling functions."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python import summary
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorf... |
import os
import sys
import unittest
sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.pardir, 'perf'))
from core import path_util
path_util.AddPyUtilsToPath()
path_util.AddTracingToPath()
import metadata_extractor
from metadata_extractor import OSName
from core.tbmv3 import trace_processor
import mock
clas... |
from nipype.testing import assert_equal
from nipype.interfaces.slicer.utilities import EMSegmentTransformToNewFormat
def test_EMSegmentTransformToNewFormat_inputs():
input_map = dict(args=dict(argstr='%s',
),
environ=dict(nohash=True,
usedefault=True,
),
ignore_exception=dict(nohash=True,
us... |
import volatility.obj as obj
class _KDDEBUGGER_DATA64(obj.CType):
"""A class for KDBG"""
def is_valid(self):
"""Returns true if the kdbg_object appears valid"""
# Check the OwnerTag is in fact the string KDBG
return obj.CType.is_valid(self) and self.Header.OwnerTag == 0x4742444B
@pro... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import sys
from nose.plugins.skip import SkipTest
if sys.version_info < (2, 7):
raise SkipTest("F5 Ansible modules require Python >= 2.7")
from ansible.compat.tests import unittest
from ansible.compat.tests... |
"""The virtual interfaces extension."""
from nova.api.openstack import common
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.api.openstack import xmlutil
from nova import compute
from nova import network
from nova.openstack.common import log as logging
LOG = logging.getLogger(__... |
'''
Unit tests for yedit
'''
import unittest
import os
from yedit import Yedit
from yedit import YeditException
class YeditTest(unittest.TestCase):
'''
Test class for yedit
'''
data = {'a': 'a',
'b': {'c': {'d': [{'e': 'x'}, 'f', 'g']}},
}
filename = 'yedit_test.yml'
def... |
from django.conf.urls import url
from oscar.core.application import DashboardApplication
from oscar.core.loading import get_class
class ShippingDashboardApplication(DashboardApplication):
name = None
default_permissions = ['is_staff']
weight_method_list_view = get_class(
'dashboard.shipping.views', ... |
"""Tests for the openmc.deplete.ReactionRates class."""
import numpy as np
from openmc.deplete import ReactionRates
def test_get_set():
"""Tests the get/set methods."""
local_mats = ["10000", "10001"]
nuclides = ["U238", "U235"]
reactions = ["fission", "(n,gamma)"]
rates = ReactionRates(local_mats, ... |
from will.plugin import WillPlugin
from will.decorators import respond_to, periodic, hear, randomly, route, rendered_template, require_settings
class ItsLovePlugin(WillPlugin):
@hear("i love(?: you,?)? will")
def hear_love(self, message):
self.say("I love you, too.", message=message)
@respond_to("i ... |
"""Test the wallet backup features.
Test case is:
4 nodes. 1 2 and 3 send transactions between each other,
fourth node is a miner.
1 2 3 each mine a block to start, then
Miner creates 100 blocks so 1 2 3 each have 50 mature
coins to spend.
Then 5 iterations of 1/2/3 sending coins amongst
themselves to get transactions ... |
import mock
import os
import sys
import re
import json
import socorro.storage.crashstorage as cstore
import socorro.unittest.testlib.expectations as exp
import socorro.lib.util as util
import socorro.unittest.testlib.loggerForTest as loggerForTest
def testLegacyThrottler():
config = util.DotDict()
config.throttleCo... |
import sys
from pdfdevice import PDFTextDevice
from pdffont import PDFUnicodeNotDefined
from layout import LTContainer, LTPage, LTText, LTLine, LTRect, LTCurve
from layout import LTFigure, LTImage, LTChar, LTTextLine
from layout import LTTextBox, LTTextBoxVertical, LTTextGroup
from utils import apply_matrix_pt, mult_ma... |
"""Starter script for Nova Cells Service."""
import sys
from oslo.config import cfg
from nova import config
from nova.openstack.common import log as logging
from nova.openstack.common.report import guru_meditation_report as gmr
from nova import service
from nova import utils
from nova import version
CONF = cfg.CONF
CON... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Article',
fields=[
('id', models.AutoField(auto_created=T... |
"""
Fuzz distortion. High gain followed by, asymmetrical clipping,
hard clip on top, soft compression on bottom.
"""
from pyo import *
s = Server(duplex=0).boot()
SOURCE = "../snds/flute.aif"
BP_CENTER_FREQ = 250
BP_Q = 2
BOOST = 5
LP_CUTOFF_FREQ = 3500
BALANCE = 0.8
src = SfPlayer(SOURCE, loop=True).mix(2)
low_table =... |
from __future__ import absolute_import
import pytest
from ansible.modules.source_control.gitlab.gitlab_hook import GitLabHook
def _dummy(x):
"""Dummy function. Only used as a placeholder for toplevel definitions when the test is going
to be skipped anyway"""
return x
pytestmark = []
try:
from .gitlab i... |
def func():
value = "not-none"
if value is None:
prin<caret>t("None")
else:
print("Not none") |
from easydict import EasyDict
from lib.curator_action import CuratorAction
import logging
logger = logging.getLogger(__name__)
class CuratorRunner(CuratorAction):
def run(self, action=None, log_level='warn', dry_run=False, operation_timeout=600, **kwargs):
"""Curator based action entry point
"""
... |
"""Unit tests for Web Development Style Guide checker."""
import os
import re
import sys
import unittest
test_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.extend([
os.path.normpath(os.path.join(test_dir, '..', '..', '..', 'tools')),
os.path.join(test_dir),
])
import find_depot_tools # pylint: disab... |
"""
Scrapy Shell
See documentation in docs/topics/shell.rst
"""
from threading import Thread
from scrapy.commands import ScrapyCommand
from scrapy.shell import Shell
from scrapy.http import Request
from scrapy.utils.spider import spidercls_for_request, DefaultSpider
from scrapy.utils.url import guess_scheme
class Comma... |
from __future__ import unicode_literals
import warnings
from django.contrib.localflavor.id.forms import (IDPhoneNumberField,
IDPostCodeField, IDNationalIdentityNumberField, IDLicensePlateField,
IDProvinceSelect, IDLicensePlatePrefixSelect)
from django.test import SimpleTestCase
class IDLocalFlavorTests(SimpleTe... |
"""Import all modules in the `ragged` package that define exported symbols.
Additional, import ragged_dispatch (which has the side-effect of registering
dispatch handlers for many standard TF ops) and ragged_operators (which has the
side-effect of overriding RaggedTensor operators, such as RaggedTensor.__add__).
We don... |
import 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 'Tidbit.content'
db.alter_column('auxiliary_tidbit', 'content', self.gf('tinymce.models.HTMLField')())
def backwar... |
"""
Layer on top of the upload APIs to perform many of the common client-side tasks
around uploading a content unit, such as the ability to resume a cancelled
download, uploading a file in multiple chunks instead of a single call, and
client-side tracking of upload requests on the server.
"""
import copy
import errno
i... |
"""
Helpers methods for site configuration.
"""
from django.conf import settings
from microsite_configuration import microsite
def get_current_site_configuration():
"""
Return configuration for the current site.
Returns:
(openedx.core.djangoapps.site_configuration.models.SiteConfiguration): SiteCon... |
from cinder.tests.functional import functional_helpers
class LoginTest(functional_helpers._FunctionalTestBase):
def test_login(self):
"""Simple check - we list volumes - so we know we're logged in."""
volumes = self.api.get_volumes()
self.assertIsNotNone(volumes) |
from odoo import api, fields, models
from ast import literal_eval
class ResCompany(models.Model):
_inherit = 'res.company'
def _compute_website_theme_onboarding_done(self):
""" The step is marked as done if one theme is installed. """
# we need the same domain as the existing action
acti... |
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir, 'perf'))
from chrome_telemetry_build import chromium_config
TELEMETRY_DIR = chromium_config.GetTelemetryDir()
_top_level_dir = os.path.dirname(os.path.realpath(__file__))
def Config(benchmark_subdirs):
return chromium_config.Chrom... |
"""
.. _on_screen_notification_tests:
:mod:`on_screen_notification_tests` -- Module for testing on-screen notifications
=================================================================================
.. automodule:: on_screen_notification_tests
.. moduleauthor:: Evgeny Fadeev <evgeny.fadeev@gmail.com>
"""
import da... |
from .ExodusSourceLineSampler import ExodusSourceLineSampler
from ..base import ChiggerResult
class ExodusResultLineSampler(ChiggerResult):
"""
Object for sampling ExodusSource object contained in an ExodusResult.
"""
@staticmethod
def getOptions():
opt = ChiggerResult.getOptions()
r... |
"""
Step definitions for providing notes/hints.
The note steps explain what was important in the last few steps of
this scenario (for a test reader).
"""
from __future__ import absolute_import
from behave import step
@step(u'note that "{remark}"')
def step_note_that(context, remark):
"""
Used as generic step th... |
"""Utility code for constructing importers, etc."""
from . import abc
from ._bootstrap import module_from_spec
from ._bootstrap import _resolve_name
from ._bootstrap import spec_from_loader
from ._bootstrap import _find_spec
from ._bootstrap_external import MAGIC_NUMBER
from ._bootstrap_external import _RAW_MAGIC_NUMBE... |
farmer = {
'kb': '''
Farmer(Mac)
Rabbit(Pete)
Mother(MrsMac, Mac)
Mother(MrsRabbit, Pete)
(Rabbit(r) & Farmer(f)) ==> Hates(f, r)
(Mother(m, c)) ==> Loves(m, c)
(Mother(m, r) & Rabbit(r)) ==> Rabbit(m)
(Farmer(f)) ==> Human(f)
(Mother(m, h) & Human(h)) ==> Human(m)
''',
'queries':'''
Human(x)
Hates(x, y)
''',
}... |
from gnuradio import gr, gr_unittest
from gnuradio import blocks, digital
import pmt
import numpy as np
import sys
def make_length_tag(offset, length):
return gr.python_to_tag({'offset' : offset,
'key' : pmt.intern('packet_len'),
'value' : pmt.from_long(leng... |
from __future__ import unicode_literals
from django.contrib.gis.geos import HAS_GEOS
from django.contrib.gis.tests.utils import no_oracle
from django.db import connection
from django.test import TestCase, skipUnlessDBFeature
from django.test.utils import override_settings
from django.utils import timezone
if HAS_GEOS:
... |
from debug_toolbar.utils.sqlparse.tokens import *
KEYWORDS = {
'ABORT': Keyword,
'ABS': Keyword,
'ABSOLUTE': Keyword,
'ACCESS': Keyword,
'ADA': Keyword,
'ADD': Keyword,
'ADMIN': Keyword,
'AFTER': Keyword,
'AGGREGATE': Keyword,
'ALIAS': Keyword,
'ALL': Keyword,
'ALLOCATE':... |
import os
import shutil
import glob
import time
import sys
import subprocess
import string
from optparse import OptionParser, make_option
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
PKG_NAME = os.path.basename(SCRIPT_DIR)
PARAMETERS = None
XW_ENV = "export DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/5000/d... |
"""Merging of policies."""
from typing import Dict, List, Set, cast
from .types import CategoryType, PolicyType
def merge_policies(policies: List[PolicyType]) -> PolicyType:
"""Merge policies."""
new_policy: Dict[str, CategoryType] = {}
seen: Set[str] = set()
for policy in policies:
for category... |
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import hamming, hanning, triang, blackmanharris, resample
import math
import sys, os, functools, time
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../../software/models/'))
sys.path.append(os.path.join(os.path.dirname(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.