content stringlengths 4 20k |
|---|
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import ratesetterclient
setup(
name='ratesetterClient',
version=ratesetterclient.__version__,
description='python library for ratesetter.com',
author='Jean-Francois Paris',
author_email='<EMAIL>',
pa... |
# -*- coding: utf-8 -*-
"""
inflection
~~~~~~~~~~~~
A port of Ruby on Rails' inflector to Python.
:copyright: (c) 2012-2015 by Janne Vanhala
:license: MIT, see LICENSE for more details.
"""
import re
import unicodedata
__version__ = '0.3.1'
PLURALS = [
(r"(?i)(quiz)$", r'\1zes'),
(r"(?i... |
import unittest
import sqlite3 as sqlite
def func_returntext():
return "foo"
def func_returnunicode():
return "bar"
def func_returnint():
return 42
def func_returnfloat():
return 3.14
def func_returnnull():
return None
def func_returnblob():
return b"blob"
def func_raiseexception():
5/0
de... |
"""Utilities for datacite module."""
import random
import string
from invenio_pidstore.errors import PIDDoesNotExistError
from invenio_pidstore.models import PersistentIdentifier
def generate_doi(prefix, experiment=None):
"""Generate random DOI, unique within PIDStore."""
while True:
doi = random_do... |
#!/usr/bin/env python
from __future__ import print_function
import sys
import os
import os.path
from datetime import datetime, timedelta
simple = os.environ.get('MWS_MERCHANT', None)
if not simple:
print("""
Please set the MWS_MERCHANT environmental variable
to your Merchant or SellerId to enable ... |
"""Test function :func:`iris.util.demote_dim_coord_to_aux_coord`."""
from __future__ import (absolute_import, division, print_function)
# Import iris.tests first so that some things can be initialised before
# importing anything else.
import iris.tests as tests
import unittest
import iris
import iris.tests.stock as... |
from pyjamas import DOM
from pyjamas import Factory
from pyjamas.ui import Applier
class CellFormatter(Applier):
def __init__(self, outer, **kwargs):
self.outer = outer
Applier.__init__(self, **kwargs)
def addStyleName(self, row, column, styleName):
self.outer.prepareCell(row, column)... |
from gnuradio import gr, gru
_plot = None
def design_filter(interpolation, decimation, fractional_bw):
"""
Given the interpolation rate, decimation rate and a fractional bandwidth,
design a set of taps.
@param interpolation: interpolation factor
@type interpolation: integer > 0
@param decima... |
# Mimic the sqlite3 console shell's .dump command
# Every identifier in sql is quoted based on a comment in sqlite
# documentation "SQLite adds new keywords from time to time when it
# takes on new features. So to prevent your code from being broken by
# future enhancements, you should normally quote any identifier th... |
#!/usr/bin/env python
import rospy
import tf
import std_msgs.msg
from math import atan2, hypot
from geometry_msgs.msg import PoseStamped #laser location
from geometry_msgs.msg import Twist #high level motor control (linear and angular bot velocity)
from nav_msgs.msg import Odometry #Get the robot position
from WheelVel... |
"""
Copyright (C) 2004-2015 Pivotal Software, Inc. All rights reserved.
This program and the accompanying materials are made available under
the terms of the under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
... |
from __future__ import division, absolute_import, print_function
import os
import distutils.msvccompiler
from distutils.msvccompiler import *
from .system_info import platform_bits
class MSVCCompiler(distutils.msvccompiler.MSVCCompiler):
def __init__(self, verbose=0, dry_run=0, force=0):
distutils.msvcc... |
"""
This module contains basic interfaces used throughout the whole gensim package.
The interfaces are realized as abstract base classes (ie., some optional functionality
is provided in the interface itself, so that the interfaces can be subclassed).
"""
from __future__ import with_statement
import logging
from gen... |
"""Identity bijector."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import constant_op
from tensorflow.python.ops.distributions import bijector
__all__ = [
"Identity",
]
class Identity(bijector.Bijector):
"""C... |
"""
Test for LMS instructor background task queue management
"""
from mock import patch, Mock
from bulk_email.models import CourseEmail, SEND_TO_ALL
from courseware.tests.factories import UserFactory
from xmodule.modulestore.exceptions import ItemNotFoundError
from instructor_task.api import (
get_running_instruct... |
from oslo.config import cfg
import webob
from nova import compute
from nova import exception
from nova.openstack.common import jsonutils
from nova import test
from nova.tests.api.openstack import fakes
CONF = cfg.CONF
CONF.import_opt('password_length', 'nova.utils')
def rescue(self, context, instance, rescue_passwo... |
import os
import sys
import tempfile
import shutil
from pip.req import InstallRequirement, RequirementSet, parse_requirements
from pip.log import logger
from pip.locations import (src_prefix, virtualenv_no_global, distutils_scheme,
build_prefix, running_under_virtualenv)
from pip.basecommand ... |
data = (
'nyaess', # 0x00
'nyaeng', # 0x01
'nyaej', # 0x02
'nyaec', # 0x03
'nyaek', # 0x04
'nyaet', # 0x05
'nyaep', # 0x06
'nyaeh', # 0x07
'neo', # 0x08
'neog', # 0x09
'neogg', # 0x0a
'neogs', # 0x0b
'neon', # 0x0c
'neonj', # 0x0d
'neonh', # 0x0e
'neod', # 0x0f
'neol', ... |
import warnings
import numpy as np
from numpy.testing import TestCase, assert_array_almost_equal, \
assert_array_equal, assert_raises, assert_
from scipy.signal import tf2zpk, zpk2tf, bessel, BadCoefficients
class TestTf2zpk(TestCase):
def test_simple(self):
z_r = np.array([0.5, -0.5])
... |
import six
from nova import exception
from nova.i18n import _
class CpuDiagnostics(object):
def __init__(self, time=0):
"""Create a new CpuDiagnostics object
:param time: CPU Time in nano seconds (Integer)
"""
self.time = time
class NicDiagnostics(object):
def __init__(se... |
import re
from flask_login import current_user
from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileAllowed, FileRequired
from packaging import version
from wtforms import StringField, SubmitField, validators, ValidationError
_project_name_re = re.compile(
r"^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-... |
import unittest
import os
from source.informationManagers.search.scriptedFileSearch import ScriptedFileSearch
class ScriptProvider_test(unittest.TestCase):
mediaRoot = "/media/root/"
class ProcessProvider(object):
scriptCalledWith = None
def call(self, cmd, shell=False):
self.s... |
"""
Test strerror
"""
import socket
import os
from twisted.trial.unittest import TestCase
from twisted.internet.tcp import ECONNABORTED
from twisted.python.win32 import _ErrorFormatter, formatError
from twisted.python.runtime import platform
class ErrorFormatingTestCase(TestCase):
"""
Tests for C{_ErrorFor... |
from __future__ import unicode_literals
import itertools
import re
from .common import SearchInfoExtractor
class GoogleSearchIE(SearchInfoExtractor):
IE_DESC = 'Google Video search'
_MAX_RESULTS = 1000
IE_NAME = 'video.google:search'
_SEARCH_KEY = 'gvsearch'
_TEST = {
'url': 'gvsearch15:... |
import urllib,urllib2,re,xbmcplugin,xbmcgui,xbmcvfs,os,sys,datetime,string,hashlib,net
from resources.lib.modules.plugintools import *
import xbmcaddon
import json
from cookielib import CookieJar
from resources.lib.modules.common import *
def vod_blaze_new():
url = 'http://www.blaze.tv/series?page='
link = ... |
"""
Oracle database backend for Django.
Requires cx_Oracle: http://www.python.net/crew/atuining/cx_Oracle/
"""
import os
import datetime
import time
# Oracle takes client-side character set encoding from the environment.
os.environ['NLS_LANG'] = '.UTF8'
try:
import cx_Oracle as Database
except ImportError, e:
... |
#! /usr/bin/env python
# encoding: utf-8
# JB Mouret - 2009
"""
Quick n dirty tbb detection
"""
import os, glob, types
import Options, Configure
def detect_tbb(conf):
env = conf.env
opt = Options.options
if Options.options.no_tbb:
print "TBB (multicore) is disabled"
return 0
if Options.options.tbb:
conf.... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Startup plugin for command-line deletes
Copyright 2009 Glencoe Software, Inc. All rights reserved.
Use is subject to license terms supplied in LICENSE.txt
"""
import sys
from omero.cli import CLI, GraphControl
HELP = """Delete OMERO data.
Remove entire gr... |
import logging
import os
import subprocess
import sys
from telemetry.core import util
from telemetry.core.platform import posix_platform_backend
from telemetry.core.platform import proc_supporting_platform_backend
from telemetry.page import cloud_storage
class LinuxPlatformBackend(
posix_platform_backend.PosixPl... |
import unittest2 as unittest
from webkitpy.tool.steps.addsvnmimetypeforpng import AddSvnMimetypeForPng
from webkitpy.common.system.filesystem_mock import MockFileSystem
from webkitpy.tool.mocktool import MockOptions, MockTool
from webkitpy.common.system.systemhost_mock import MockSystemHost
from webkitpy.common.system... |
import datetime
# Django
from django.contrib.auth.models import User
from django.core.cache import cache
from django.core.exceptions import ValidationError
from django.urls import (
reverse,
reverse_lazy
)
# wger
from wger.core.tests import api_base_test
from wger.core.tests.base_testcase import (
WgerAdd... |
'''Tests the rpc middleware and utilities. It uses the calculator example.'''
import unittest
import pulsar
from pulsar import Config, get_actor
from pulsar.apps import MultiApp
from pulsar.apps.wsgi import WSGIServer
def dummy(environ, start_response):
start_response('200 OK', [])
yield [b'dummy']
class M... |
from .libindy import do_call, create_cb
from typing import Optional
from ctypes import *
import logging
async def add_wallet_record(wallet_handle: int,
type_: str,
id_: str,
value: str,
tags_json: Optiona... |
import base
import tuned.logs
log = tuned.logs.get()
class Plugin(base.Plugin):
"""
Base class for plugins with device hotpluging support.
"""
def __init__(self, *args, **kwargs):
super(Plugin, self).__init__(*args, **kwargs)
self._hardware_events_init()
def cleanup(self):
super(Plugin, self).cleanup()
... |
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.connection import Connection
from ansible.module_utils.network.eos.providers import providers
from ansible.module_utils._text import to_text
class NetworkModule(AnsibleModule):
fail_on_missing_provider = True
def __init__(self, c... |
#! /usr/bin/env python3
# one of two scripts to create the tables, types and schemas necessary for odie.
# Unfortunately we need to split these (nearly identical) scripts due to Flask-SQLAlchemy
# not correctly handling Enum creation when handling multiple databases.
# (See https://gist.github.com/TehMillhouse/fdaffc4... |
"""
=========
traitsdoc
=========
Sphinx extension that handles docstrings in the Numpy standard format, [1]
and support Traits [2].
This extension can be used as a replacement for ``numpydoc`` when support
for Traits is required.
.. [1] http://projects.scipy.org/numpy/wiki/CodingStyleGuidelines#docstring-standard
.... |
from django import forms
from django.contrib.gis.geos import GEOSException, GEOSGeometry
from django.utils.translation import ugettext_lazy as _
from .widgets import OpenLayersWidget
class GeometryField(forms.Field):
"""
This is the basic form field for a Geometry. Any textual input that is
accepted by ... |
from contextlib import contextmanager
import os
import sys
import unittest.mock
from coala_utils.ContextManagers import retrieve_stdout, retrieve_stderr
def execute_coala(func, binary, *args):
"""
Executes the main function with the given argument string from given module.
:param function: A main fun... |
from cassandra.cluster import Cluster
from cassandra.policies import (RoundRobinPolicy, DCAwareRoundRobinPolicy,
TokenAwarePolicy, WhiteListRoundRobinPolicy)
from cassandra.auth import PlainTextAuthProvider
from airflow.hooks.base_hook import BaseHook
from airflow.utils.log.logging_mixi... |
from telemetry.core import exceptions
from telemetry.core import util
from telemetry.unittest import tab_test_case
class InspectorRuntimeTest(tab_test_case.TabTestCase):
def testRuntimeEvaluateSimple(self):
res = self._tab.EvaluateJavaScript('1+1')
assert res == 2
def testRuntimeEvaluateThatFails(self):
... |
import glob
import os
import random
import cv2
import numpy as np
import matplotlib.pyplot as plt
from annot_utils import *
import torch
from torch.utils.data import Dataset
def normalizeCoords(x, size):
n = (x / size) * 2.0 - 1.0
return n
def denormalizeCoords(n, size):
x = int((n + 1) / 2 * size)
... |
import unittest
import os
import IECore
class SkeletonPrimitiveTests(unittest.TestCase):
def setUp(self):
mts = IECore.M44fVectorData()
mts.resize(10)
ids = IECore.IntVectorData()
ids.resize(10)
for i in range(0, 10):
ids[i] = i-1
vec = IECore.V3f(0-i, i+1, 2*i)
mts[i] = mts[i].setTranslation(vec... |
"""Test Axis config flow."""
from unittest.mock import Mock, patch
from homeassistant.components import axis
from homeassistant.components.axis import config_flow
from tests.common import mock_coro, MockConfigEntry
async def test_configured_devices(hass):
"""Test that configured devices works as expected."""
... |
# This build on top of test7 by adding some configuration values in targets
# and overriding them in the application
expected_results = {
"base": {
"desc": "override values based on labels with libs and target params (no labels)",
"app.app1": "v_app1",
"app.app2": "v_app2",
"lib1.p1"... |
#!/usr/bin/python
# coding=utf-8
##########################################################################
from test import CollectorTestCase
from test import get_collector_config
from test import unittest
from test import run_only
from mock import MagicMock
from mock import patch
from mock import call
from diamond.... |
"""Support for Motion Blinds sensors."""
from motionblinds import BlindType
from homeassistant.components.sensor import SensorEntity
from homeassistant.const import (
DEVICE_CLASS_BATTERY,
DEVICE_CLASS_SIGNAL_STRENGTH,
PERCENTAGE,
SIGNAL_STRENGTH_DECIBELS_MILLIWATT,
)
from homeassistant.helpers.update_... |
"""
Utility module for the search engine, contains various functions to do common
operations on lists and set of iterables
"""
import re
from search import config
def _dec(fl):
"""Return a stringified more readable float, for debugging purposes."""
return '{:.2f}'.format(fl)
def normalize(iterable):
"""... |
"""
This test will run for annotator_mixin.py
"""
import unittest
from lxml import etree
from xmodule.annotator_mixin import get_instructions, get_extension, html_to_text
class HelperFunctionTest(unittest.TestCase):
"""
Tests to ensure that the following helper functions work for the annotation tool
"""... |
# -*- coding: utf-8 -*-
# This file is placed into the public domain.
# Calculates the current version number. If possible, this is the
# output of “git describe”, modified to conform to the versioning
# scheme that setuptools uses. If “git describe” returns an error
# (most likely because we're in an unpacked copy ... |
from datetime import datetime
import pyotp
from flask import flash, redirect, request, render_template, session, url_for
from flask_login import current_user, login_required
from app.constants import event_type
from app.lib.db_utils import create_object, update_object
from app.lib.fernet_utils import decrypt_string, ... |
# TODO(okuta): Implement norm
# TODO(okuta): Implement cond
# TODO(okuta): Implement det
# TODO(okuta): Implement matrix_rank
# TODO(okuta): Implement slogdet
def trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None):
"""Returns the sum along the diagonals of an array.
It computes the sum along ... |
import sys
import mock
from oslo.config import cfg
import testtools
import webtest
from neutron.api import extensions
from neutron.api.v2 import attributes
from neutron.common import config
from neutron.common import exceptions
from neutron import context
from neutron.db import api as db
from neutron.db import quota_... |
"""
dataset.py
"""
from six import (
iteritems,
with_metaclass,
)
from zipline.modelling.term import Term
class Column(object):
"""
An abstract column of data, not yet associated with a dataset.
"""
def __init__(self, dtype):
self.dtype = dtype
def bind(self, dataset, name):
... |
import falcon
from graceful.serializers import BaseSerializer
from graceful.fields import IntField, StringField
from graceful.parameters import StringParam
from graceful.errors import ValidationError
from graceful.resources.generic import (
RetrieveUpdateDeleteAPI,
PaginatedListCreateAPI,
)
from jinja2 import... |
import os
import datetime
from datetime import datetime, timedelta
from ansible.plugins.callback import CallbackBase
class CallbackModule(CallbackBase):
"""
This callback module tells you how long your plays ran for.
"""
CALLBACK_VERSION = 2.0
CALLBACK_TYPE = 'aggregate'
CALLBACK_NAME = 'timer... |
import numpy as np
import scipy.sparse as sp
import numbers
from scipy import linalg
from sklearn.decomposition import NMF, non_negative_factorization
from sklearn.decomposition import nmf # For testing internals
from scipy.sparse import csc_matrix
from sklearn.utils.testing import assert_true
from sklearn.utils.te... |
"""Test configuration for the ZHA component."""
import pytest
import zigpy
from zigpy.application import ControllerApplication
import zigpy.config
import zigpy.group
import zigpy.types
from homeassistant.components.zha import DOMAIN
import homeassistant.components.zha.core.const as zha_const
import homeassistant.comp... |
from __future__ import unicode_literals
import mimetypes
import unittest
from os import path
from django.conf.urls.static import static
from django.http import FileResponse, HttpResponseNotModified
from django.test import SimpleTestCase, override_settings
from django.utils.http import http_date
from django.views.stat... |
"""
Single page performance tests for Studio.
"""
from bok_choy.web_app_test import WebAppTest, with_cache
from ..pages.studio.auto_auth import AutoAuthPage
from ..pages.studio.overview import CourseOutlinePage
from nose.plugins.attrib import attr
@attr(har_mode='explicit')
class StudioPagePerformanceTest(WebAppTest)... |
try:
from pyrax.exceptions import NotFound
except ImportError:
# fake exception for testing without pyrax
class NotFound(Exception):
pass
from heat.common import exception
from heat.openstack.common import log as logging
from . import rackspace_resource
logger = logging.getLogger(__name__)
clas... |
import frappe
import frappe.utils, markdown2
from frappe.website.render import clear_cache
from frappe import _
@frappe.whitelist(allow_guest=True)
def add_comment(args=None):
"""
args = {
'comment': '',
'comment_by': '',
'comment_by_fullname': '',
'comment_doctype': '',
'comment_docname': '',
'p... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.db.models.deletion
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('contentt... |
import os, sys
this_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.abspath(os.path.join(this_dir, "..", "common")))
import simplejson
def generateJSON(projectDir, outFile):
index = {}
for dirpath, dirnames, filenames in os.walk(projectDir):
for name in filenames:
if os.environ.has_key(... |
#-*- coding: utf-8 -*-
"""
.. codeauthor:: Rinze de Laat <<EMAIL>>
Copyright © 2014 Rinze de Laat, Delmic
This file is part of Odemis.
.. license::
Odemis is free software: you can redistribute it and/or modify it under the
terms of the GNU General Public License version 2 as published by the Free
Softw... |
import sys
import StringIO
from lxml import etree
import utils
Font_size= 10.0
def verbose(text):
sys.stderr.write(text+"\n")
class textbox(object):
"""A box containing plain text.
It can have an offset, in chars.
Lines can be either text strings, or textbox'es, recursively.
"""
def __init_... |
import glob
import os
import re
import shutil
import subprocess
import sys
from distutils.core import Command
class CleanupCommand(Command):
patterns = [".coverage", ".tox", ".venv", "build", "dist", "*.egg", "*.egg-info"]
description = "Clean up project directory"
user_options = []
def initialize_op... |
# Tests some corner cases with isinstance() and issubclass(). While these
# tests use new style classes and properties, they actually do whitebox
# testing of error conditions uncovered when using extension types.
import unittest
from test import test_support
import sys
class TestIsInstanceExceptions(unittest.Tes... |
import datetime
from openerp.osv import fields, osv
class analytical_timesheet_employees(osv.osv_memory):
_name = 'hr.analytical.timesheet.users'
_description = 'Print Employees Timesheet'
_columns = {
'month': fields.selection([(1,'January'), (2,'February'), (3,'March'), (4,'April'),
... |
# -*- coding: utf-8 -*-
import unittest
from castle.cms import trash
from castle.cms.interfaces import ITrashed
from castle.cms.testing import CASTLE_PLONE_INTEGRATION_TESTING
from plone import api
from plone.app.testing import TEST_USER_ID
from plone.app.testing import TEST_USER_NAME
from plone.app.testing import log... |
import copy
from django.conf import settings
from django.test.utils import override_settings
import horizon
from openstack_dashboard.dashboards.admin.info import panel as info_panel
from openstack_dashboard.test import helpers as test
from openstack_dashboard.test.test_panels.plugin_panel \
import panel as plugi... |
import re
import time
import boto.exception
from oslo_log import log as logging
import testtools
from tempest import config
CONF = config.CONF
LOG = logging.getLogger(__name__)
def state_wait(lfunction, final_set=set(), valid_set=None):
# TODO(afazekas): evaluate using ABC here
if not isinstance(final_set,... |
from django.test import TestCase
from zerver.lib.initial_password import initial_password
from zerver.lib.db import TimeTrackingCursor
from zerver.lib import cache
from zerver.lib import event_queue
from zerver.worker import queue_processors
from zerver.lib.actions import (
check_send_message, create_stream_if_ne... |
# -*- coding: utf-8 -*-
import os, sys
import tempfile
import time
import logging
from subprocess import call
import numpy as np
import json
import uuid
import cv2
import csfm
from opensfm import context
logger = logging.getLogger(__name__)
def resized_image(image, config):
feature_process_size = config.get('... |
# MapLoop - asks ScanMaster to make a series of scans with one of the pg
# parameters incremented scan to scan
from DAQ.Environment import *
def aquireWithEFlip(numScans, start, stop, step):
# setup
fileSystem = Environs.FileSystem
# loop over voltages
l = range(int(10*start), int(10*stop), int(10*step))
for j i... |
import click
from alertaclient.utils import action_progressbar, build_query
@click.command('shelve', short_help='Shelve alerts')
@click.option('--ids', '-i', metavar='UUID', multiple=True, help='List of alert IDs (can use short 8-char id)')
@click.option('--query', '-q', 'query', metavar='QUERY', help='severity:"war... |
def print_n2(txt, num_of_times, num_of_times_fixed):
txt = txt.replace("\n", " ")
f = num_of_times_fixed #in this case equal to number of lines in msgbox
n = num_of_times #n is the number of times left to go
if num_of_times <= 0: #if all lines of txt are printed the bottom of msgbox is returned
... |
import logging
import re
import time
from lxml import html
from desktop.lib.view_util import format_duration_in_millis
from jobbrowser.models import format_unixtime_ms
LOGGER = logging.getLogger(__name__)
class Application:
def __init__(self, attrs):
for attr in attrs.keys():
setattr(self, attr, att... |
import sys
import unittest
from pyasn1.codec.der.decoder import decode as der_decoder
from pyasn1.codec.der.encoder import encode as der_encoder
from pyasn1.type import char
from pyasn1.type import univ
from pyasn1_modules import pem
from pyasn1_modules import rfc2986
from pyasn1_modules import rfc5280
class Certif... |
"""
Indexed corpus is a mechanism for random-accessing corpora.
While the standard corpus interface in gensim allows iterating over corpus with
`for doc in corpus: pass`, indexed corpus allows accessing the documents with
`corpus[docno]` (in O(1) look-up time).
This functionality is achieved by storing an extra file ... |
from ducktape.tests.test import Test
from kafkatest.services.zookeeper import ZookeeperService
from kafkatest.services.kafka import KafkaService
class KafkaTest(Test):
"""
Helper class that manages setting up a Kafka cluster. Use this if the
default settings for Kafka are sufficient for your test; any c... |
"""
This module houses the GEOSCoordSeq object, which is used internally
by GEOSGeometry to house the actual coordinates of the Point,
LineString, and LinearRing geometries.
"""
from ctypes import byref, c_double, c_uint
from django.contrib.gis.geos import prototypes as capi
from django.contrib.gis.geos.base import... |
#!/usr/bin/env python3
# Given two rectangular Earth images, day and night,
# generate a combined image for a given time.
import ephem
from ephem import cities
import math
from datetime import datetime, timezone, timedelta
from PIL import Image
import os, sys
# How many degrees wide should the blur zone be? BLUR is... |
"""
Model and functions related to blackbody radiation.
.. _blackbody-planck-law:
Blackbody Radiation
-------------------
Blackbody flux is calculated with Planck law
(:ref:`Rybicki & Lightman 1979 <ref-rybicki1979>`):
.. math::
B_{\\lambda}(T) = \\frac{2 h c^{2} / \\lambda^{5}}{exp(h c / \\lambda k T) - 1}
... |
# -*- coding: utf-8 -*-
import unittest
from nose.tools import * # noqa (PEP8 asserts)
from flask import Flask
from webtest_plus import TestApp
from framework.exceptions import HTTPError
from framework.routing import json_renderer, process_rules, Rule
def error_view():
raise HTTPError(400)
def error_with_msg()... |
import base64
import logging
import odoo
from werkzeug.exceptions import MethodNotAllowed, InternalServerError
from werkzeug.wrappers import Response
from odoo.addons.web.controllers.main import db_monodb
from odoo.addons.frepple.controllers.outbound import exporter
from odoo.addons.frepple.controllers.inbound import... |
"""
Validator for repeating items.
"""
from .api import NoDefault, Invalid
from .compound import CompoundValidator, from_python
__all__ = ['ForEach']
class ForEach(CompoundValidator):
"""
Use this to apply a validator/converter to each item in a list.
For instance::
ForEach(AsInt(), InList([1,... |
import pytest
import unittest
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import WebDriverException
class FormHandlingTests(unittest.TestCase):
def testShouldClickOnSubmitInputElements(self):
self._loadPage("formPage")
self.driver.find_element_by... |
#!/usr/bin/env python3
import sys
import os
import shutil
from subprocess import call
class PathUtilsException(RuntimeError):
def __init__(self, msg):
self._set_message(msg)
def _get_message(self):
return self._message
def _set_message(self, message):
self._message = message
... |
from functools import partial
import sys
if sys.version_info < (3, 4):
# FIXME: Remove `partialmethod` when dropping Python 3.3 support.
# Copied from Python 3.4.3 (/Lib/functools.py)
class partialmethod(object): # pragma: no cover
"""
Method descriptor with partial application of the give... |
import logging
from autotest.client.shared import error
def run_disable_win_update(test, params, env):
"""
This simply stop updates services in Windows guests.
:param test: QEMU test object
:param params: Dictionary with the test parameters
:param env: Dictionary with test environment.
"""
... |
"""Stub file to maintain backwards compatibility."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# pylint: disable=wildcard-import,unused-import,redefined-builtin
from tensorflow_estimator.python.estimator.tpu.tpu_estimator import *
# used by tests
from... |
"""
hostdev device support class(es)
http://libvirt.org/formatdomain.html#elementsHostDev
"""
import logging
from virttest.libvirt_xml.devices import base
from virttest.libvirt_xml import accessors
class Hostdev(base.TypedDeviceBase):
__slots__ = ('mode', 'hostdev_type', 'source_address',
'mana... |
# -*- coding: utf-8 -*-
from django.core.cache import cache
from django.utils.translation import ugettext_lazy as _
from cms.menu_bases import CMSAttachMenu
from menus.base import NavigationNode
from menus.menu_pool import menu_pool
from cms_content.settings import ROOT_URL
from cms_content.models import CMSMenuID, ... |
"""
Collection of CRC models. This module contains the CRC models known to pycrc.
To print the parameters of a particular model:
import pycrc.models as cm
models = cm.CrcModels()
print(", ".join(models.names()))
m = models.get_params("crc-32")
if m != None:
print("Width: {width:d}"... |
#! /usr/bin/env python2.5
# -*- coding: latin-1 -*-
import axiom_rules
import fact_groups
import instantiate
import pddl
import sas_tasks
import simplify
# TODO: The translator may generate trivial derived variables which are always true,
# for example if there ia a derived predicate in the input that only depends on... |
"""Tests for tensorflow.ops.random_ops.random_gamma."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import numpy as np
from six.moves import xrange # pylint: disable=redefined-builtin
from tensorflow.python.framework import dtypes
from te... |
import json
import errno
import socket
class QMPError(Exception):
pass
class QMPConnectError(QMPError):
pass
class QMPCapabilitiesError(QMPError):
pass
class QEMUMonitorProtocol:
def __init__(self, address, server=False):
"""
Create a QEMUMonitorProtocol class.
@param addres... |
from xmlrpclib import Fault
import types
import XendClient
class XendInvalidDomain(Fault):
def __init__(self, value):
Fault.__init__(self, XendClient.ERROR_INVALID_DOMAIN, value)
class XendError(Fault):
def __init__(self, value):
Fault.__init__(self, XendClient.ERROR_GENERIC, value)
... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
from ansible.module_utils.basic import AnsibleModule
import time
try:
import pan.xapi
HAS_LIB = True
except ImportError:
HAS_LIB = False
def check_jobs(jobs, module... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.