content stringlengths 4 20k |
|---|
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
import base64
import json
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import ... |
from __future__ import print_function
import os
import sys
from command import PagedCommand
class Manifest(PagedCommand):
common = False
helpSummary = "Manifest inspection utility"
helpUsage = """
%prog [-o {-|NAME.xml} [-r]]
"""
_helpDescription = """
With the -o option, exports the current manifest for ins... |
from org.eclipse.draw2d import MouseMotionListener
from org.eclipse.draw2d import FigureCanvas
from org.eclipse.draw2d import Panel
from org.eclipse.draw2d import Figure
from org.eclipse.draw2d import XYLayout
from org.eclipse.swt.widgets import Display;
from org.eclipse.swt.widgets import Shell;
from org.eclipse.draw2... |
from UnitTest import UnitTest
import time
from write import write, writebr
class A(object):
def __init__(self, x):
self.x = x
def getX(self):
return self.x
def fib(n):
if n<3.0:
return 1.0
return fib(n-2.0)+fib(n-1.0)
def int_fib(n):
if n<3:
return 1
return i... |
from os.path import join, dirname
from typing import Callable, Dict, Tuple, Union, Type
import numpy as np
from numpy.testing import (
assert_array_almost_equal, assert_equal, assert_allclose)
import pytest
from pytest import raises as assert_raises
from scipy.fft._pocketfft.realtransforms import (
dct, idct,... |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
# system imports
import unittest
# third-party library imports
from mantid.py3compat.mock import MagicMock, PropertyMock, call, patch
from mantidqt.plotting.figuretype import FigureType
from qtpy.QtCore import... |
"""Tests for tensorflow.ops.math_ops.matrix_inverse."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes as dtypes_lib
from tensorflow.pyth... |
def execute_config_command(commands, module):
try:
module.configure(commands)
except ShellError, clie:
module.fail_json(msg='Error sending CLI commands',
error=str(clie), commands=commands)
def get_cli_body_ssh(command, response):
"""Get response for when transport... |
import github.GithubObject
class GitTreeElement(github.GithubObject.NonCompletableGithubObject):
"""
This class represents GitTreeElements as returned for example by http://developer.github.com/v3/todo
"""
@property
def mode(self):
"""
:type: string
"""
return self... |
from neutron.api.v2 import attributes
from neutron.common import constants
from neutron.common import exceptions as n_exc
from neutron import context
from neutron import manager
from neutron.tests.unit import test_db_plugin
from neutron.tests.unit import testlib_api
from neutron.tests.unit import testlib_plugin
class... |
import os
from subprocess import PIPE, STDOUT, Popen
from tempfile import NamedTemporaryFile, TemporaryDirectory, gettempdir
from airflow.sensors.base_sensor_operator import BaseSensorOperator
from airflow.utils.decorators import apply_defaults
class BashSensor(BaseSensorOperator):
"""
Executes a bash comman... |
from openerp import models, fields, api
class ResPartner(models.Model):
_inherit = 'res.partner'
@api.one
@api.depends('company_credit_limit', 'insurance_credit_limit')
def _credit_limit(self):
self.credit_limit = (self.company_credit_limit +
self.insurance_credit... |
"""
Defines a OptNode and OptGraph to be used by OptimizerBase subclasses.
Together they define the path of one or more optimizations and can be used to
store and replay optimization history.
"""
import copy
class OptNode:
"""
Node as the result of an optimization.
Attributes
----------
parameter... |
import sys
from django.conf import settings
from django.db.backends.base.creation import BaseDatabaseCreation
from django.db.utils import DatabaseError
from django.utils.crypto import get_random_string
from django.utils.functional import cached_property
TEST_DATABASE_PREFIX = 'test_'
class DatabaseCreation(BaseData... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
import re
# import module snippets
from ansible.module_utils.basic import AnsibleModule
... |
from setuptools import setup, find_packages
import os
import os.path as osp
def get_version():
"""Get version from source file"""
import codecs
with codecs.open("spyder_memory_profiler/__init__.py", encoding="utf-8") as f:
lines = f.read().splitlines()
for l in lines:
if "__ver... |
import torch
from tests.common import assert_equal
from pyro.contrib.timeseries import GenericLGSSM, GenericLGSSMWithGPNoiseModel
import pytest
@pytest.mark.parametrize('model_class', ['lgssm', 'lgssmgp'])
@pytest.mark.parametrize('state_dim', [2, 3])
@pytest.mark.parametrize('obs_dim', [2, 4])
@pytest.mark.parametr... |
# -*- coding: utf-8 -*-
from south.db import db
from south.v2 import SchemaMigration
class Migration(SchemaMigration):
depends_on = (
('projects', '0014_move_projects'),
)
def forwards(self, orm):
# Adding field 'ProjectApplication.project_tmp'
db.add_column('applications_project... |
import datetime
import sys
from pyspark.sql import Row
from pyspark.sql.functions import udf, input_file_name
from pyspark.testing.sqlutils import ReusedSQLTestCase
class FunctionsTests(ReusedSQLTestCase):
def test_explode(self):
from pyspark.sql.functions import explode, explode_outer, posexplode_outer... |
from django.contrib.auth.models import User
from django.http import Http404
from rest_framework import serializers
from openedx.core.djangoapps.course_groups.cohorts import is_course_cohorted
from notification_prefs import NOTIFICATION_PREF_KEY
from lang_pref import LANGUAGE_KEY
class NotifierUserSerializer(serializ... |
from openerp.osv import osv,fields
class company(osv.osv):
_inherit = 'res.company'
_columns = {
'manufacturing_lead': fields.float('Manufacturing Lead Time', required=True,
help="Security days for each manufacturing operation."),
}
_defaults = {
'manufacturing_lead': lambda... |
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
import re
decimal_point = re.compile(r"(\d+)")
def mkversion(major, minor, patch):
return (1000 * 1000 * int(major)) + (1000 * int(minor)) + int(patch)
def parse_lvs(data):
lvs =... |
"""
synaptiks._bindings.xinput
==========================
ctypes-based libXi binding.
.. moduleauthor:: Sebastian Wiesner <<EMAIL>>
"""
from __future__ import (print_function, division, unicode_literals,
absolute_import)
from ctypes import (POINTER, Structure, byref, string... |
from datetime import datetime
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
import django.forms as forms
from main.support import ac
from streamjar.models import Streamja... |
from rest_framework import permissions
from api.base.utils import assert_resource_type, get_user_auth
from osf.utils.permissions import MANAGE
from osf.models import OSFGroup, OSFUser
class IsGroupManager(permissions.BasePermission):
acceptable_models = (OSFGroup,)
def has_object_permission(self, request, ... |
"""
Copyright (c) 2011, 2012, Regents of the University of California
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this l... |
"""Abstract base classes related to import."""
from . import _bootstrap
from . import machinery
try:
import _frozen_importlib
except ImportError as exc:
if exc.name != '_frozen_importlib':
raise
_frozen_importlib = None
import abc
import imp
import marshal
import sys
import tokenize
im... |
"""Utilities for configuring IP address forwarding."""
import logging
import os
import re
try:
import netifaces
except ImportError:
netifaces = None
MAC_REGEX = re.compile(r'\A([0-9A-Fa-f]{2}[:]){5}([0-9A-Fa-f]{2})\Z')
class NetworkUtils(object):
"""System network Ethernet interface utilities."""
def __in... |
"""Worksheet is the 2nd-level container in Excel."""
# Python stdlib imports
import re
# package imports
from . import cell
from .cell import coordinate_from_string, \
column_index_from_string, get_column_letter
from .shared.exc import SheetTitleException, \
InsufficientCoordinatesException, CellCoordinatesEx... |
"""
Use this module to get and run all tk tests.
Tkinter tests should live in a package inside the directory where this file
lives, like test_tkinter.
Extensions also should live in packages following the same rule as above.
"""
import os
import sys
import unittest
import importlib
import test.test_support
this_dir_... |
"""Ftrl-proximal for TensorFlow."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import ops
from tensorflow.python.ops import math_ops
from tensorflow.python.training imp... |
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpR... |
from neutron.common import constants
from neutron.extensions import portbindings
from neutron.plugins.ml2.drivers.macvtap.mech_driver import mech_macvtap
from neutron.tests.unit.plugins.ml2 import _test_mech_agent as base
class MacvtapMechanismBaseTestCase(base.AgentMechanismBaseTestCase):
VIF_TYPE = portbindings... |
from setuptools import setup
import simple_history
tests_require = [
'Django>=1.6', 'WebTest==2.0.24', 'django-webtest==1.8.0', 'mock==1.0.1']
setup(
name='django-simple-history',
version=simple_history.__version__,
description='Store model history and view/revert changes from admin site.',
long_d... |
from test_framework.test_framework import ComparisonTestFramework
from test_framework.util import *
from test_framework.comptool import TestManager, TestInstance
from test_framework.mininode import *
from test_framework.blocktools import *
import logging
import copy
import time
'''
In this test we connect to one node... |
from base64 import b64encode
from datetime import timedelta
import httplib
import json
import os.path
import re
import urllib2
from couchpotato.core._base.downloader.main import DownloaderBase, ReleaseDownloadList
from couchpotato.core.helpers.encoding import isInt, sp
from couchpotato.core.helpers.variable import try... |
"""Tests for DC optimal power flow using PIPS solver.
"""
from os.path import dirname, join
from numpy import array, ones, Inf, arange, r_
from scipy.io import loadmat
from scipy.sparse import csr_matrix as sparse
from pypower.ppoption import ppoption
from pypower.rundcopf import rundcopf
from pypower.loadcase impo... |
from __future__ import absolute_import
from celery import current_task
from celery.utils.log import get_task_logger
from cloudmesh.iaas.openstack.queue.celery import celery_openstack_queue
from cloudmesh.cm_mongo import cm_mongo
import time
#
# logger = get_task_logger(__name__)
#
@celery_openstack_queue.task(track_... |
import os
import sys
import random
import unittest
sys.path.insert(1, os.path.abspath(os.path.join(__file__, "../..")))
import base_test
repo_root = os.path.abspath(os.path.join(__file__, "../../.."))
sys.path.insert(1, os.path.join(repo_root, "tools", "webdriver"))
from webdriver import exceptions
class WindowSizeT... |
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
from ansible.module_utils.openstack im... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.conf import settings
import xmodule_django.models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations ... |
# -*- coding: utf-8 -*-
r"""
werkzeug.posixemulation
~~~~~~~~~~~~~~~~~~~~~~~
Provides a POSIX emulation for some features that are relevant to
web applications. The main purpose is to simplify support for
systems such as Windows NT that are not 100% POSIX compatible.
Currently this only imple... |
"""Unit test for plural3.py
This program is part of "Dive Into Python", a free Python book for
experienced programmers. Visit http://diveintopython.org/ for the
latest version.
"""
__author__ = "Mark Pilgrim (<EMAIL>)"
__version__ = "$Revision: 1.2 $"
__date__ = "$Date: 2004/03/17 14:34:40 $"
__copyright__ = "Copyri... |
"""Miscellaneous utility functions."""
import contextlib
import datetime
import errno
import json
import os
import shutil
import subprocess
import sys
import tempfile
import time
# UTC datetime corresponding to zero Unix timestamp.
EPOCH = datetime.datetime.utcfromtimestamp(0)
def parse_rfc3339_epoch(value):
"""... |
import unittest as ut
import espressomd
import numpy as np
from espressomd.interactions import LennardJonesInteraction
if "LENNARD_JONES_GENERIC" in espressomd.features():
from espressomd.interactions import GenericLennardJonesInteraction
class Non_bonded_interactionsTests(ut.TestCase):
# def __init__(self,p... |
import base64
import urllib
from io import StringIO
import ujson
from django.conf import settings
from zerver.lib.test_classes import ZulipTestCase
from zerver.lib.test_helpers import (
create_s3_buckets,
get_test_image_file,
override_settings,
use_s3_backend,
)
from zerver.lib.upload import upload_ba... |
"""Allows dot-accessible dictionaries."""
class Bunch(dict):
def __init__(self, d):
dict.__init__(self, d)
self.__dict__.update(d)
# Converts any kind of variable to a Bunch
def to_bunch(var):
if isinstance(var, list):
return [to_bunch(i) for i in var]
if isinstance(var, dict):
ret = {}
f... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from .common import InfoExtractor
class HarkIE(InfoExtractor):
_VALID_URL = r'https?://www\.hark\.com/clips/(?P<id>.+?)-.+'
_TEST = {
'url': 'http://www.hark.com/clips/mmbzyhkgny-obama-beyond-the-afghan-theater-we-only-target-al-qaeda-on... |
import unittest2 as unittest
from webkitpy.common.system.outputcapture import OutputCapture
from webkitpy.tool.mocktool import MockOptions, MockTool
from webkitpy.tool.steps.closebugforlanddiff import CloseBugForLandDiff
class CloseBugForLandDiffTest(unittest.TestCase):
def test_empty_state(self):
capture... |
from unittest import mock
from taskplus.core.shared.request import RequestError
from taskplus.core.shared.response import ResponseFailure
from taskplus.core.shared.action import Action
def test_action_cannot_process_valid_requests():
request = mock.MagicMock()
request.__bool__.return_value = True
action... |
#!/usr/bin/env python
"""
setup.py file for SWIG example
"""
import sys
import os.path
def get_rootdir():
return ''
#return '/home/users/okazaki/local'
def get_includedir():
return os.path.join(get_rootdir(), 'include')
def get_librarydir():
return os.path.join(get_rootdir(), 'lib')
import os; os.en... |
import cPickle as pickle
import hashlib
import hmac
import os
from Crypto.Cipher import AES
class AuthenticationError(Exception):
pass
class Crypticle(object):
"""Authenticated encryption class
Encryption algorithm: AES-CBC
Signing algorithm: HMAC-SHA256
"""
PICKLE_PAD = "pickle::"
AES... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from urllib import unquote_plus
import urllib2
from django.db import models
from django.conf import settings
from django.http import QueryDict
from django.utils.http import urlencode
from vendor.paypal.standard.models import PayPalStandardBase
from vendor.paypal.standard.co... |
#!/usr/bin/env python
from distutils.core import setup
import os
from subprocess import check_output
driver_path = None
try:
cmd_output = check_output(
["/usr/bin/locate", "neutron_lbaas/drivers/brocade/driver_v2.py"]
)
if len(cmd_output) > 0:
path_guess = os.path.dirname(cmd_output.split(... |
# coding=utf-8
"""Reporting 101."""
import os
import unittest
from safe.common.utilities import safe_dir
from safe.definitions.constants import INASAFE_TEST
from safe.definitions.reports import (
jinja2_component_type,
final_product_tag,
table_product_tag,
html_product_tag)
from safe.impact_function.... |
import json
def main(request, response):
origin = request.GET.first("origin", request.headers.get('origin'))
if "check" in request.GET:
token = request.GET.first("token")
value = request.server.stash.take(token)
if value is not None:
if request.GET.first("check", None) == "... |
#!/usr/bin/env python
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=u... |
"""Fichier contenant le paramètre 'supprimer' de la commande 'chemin'."""
from primaires.interpreteur.masque.parametre import Parametre
class PrmSupprimer(Parametre):
"""Commande 'chemin supprimer'.
"""
def __init__(self):
"""Constructeur du paramètre"""
Parametre.__init__(self, "suppri... |
import json
from social.tests.backends.oauth import OAuth2Test
class SoundcloudOAuth2Test(OAuth2Test):
backend_path = 'social.backends.soundcloud.SoundcloudOAuth2'
user_data_url = 'https://api.soundcloud.com/me.json'
expected_username = 'foobar'
access_token_body = json.dumps({
'access_token'... |
"""Manage HTTP Response Headers
Much of this module is red-handedly pilfered from email.message in the stdlib,
so portions are Copyright (C) 2001,2002 Python Software Foundation, and were
written by Barry Warsaw.
"""
from types import ListType, TupleType
# Regular expression that matches `special' characters in para... |
import unittest
from unittest import skipIf
try:
from nio_cli.commands.buildrelease import BuildRelease
niocore_installed = True
except:
niocore_installed = False
class TestCLI(unittest.TestCase):
@skipIf(not niocore_installed, 'niocore required for buildrelease')
def test_buildrelease_git_remot... |
import pathlib
import re
import sqlite3
import time
from datetime import datetime, timedelta, tzinfo
from typing import List, Tuple
import discord
import pytz
from dateutil.tz import gettz
from pytz import reference
last = {}
delete = []
date_formats = [
"%d.%m.%y %H:%M:%S",
"%d.%m.%Y %H:%M:%S",
"%d.%m.%... |
import logging
lg = logging.getLogger('packet')
from pox.lib.util import initHelper
class packet_base (object):
"""
TODO: This description is somewhat outdated and should be fixed.
Base class for packets.
Classes that perform packet manipulation (parsing and contruction)
should derive from this ... |
from importlib import machinery
import imp
import unittest
from .. import abc
from .. import util
from test.support import captured_stdout
class LoaderTests(abc.LoaderTests):
def test_module(self):
with util.uncache('__hello__'), captured_stdout() as stdout:
module = machinery.FrozenImporter.l... |
###############################################################################
#
# domeval.py - functions to evaluate domain decomposition accuracy
#
# File: domeval.py
#
# $Id: domeval.py 3236 2010-01-13 02:06:50Z alexs $
#
###############################################################################
"""
Functi... |
import sys, os
import binascii
import hashlib
if sys.version_info.major == 3:
string_types = (str)
string_or_bytes_types = (str, bytes)
int_types = (int, float)
# Base switching
code_strings = {
2: '01',
10: '0123456789',
16: '0123456789abcdef',
32: 'abcdefghijklmno... |
from __future__ import absolute_import, division, unicode_literals
from pip._vendor.six import text_type
import re
from codecs import register_error, xmlcharrefreplace_errors
from .constants import voidElements, booleanAttributes, spaceCharacters
from .constants import rcdataElements, entities, xmlEntities
from . im... |
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
int_or_none,
unified_strdate,
unescapeHTML,
)
class UstudioIE(InfoExtractor):
IE_NAME = 'ustudio'
_VALID_URL = r'https?://(?:(?:www|v1)\.)?ustudio\.com/video/(?P<id>[^/]+)/(?P<display_id>[^/... |
"""
=========================================
Segmenting the picture of Lena in regions
=========================================
This example uses :ref:`spectral_clustering` on a graph created from
voxel-to-voxel difference on an image to break this image into multiple
partly-homogeneous regions.
This procedure (spe... |
#!/usr/bin/env python
"""Distutils setup file, used to install or test 'setuptools'"""
import sys
import os
import textwrap
# Allow to run setup.py from another directory.
os.chdir(os.path.dirname(os.path.abspath(__file__)))
src_root = None
from distutils.util import convert_path
command_ns = {}
init_path = convert... |
import os
import tower_cli.utils.exceptions as exc
from tower_cli.utils import parser
from tower_cli.api import client
def tower_auth_config(module):
'''tower_auth_config attempts to load the tower-cli.cfg file
specified from the `tower_config_file` parameter. If found,
if returns the contents of the fil... |
# coding=utf-8
"""
WSGI config for projecta project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSG... |
{
'name': 'Clouder Website',
'version': '10.0.10.0.0',
'category': 'Clouder',
'depends': ['base', 'auth_signup', 'clouder'],
'author': 'Yannick Buron (Clouder), Nicolas Petit',
'license': 'LGPL-3',
'website': 'https://github.com/clouder-community/clouder',
'demo': [],
'data': [
... |
from twisted.internet import defer, protocol, reactor
from twisted.conch import error
from twisted.conch.ssh import transport
from twisted.python import log
class SSHClientFactory(protocol.ClientFactory):
def __init__(self, d, options, verifyHostKey, userAuthObject):
self.d = d
self.options = op... |
__author__ = 'Antring'
import urllib.request
import os
import feedparser
import datetime
from time import *
class rssReader:
'''Class for finding and downloading podcast'''
def __init__(self, url):
self.rssurl = url
self.podstream = feedparser.parse(self.rssurl)
self.podLink = self.p... |
from __future__ import print_function
from fabric.api import local, run, env, parallel, roles, hide, sudo, hosts, \
task, execute, cd, warn_only
from fabric.contrib.files import exists
from fabric.contrib.console import confirm
from fabric.colors import red, green, yellow
from datetime import timedelta
import json
... |
"""Simplify unit tests based on pymox."""
import os
import random
import shutil
import string
import StringIO
import subprocess
import sys
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
from third_party.pymox import mox
class IsOneOf(mox.Comparator):
def __init__(self, keys):
self._keys = keys
... |
#!/usr/bin/env python
import subprocess
import socket
import ssl
import sys
import time
if sys.version < '2.7':
print("WARNING: SSL not supported on Python 2.6")
exit(0)
if ssl.OPENSSL_VERSION_NUMBER < 0x10000000:
print("WARNING: TLS-PSK not supported on OpenSSL < 1.0")
exit(0)
import inspect, os, ... |
"Pythonic simple JSON RPC Client implementation"
__author__ = "Mariano Reingart (<EMAIL>)"
__copyright__ = "Copyright (C) 2011 Mariano Reingart"
__license__ = "LGPL 3.0"
__version__ = "0.05"
import urllib
from xmlrpclib import Transport, SafeTransport
from cStringIO import StringIO
import random
import sys
try:
... |
import copy
import numpy as np
from openpathsampling.netcdfplus import StorableObject, ObjectStore, WeakLRUCache
from openpathsampling.integration_tools import error_if_no_simtk_unit, unit
def unmask_quantity(quantity):
"""Force a maskedarray quantity to be unmasked.
NetCDF keeps giving us masked arrays, eve... |
def test_parse_incar():
from pylada.vasp import parse_incar
from pylada.error import ValueError
string = """ALGO = Fast\n"""\
"""ENCUT = 294.414\n"""\
"""EDIFF = 2e-12\n"""\
"""MAGMOM = -0*8 1.5*2\n"""\
"""ISPIN = 1\n"""\
"""ISMEAR = -1\n"""\... |
import pymongo
import traceback
from colorama import Fore
from toolset.utils.output_helper import log
from toolset.databases.abstract_database import AbstractDatabase
class Database(AbstractDatabase):
@classmethod
def get_connection(cls, config):
return pymongo.MongoClient(host = config.database_host... |
import tflib as lib
import numpy as np
import tensorflow as tf
_default_weightnorm = False
def enable_default_weightnorm():
global _default_weightnorm
_default_weightnorm = True
def disable_default_weightnorm():
global _default_weightnorm
_default_weightnorm = False
_weights_stdev = None
def set_wei... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.plugins.action.net_base import ActionModule as _ActionModule
class ActionModule(_ActionModule):
def run(self, tmp=None, task_vars=None):
result = super(ActionModule, self).run(tmp, task_vars)
del ... |
e1 = 'a_func from pkg2.a'
e2 = 'b_func from pkg2.b (pkg2/extra/b.py)'
e3 = 'notamodule from pkg2.__init__'
from pkg1 import *
t1 = a.a_func()
if t1 != e1:
print "expected:", e1
print " got:", t1
t2 = b.b_func()
if t2 != e2:
print "expected:", e2
print " got:", t2
t3 = notamodule()
if t3 ... |
from codemlparser import *
from slrparser import * |
import gtk
import ns.core
import ns.network
import ns.internet
import ns.ndnSIM
from visualizer.base import InformationWindow
class ShowNdnPit(InformationWindow):
(
COLUMN_PREFIX,
COLUMN_FACE
) = range(2)
def __init__(self, visualizer, node_index):
InformationWindow.__init__(... |
from openerp.osv import osv,fields
from openerp.tools.translate import _
class account_voucher(osv.osv):
_inherit = 'account.voucher'
def _get_partner_bank(self, cr, uid, context=None):
if self.partner_id:
p = self.pool.get('res.partner').browse(cr, uid, self.partner_id)
... |
import math
import logging
import numpy as np
from scipy.interpolate import splev
from hyperspy.component import Component
from hyperspy.misc.eels.hartree_slater_gos import HartreeSlaterGOS
from hyperspy.misc.eels.hydrogenic_gos import HydrogenicGOS
from hyperspy.misc.eels.effective_angle import effective_angle
from ... |
#!/usr/bin/env python
import sys
from subprocess import check_output, CalledProcessError, Popen
import logging
import os
import signal
import re
import boto3
import yaml
import glob
from os.path import join, basename
import threading
from time import sleep
from filecmp import cmp as fcmp
sys.path.append(os.path.abspa... |
#!/usr/bin/python
# pieces.py
# fishlamp-install
#
# Created by Mike Fullerton on 8/3/13.
#
import sys
import os
scriptName = os.path.basename(sys.argv[0])
scriptPath = os.path.dirname(sys.argv[0])
sharedPath = os.path.join(scriptPath, "../../shared/")
sys.path.append(os.path.abspath(sharedPath))
import Utils
im... |
from TargetGroup import TargetGroup
from utils.datatypes import *
from layout import Unit
class TargetDisplay(TargetGroup):
def __init__(self, name, parent):
TargetGroup.__init__(self, name, parent)
self._register_property("desktop-borders", TYPE_UNIT_LIST,
self.... |
"""
Exceptions and errors for use in twisted.internet modules.
Maintainer: Itamar Shtull-Trauring
"""
import socket
from twisted.python import deprecate
from twisted.python.versions import Version
class BindError(Exception):
"""An error occurred binding to an interface"""
def __str__(self):
s = s... |
"""
Utility functions for generating "lorem ipsum" Latin text.
"""
import random
COMMON_P = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo con... |
import os
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from django.conf import settings
from django.core.files.base import File
from django.core.files.storage import Storage
from django.core.files.uploadedfile import UploadedFile
from django.core.files.uploadhandler im... |
import re
import logging
import fourcc
import language
from strutils import str_to_unicode, unicode_to_str
UNPRINTABLE_KEYS = ['thumbnail', 'url', 'codec_private']
MEDIACORE = ['title', 'caption', 'comment', 'size', 'type', 'subtype', 'timestamp',
'keywords', 'country', 'language', 'langcode', 'url', 'art... |
#!/home/tom/ab/android/python-for-android/build/python-install/bin/python2.7
"""An RFC 2821 smtp proxy.
Usage: %(program)s [options] [localhost:localport [remotehost:remoteport]]
Options:
--nosetuid
-n
This program generally tries to setuid `nobody', unless this flag is
set. The setuid call ... |
"""A Python interface for creating TensorFlow servers."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.core.framework import device_attributes_pb2
from tensorflow.python import pywrap_tensorflow
def list_local_devices():
"""List the a... |
import os
import tempfile
import pytest
# Make sure we use temporary directories for the config and cache
# so that the tests are insensitive to local configuration.
os.environ['XDG_CONFIG_HOME'] = tempfile.mkdtemp('astropy_config')
os.environ['XDG_CACHE_HOME'] = tempfile.mkdtemp('astropy_cache')
os.mkdir(os.path.jo... |
"""
raven.transport.gevent
~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from raven.transport.base import AsyncTransport
from raven.transport.http import HTTPTransport
try:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.