content stringlengths 4 20k |
|---|
"""
The library should be able to handle networks without any weight:
>>> n1= buildNonGravityNet(False)
>>> n1.paramdim
0
>>> n1.activate([0.2,0.4])[0]
1.289...
>>> n1.activate([0.2,0.4])[0]
1.289...
Now let's verify the recurrent one as well:
>>> n2= buildNonGravityNet(True)
>>>... |
"""SCons.Tool.fortran
Tool-specific initialization for a generic Posix f77/f90 Fortran compiler.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 20... |
"""Unit test for the gtest_xml_output module"""
__author__ = '<EMAIL> (Sean Mcafee)'
import datetime
import errno
import os
import re
import sys
from xml.dom import minidom, Node
import gtest_test_utils
import gtest_xml_test_utils
GTEST_FILTER_FLAG = '--gtest_filter'
GTEST_LIST_TESTS_FLAG = '--gtest_list_tests'
GT... |
import math
def pixels_to_EMU(value):
return int(round(value * 9525))
def EMU_to_pixels(value):
if not value:
return 0
else:
return round(value / 9525.)
def EMU_to_cm(value):
if not value:
return 0
else:
return (EMU_to_pixels(value) * 2.57 / 96)
def pixels_to_po... |
"""Kytos Buffer Classes, based on Python Queue."""
import logging
# from queue import Queue
from janus import Queue
from kytos.core.events import KytosEvent
__all__ = ('KytosBuffers', )
LOG = logging.getLogger(__name__)
class KytosEventBuffer:
"""KytosEventBuffer represents a queue to store a set of KytosEven... |
"""
===================================================
Lasso model selection: Cross-Validation / AIC / BIC
===================================================
Use the Akaike information criterion (AIC), the Bayes Information
criterion (BIC) and cross-validation to select an optimal value
of the regularization paramet... |
from django.contrib.sessions.models import Session
from django.dispatch import receiver
from django.utils.translation import ugettext as _
from account.models import EmailAddress
from account.signals import email_confirmation_sent, password_changed, user_signed_up
from board.models import Board, Notification
from boar... |
from sklearn.feature_extraction import DictVectorizer
from seldon.pipeline.pandas_pipelines import BasePandasEstimator
from collections import OrderedDict
import io
from sklearn.utils import check_X_y
from sklearn.utils import check_array
from sklearn.base import BaseEstimator,ClassifierMixin
import pandas as pd
clas... |
"""
Miscellany of text-munging functions.
"""
import string, types
from twisted.python import deprecate, versions
def stringyString(object, indentation=''):
"""
Expansive string formatting for sequence types.
list.__str__ and dict.__str__ use repr() to display their
elements. This function also tu... |
from unittest import mock
import os
import platform
import subprocess
import sys
import tempfile
import unittest
import warnings
from test import support
class PlatformTest(unittest.TestCase):
def test_architecture(self):
res = platform.architecture()
@support.skip_unless_symlink
def test_archite... |
#!/usr/bin/env python3
import os
from distutils.core import setup
from setuptools import find_packages
import okapi
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
README = read('README.rst')
CHANGES = read('CHANGES.rst')
setup(
name='tz-okapi',
version=okapi.__ver... |
# coding: spec
from harpoon.errors import BadOptionFormat, NoSuchEnvironmentVariable
from harpoon.formatter import MergedOptionStringFormatter
from tests.helpers import HarpoonCase
from delfick_project.errors_pytest import assertRaises
from delfick_project.option_merge import MergedOptions
from delfick_project.norms... |
# coding: utf-8
"""
Provides a class to customize template information on a per-view basis.
To customize template properties for a particular view, create that view
from a class that subclasses TemplateSpec. The "spec" in TemplateSpec
stands for "special" or "specified" template information.
"""
class TemplateSpec... |
from __future__ import absolute_import, division, print_function
import datetime
import json
import appr.semver
from appr.exception import (PackageAlreadyExists, PackageNotFound, ResourceNotFound,
raise_channel_not_found, raise_package_not_found)
DEFAULT_LOCK_TIMEOUT = 3
class ModelsInd... |
__all__ = ['JobTask', 'Queue']
import tacticenv
from pyasm.security import Batch
from pyasm.common import Common, Config, Container, Environment, jsonloads, jsondumps, TacticException
from pyasm.biz import Project
from pyasm.search import Search, SearchType, DbContainer, Transaction
from pyasm.command import Command
... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import re
import codecs
# Decode escapes adapted from rspeer's answer here:
# http://stackoverflow.com/questions/4020539/process-escape-sequences-in-a-string-in-python
_HEXCHAR = '[a-fA-F0-9]'
_ESCAPE_SEQUENCE_RE = re.compile(r'''... |
"""CLI tool for downloading results from Shippable CI runs."""
from __future__ import print_function
# noinspection PyCompatibility
import argparse
import json
import os
import re
import requests
try:
import argcomplete
except ImportError:
argcomplete = None
def main():
"""Main program body."""
api... |
"""scons.Node.Alias
Alias nodes.
This creates a hash of global Aliases (dummy targets).
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation fil... |
#!/home/pi/.venv/jns/bin/python
#
# last modified 2019/05/26
#
# Python helper script to download Julia 1.1.0 binaries
# not meant to be executed manually
# https://stackoverflow.com/questions/38511444/python-download-files-from-google-drive-using-url
#
FILE_ID = '1fj6pNAJgmUD7bsSXqh8ocC1wESx8jkRh'
DESTINATION = './j... |
"""'with'-compliant StringIO implementation."""
import StringIO
class StringIO(StringIO.StringIO):
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
pass |
from __future__ import unicode_literals
import frappe
import smtplib
import _socket
from frappe.utils import cint
from frappe import _
def send(email, as_bulk=False):
"""send the message or add it to Outbox Email"""
if frappe.flags.mute_emails or frappe.conf.get("mute_emails") or False:
frappe.msgprint(_("Emails ... |
import os
import re
from uuid import UUID
from ansible.module_utils.six import text_type, binary_type
FINAL_STATUSES = ('ACTIVE', 'ERROR')
VOLUME_STATUS = ('available', 'attaching', 'creating', 'deleting', 'in-use',
'error', 'error_deleting')
CLB_ALGORITHMS = ['RANDOM', 'LEAST_CONNECTIONS', 'ROUND_R... |
from morsel.panda import *
from solid import Solid
from body import Body
from joint import Joint
from morsel.nodes.iterator import Iterator
from morsel.nodes.scene import Scene as Base
#-------------------------------------------------------------------------------
class Scene(Base):
def __init__(self, **kargs):
... |
import time
from nose.tools import eq_
from pyquery import PyQuery as pq
from kitsune.flagit.models import FlaggedObject
from kitsune.kbforums.models import Post, Thread
from kitsune.kbforums.tests import KBForumTestCase, thread, post as post_
from kitsune.sumo.urlresolvers import reverse
from kitsune.sumo.tests impo... |
#!"C:\Users\hog\Documents\Visual Studio 2010\Projects\ArdupilotMega\ArdupilotMega\bin\Debug\ipy.exe"
""" Test functions for fftpack.convolve, in particular
behaviour of callbacks.
This is present to assist in switching from f2py to fwrap,
to make sure results are the same. True results are derived
from running the tes... |
from sqlalchemy import Column, Text
from nova.db.sqlalchemy import api as db
from nova.db.sqlalchemy import types
from nova.db.sqlalchemy import utils
def upgrade(migrate_engine):
compute_nodes = utils.get_table(migrate_engine, 'compute_nodes')
host_ip = Column('host_ip', types.IPAddress())
supported_ins... |
"""
Middleware that will provide Dynamic Large Object (DLO) support.
---------------
Using ``swift``
---------------
The quickest way to try out this feature is use the ``swift`` Swift Tool
included with the `python-swiftclient`_ library. You can use the ``-S``
option to specify the segment size to use when splittin... |
# -*- coding: utf-'8' "-*-"
import hashlib
import hmac
import logging
import time
import urlparse
from openerp import api, fields, models
from openerp.addons.payment.models.payment_acquirer import ValidationError
from openerp.addons.payment_authorize.controllers.main import AuthorizeController
from openerp.tools.floa... |
#!/usr/bin/env python
import datetime
import os
import shutil
import sys
import glob
from optparse import OptionParser
from subprocess import Popen, PIPE
from xhtml2pdf import pisa
def render_pdf(filename, output_dir, options):
if options.debug:
print 'Rendering %s' % filename
basename = os.path.base... |
from shinken_test import *
class TestReactionnerTagGetNotifs(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/nagios_reactionner_tag_get_notif.cfg')
# For a service, we generate a notification and a event handler.
# Each one got a specific reactionner_tag that we will look for.
def te... |
"""
Import-map configuration.
"""
import logging
from ryu.services.protocols.bgp.api.base import register
from ryu.services.protocols.bgp.core_manager import CORE_MANAGER
from ryu.services.protocols.bgp.core_managers.import_map_manager\
import ImportMapAlreadyExistsError
from ryu.services.protocols.bgp.rtconf.bas... |
"""
Test the conversion to/from astropy.table
"""
# TEST_UNICODE_LITERALS
import io
import os
import numpy as np
from ....utils.data import get_pkg_data_filename, get_pkg_data_fileobj
from ..table import parse, writeto
from .. import tree
def test_table(tmpdir):
# Read the VOTABLE
votable = parse(
... |
"""
Caching framework.
This package defines set of cache backends that all conform to a simple API.
In a nutshell, a cache is a set of values -- which can be any object that
may be pickled -- identified by string keys. For the complete API, see
the abstract BaseCache class in django.core.cache.backends.base.
Client ... |
# -*- coding: utf-8 -*-
import copy
import numbers
import numpy as np
from .instrument import save_instrument
from .loaders import DcsMslice, Grasp, Ice, Icp, Mad, Neutronpy, Spice
def load_data(files, filetype='auto', tols=1e-4, build_hkl=True, load_instrument=False):
r"""Loads one or more files and creates a ... |
from __future__ import unicode_literals
from django.test import TestCase
from django.test.utils import override_settings
from ..models import UrlArticle
@override_settings(ROOT_URLCONF='view_tests.urls')
class DefaultsTests(TestCase):
"""Test django views in django/views/defaults.py"""
fixtures = ['testdata... |
"""Freeze a model to a GraphDef proto."""
from absl import app, flags
import dual_net
flags.DEFINE_string('model_path', None, 'Path to model to freeze')
flags.DEFINE_integer('trt_batch', 0, 'Batch to freeze model to TRT graph')
flags.mark_flag_as_required('model_path')
FLAGS = flags.FLAGS
def main(unused_argv):
... |
# -*- coding: utf-8 -*-
from openerp.tests import common
class test_inherits(common.TransactionCase):
def test_create_3_levels_inherits(self):
""" Check that we can create an inherits on 3 levels """
pallet = self.env['test.pallet'].create({
'name': 'B',
'field_in_box': 'b... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'core'}
DOCUMENTATION = r'''
---
module: win_ping
version_added: "1.7"
short_description: A windows version of the classic ping module
description:
- Checks management connectivity of... |
from tests import unittest
from watchdog.utils.bricks import SkipRepeatsQueue
class TestSkipRepeatsQueue(unittest.TestCase):
def test_basic_queue(self):
q = SkipRepeatsQueue()
e1 = (2, 'fred')
e2 = (2, 'george')
e3 = (4, 'sally')
q.put(e1)
q.put(e2)
q.put... |
"""Applies online refinement while running inference.
Instructions: Run static inference first before calling this script. Make sure
to point output_dir to the same folder where static inference results were
saved previously.
For example use, please refer to README.
"""
from __future__ import absolute_import
from __... |
#!/usr/bin/env python
from __future__ import absolute_import, print_function
import os
# if PAPARAZZI_HOME not set, then assume the tree containing this
# file is a reasonable substitute
PPRZ_HOME = os.getenv("PAPARAZZI_HOME", os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)),
... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'core'}
# FIXME: standardize into module_common
from traceback import format_exc
from ansible.module_util... |
import os
from collections import OrderedDict
from django.apps import apps
from django.conf import settings
from django.contrib.staticfiles import utils
from django.core.exceptions import ImproperlyConfigured
from django.core.files.storage import (
FileSystemStorage, Storage, default_storage,
)
from django.utils i... |
"""Imposter encodings module that installs a coverage-style tracer.
This is NOT the encodings module; it is an imposter that sets up tracing
instrumentation and then replaces itself with the real encodings module.
If the directory that holds this file is placed first in the PYTHONPATH when
using "coverage" to run Pyt... |
"""
These classes are light wrappers around Django's database API that provide
convenience functionality and permalink functions for the databrowse app.
"""
from __future__ import unicode_literals
from django.db import models
from django.utils import formats
from django.utils.text import capfirst
from django.utils.enc... |
from django.conf.urls import patterns, include, url
from django.conf import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'Creamas.views.home', name='home'),
# url(r'^Creamas/', include... |
import warnings
import unittest
import sys
from nose.tools import assert_raises
from sklearn.utils.testing import (
_assert_less,
_assert_greater,
assert_less_equal,
assert_greater_equal,
assert_warns,
assert_no_warnings,
assert_equal,
set_random_state,
assert_raise_message)
from ... |
import abc
class LogDB(object):
"""Database interface for storing client-side CT data."""
__metaclass__ = abc.ABCMeta
# The largest BSON can handle
timestamp_max = 2**63-1
@abc.abstractmethod
def add_log(self, metadata):
"""Store log metadata. This creates the necessary mappings betwe... |
from enum import Enum
import logging
from ..address_translator import AT
l = logging.getLogger(name=__name__)
class SymbolType(Enum):
"""
ABI-agnostic symbol types
"""
TYPE_OTHER = 0
TYPE_NONE = 1
TYPE_FUNCTION = 2
TYPE_OBJECT = 3
TYPE_SECTION = 4
TYPE_TLS_OBJECT = 5
class Symb... |
import requests
from lxml import etree
from cloudbot import hook
from cloudbot.util import formatting
# security
parser = etree.XMLParser(resolve_entities=False, no_network=True)
API_URL = "http://steamcommunity.com/id/{}/"
ID_BASE = 76561197960265728
headers = {}
class SteamError(Exception):
pass
def conve... |
import socket
try:
from select import poll, POLLIN
except ImportError: # `poll` doesn't exist on OSX and other platforms
poll = False
try:
from select import select
except ImportError: # `select` doesn't exist on AppEngine.
select = False
def is_connection_dropped(conn): # Platform-... |
"""
OpenNetMon.Forwarding
Requires openflow.discovery
"""
from pox.lib.revent.revent import EventMixin, Event
from pox.lib.addresses import IPAddr
from pox.lib.packet.vlan import vlan
from pox.lib.packet.ipv4 import ipv4
import pox.lib.util as util
from pox.core import core
import pox.openflow.libopenflow_01 as of
... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
try:
import shade
HAS_SHADE = True
except ImportError:
HAS_SHADE = False
from distutils.version import StrictVersion
def _present_volume(module, cloud):
if clou... |
import unittest
import paddle.fluid as fluid
import paddle.fluid.layers as layers
import paddle.fluid.framework as framework
import paddle.fluid.optimizer as optimizer
from paddle.fluid.backward import calc_gradient
class TestCalcGradient(unittest.TestCase):
def test_calc_gradient(self):
x = layers.creat... |
import gc
import sys
import time
import unittest
import weakref
from types import TracebackType
from django.dispatch import Signal, receiver
if sys.platform.startswith('java'):
def garbage_collect():
# Some JVM GCs will execute finalizers in a different thread, meaning
# we need to wait for that t... |
"""SCons.Tool.dvi
Common DVI Builder definition for various other Tool modules that use it.
"""
#
# Copyright (c) 2001 - 2014 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the ... |
"""Detect Thermos tasks on disk
This module contains the TaskDetector, used to detect Thermos tasks within a given checkpoint root.
"""
import functools
import glob
import os
import re
from abc import abstractmethod
from twitter.common.lang import Compatibility, Interface
from apache.thermos.common.constants impor... |
"""Interface Verify tests
"""
import doctest
import unittest
from zope.interface import Interface, implements, classImplements, Attribute
from zope.interface.verify import verifyClass, verifyObject
from zope.interface.exceptions import DoesNotImplement, BrokenImplementation
from zope.interface.exceptions import Broken... |
# Simple example presenting how persistent ID can be used to pickle
# external objects by reference.
import pickle
import sqlite3
from collections import namedtuple
# Simple class representing a record in our database.
MemoRecord = namedtuple("MemoRecord", "key, task")
class DBPickler(pickle.Pickler):
def persi... |
"""Session Handling for SQLAlchemy backend."""
from oslo_config import cfg
from oslo_db.sqlalchemy import session
from oslo_log import log as logging
LOG = logging.getLogger(__name__)
CONF = cfg.CONF
_FACADES = {}
def _create_facade_lazily(cfg_group, connection=None, discriminator=None):
connection = connec... |
import unittest2 as unittest
from saltmeter import utils
class TestUtils(unittest.TestCase):
def test_execute(self):
u = utils.Utils()
result = u.execute('ls')
self.assertTrue(result)
def test_execute_invalid_command(self):
u = utils.Utils()
result = u.execute('invali... |
import shmooze.lib.service as service
import shmooze.settings as settings
import os
import signal
import math
try:
import alsaaudio
except:
alsaaudio = None
try:
import osax
except:
osax = None
exp=0.6 # approximate
def human_to_computer(val):
return int(100*(float(val)/100)**exp)
def computer_to_... |
# Tests for rich comparisons
from test_support import TestFailed, verify, verbose
class Number:
def __init__(self, x):
self.x = x
def __lt__(self, other):
return self.x < other
def __le__(self, other):
return self.x <= other
def __eq__(self, other):
return self.x ==... |
from openerp.osv import fields, osv
class sale_configuration(osv.osv_memory):
_inherit = 'sale.config.settings'
_columns = {
'group_template_required': fields.boolean("Mandatory use of templates.",
implied_group='account_analytic_analysis.group_template_required',
help="Allows ... |
#!/usr/bin/env python
from __future__ import print_function
import sys
from os import path, getenv
# if PAPARAZZI_SRC not set, then assume the tree containing this
# file is a reasonable substitute
PPRZ_SRC = getenv("PAPARAZZI_SRC", path.normpath(path.join(path.dirname(path.abspath(__file__)), '../../../')))
sys.pat... |
import sys
import unittest
from test.test_support import run_unittest, have_unicode
import math
L = [
('0', 0),
('1', 1),
('9', 9),
('10', 10),
('99', 99),
('100', 100),
('314', 314),
(' 314', 314),
('314 ', 314),
(' \t\t 314 \t\t ', ... |
from nova.api.openstack.compute.contrib import used_limits
from nova.api.openstack.compute import limits
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
import nova.context
from nova import exception
from nova import quota
from nova import test
class FakeRequest(object):
def __init__... |
from google.appengine.dist import use_library
use_library('django', '1.1')
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from handlers.dashboard import Dashboard
from handlers.gc import GC
from handlers.nextpatch import NextPatch
from handlers.patch import Patch
fro... |
"""
Base file upload handler classes, and the built-in concrete subclasses
"""
from __future__ import unicode_literals
from io import BytesIO
from django.conf import settings
from django.core.files.uploadedfile import (
InMemoryUploadedFile, TemporaryUploadedFile,
)
from django.utils.encoding import python_2_uni... |
import os
import sys
import pwd
import socket
import subprocess
def get_sysinfo(nonce='00000000'):
# NOTE: requires global variable "server" to be set
# nonce | listener | domainname | username | hostname | internal_ip | os_details | os_details | high_integrity | process_name | process_id | language | languag... |
import gc
import io
import os
import sys
import signal
import weakref
import unittest
@unittest.skipUnless(hasattr(os, 'kill'), "Test requires os.kill")
@unittest.skipIf(sys.platform =="win32", "Test cannot run on Windows")
class TestBreak(unittest.TestCase):
int_handler = None
def setUp(self):
self... |
from oslo_policy import policy
from mistral.policies import base
WORKBOOKS = 'workbooks:%s'
rules = [
policy.DocumentedRuleDefault(
name=WORKBOOKS % 'create',
check_str=base.RULE_ADMIN_OR_OWNER,
description='Create a new workbook.',
operations=[
{
'path... |
"""DAG run APIs."""
from datetime import datetime
from typing import Dict
from airflow.api.common.experimental import check_and_get_dag, check_and_get_dagrun
def get_dag_run_state(dag_id: str, execution_date: datetime) -> Dict[str, str]:
"""Return the task object identified by the given dag_id and task_id.
... |
import os
if os.name == 'posix':
hiddenimports = ['libvtkCommonPython','libvtkFilteringPython','libvtkIOPython','libvtkImagingPython','libvtkGraphicsPython','libvtkRenderingPython','libvtkHybridPython','libvtkParallelPython','libvtkPatentedPython']
else:
hiddenimports = ['vtkCommonPython','vtkFilteringPython','... |
"""Field handler classes.
The field handlers are meant to parse information from or do some other generic
action for a specific field type for the build_api script.
"""
from __future__ import print_function
import contextlib
import functools
import os
import shutil
import sys
from google.protobuf import message as ... |
def main():
module = AnsibleModule(
argument_spec={
'name': {'required': True},
'state': {'default': 'present', 'choices': ['present', 'absent', 'probe']},
'params': {'default': ''},
},
supports_check_mode=True,
)
args = {
'changed': False,... |
from openerp.osv import fields, osv
class stock_picking(osv.osv):
_inherit = "stock.picking"
_columns = {
'analytic_account_ids': fields.related(
'move_lines', 'analytic_account_id', type='many2many',
relation='account.analytic.account', string='Analytic Account',
... |
import threading
import time
class PeriodicSaveThread(threading.Thread):
def __init__(self, main_area):
threading.Thread.__init__(self)
self.main_area = main_area
self.cancel = False
def run (self):
time.sleep (60)
while not self.cancel:
self.main_area.save... |
from __future__ import unicode_literals
import datetime
from django.db import models
from django.utils.translation import ugettext_lazy as _
try:
from django.utils.timezone import now
except ImportError: # Django < 1.4
now = datetime.datetime.now
class Timeline(models.Model):
"A series of milestones wh... |
"""Tests for VGG16 application."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python import keras
from tensorflow.python.platform import test
class VGG16Test(test.TestCase):
def test_with_top(self):
model = keras.applications.V... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
from ansible.module_utils.basic import AnsibleModule
def gather_lldp(module):
cmd = [... |
"""
Support for Sense Hat LEDs.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/light.sensehat/
"""
import logging
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.components.light import (
ATTR_BRIGHT... |
'''
Copyright (C) 2014 ddurdle
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.
This program is distrib... |
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import StringIO
import datetime as dt
import random
import logging
import md5
import boto3
from flask import Flask, request, send_file, redirect, url_for, jsonify, render_template_string
from flask.json import JSONEncoder
from raven.contrib.flask... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('auth', '0006_require_contenttypes_0002'),
('data_api', '0014_auto_20150901_1640'),
]
operations = [
migrations.Creat... |
import mock
import testtools
from dragonflow import conf as cfg
from dragonflow.switch.drivers.ovs import os_ken_base_app
from dragonflow.tests import base as tests_base
class TestOsKenDFAdapter(tests_base.BaseTestCase):
"""
This unit test has to verify that all events are called correctly, both
via the ... |
""" Class representing a single artillery piece. """
from math import sin
from math import cos
from math import radians
from math import floor
EXIT_VELOCITY = 120
GRAVITY = 9.8
DEFAULT_ELEVATION = 45
DEFAULT_AZIMUTH = 45
DEFAULT_AMMO = 10
class Gun(object):
""" Class for representing a particular artillery piece... |
from django import http
from django.conf import settings
class XViewMiddleware(object):
"""
Adds an X-View header to internal HEAD requests -- used by the documentation system.
"""
def process_view(self, request, view_func, view_args, view_kwargs):
"""
If the request method is HEAD and... |
from __future__ import unicode_literals, division, absolute_import
from builtins import * # noqa pylint: disable=unused-import, redefined-builtin
import logging
import re
from flexget import plugin
from flexget.event import event
from flexget.components.sites.urlrewriting import UrlRewritingError
from flexget.utils.... |
import gen_utils
from module_base import ModuleBase
from module_mixins import NoConfigModuleMixin
import module_utils
import vtktud
class imageCurvature(ModuleBase, NoConfigModuleMixin):
"""Calculates image curvature with VTKTUD vtkImageCurvature filter.
You need 8 inputs, and in the following sequence: d... |
import imp
import os
import sys
from spec import Spec, eq_, raises
from invoke.loader import Loader, FilesystemLoader as FSLoader
from invoke.collection import Collection
from invoke.exceptions import CollectionNotFound
from _util import support
class _BasicLoader(Loader):
"""
Tests top level Loader behavi... |
from django import forms
# import autocomplete_light
from .models import Organisation, User
class OrganisationForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(OrganisationForm, self).__init__(*args, **kwargs)
class Meta:
model = Organisation
exclude = ('user', 'cre... |
"""Local Postgres plugin."""
import gettext
from otopi import plugin, util
from ovirt_engine_setup import constants as osetupcons
from ovirt_engine_setup import dialog
from ovirt_engine_setup.engine import constants as oenginecons
from ovirt_engine_setup.engine_common import constants as oengcommcons
from ovirt_eng... |
import base64
from django.core import validators
from django.db import models
from django.utils.translation import ugettext_lazy as _
import floppyforms as forms
from misago.utils.timezones import tzlist
try:
import cPickle as pickle
except ImportError:
import pickle
class Setting(models.Model):
setting = ... |
"""MySQLdb Cursors
This module implements Cursors of various types for MySQLdb. By
default, MySQLdb uses the Cursor class.
"""
import re
import sys
from _mysql_exceptions import Warning, Error, InterfaceError, DataError, \
DatabaseError, OperationalError, IntegrityError, InternalError, \
NotSupp... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
def function():
return "pineapple"
def function2():
return "tractor"
class Class:
def method(self):
return "parrot"
class AboutMethodBindings(Koan):
def test_methods_are_bound_to_an_object(self):
obj = Class()
... |
import sys
sys.path[0:0] = [""]
import unittest
from bson import ObjectId
from datetime import datetime
from mongoengine import *
from mongoengine.queryset import Q
from mongoengine.errors import InvalidQueryError
__all__ = ("QTest",)
class QTest(unittest.TestCase):
def setUp(self):
connect(db='mongo... |
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRequest, HttpResponse
from azure.mgmt.cor... |
"""Runs the specified tests for Google Test.
This script requires Python 2.3 or higher. To learn the usage, run it
with -h.
"""
import os
import sys
SCRIPT_DIR = os.path.dirname(__file__) or '.'
sys.path.append(os.path.join(SCRIPT_DIR, 'test'))
import run_tests_util
def _Main():
"""Runs all tests for Google Te... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
***************************************... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.