content stringlengths 4 20k |
|---|
"""The WaveBlocks Project
IOM plugin providing functions for handling
homogeneous Hagedorn wavepacket data.
@author: R. Bourquin
@copyright: Copyright (C) 2010, 2011 R. Bourquin
@license: Modified BSD License
"""
import numpy as np
def add_wavepacket(self, parameters, timeslots=None, blockid=0):
r"""
Add s... |
"""
Orange canvas about dialog
"""
import sys
import pkg_resources
from PyQt4.QtGui import QDialog, QDialogButtonBox, QVBoxLayout, QLabel
from PyQt4.QtCore import Qt
from .. import config
ABOUT_TEMPLATE = """\
<center>
<h4>Orange</h4>
<p>Version: {version}</p>
<p>(git revision: {git_revision})</p>
</center>
"""
... |
import XenAPI, sys
def main(session,sr,map):
# Get all the PBDs associated with the SR
sr = session.xenapi.SR.get_by_uuid(sr)
pbds = session.xenapi.SR.get_PBDs(sr)
# Unplug them all
for pbd in pbds:
session.xenapi.PBD.unplug(pbd)
# Now delete and recreate them one by one, updating... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
try:
from botocore.exceptions import ClientError
HAS_BOTOCORE = True
except ImportError:
HAS_BOTOCORE = False
try:
import boto3
HAS_BOTO3 = True
except Import... |
# pylint: disable=g-bad-import-order,unused-import
import tensorflow.python.platform
import numpy as np
import tensorflow as tf
from tensorflow.models.rnn import linear
class LinearTest(tf.test.TestCase):
def testLinear(self):
with self.test_session() as sess:
with tf.variable_scope("root", initializer... |
try:
from django.conf.urls import patterns, handler500, url
# Fallback for Django versions < 1.4
except ImportError:
from django.conf.urls.defaults import patterns, handler500, url
urlpatterns = patterns(
'djangosaml2.views',
url(r'^login/$', 'login', name='saml2_login'),
url(r'^acs/$', 'assertion_... |
from utils import get_content_size
import cairo
import gtk
import pango
import sys
# Below import must at end, otherwise will got ImportError
from draw import draw_vlinear, draw_text
def render_pixbuf(widget, event, input_args):
'''
Render and save pixbuf.
@param widget: Gtk.Widget instance.
@param e... |
from IPython.display import HTML, display
devs = [
('Fernando Perez', 'fperez.jpg'),
('Brian Granger', 'ellisonbg.jpg'),
('Min Ragan-Kelley', 'minrk.jpg'),
('Thomas Kluyver', 'takluyver.jpg'),
('Matthias Bussonnier', 'matthias.jpg'),
('Jonathan Frederic', 'jdfreder.jpg'),
('Paul Ivanov', 'i... |
import unittest
import vimdoc
from vimdoc.block import Block
from vimdoc import error
from vimdoc import module
class TestVimModule(unittest.TestCase):
def test_section(self):
plugin = module.VimPlugin('myplugin')
main_module = module.Module('myplugin', plugin)
intro = Block(vimdoc.SECTION)
intro.L... |
"""GHOP specific views for Organization Mentors.
"""
__authors__ = [
'"Madhusudan.C.S" <<EMAIL>>'
]
from soc.logic import dicts
from soc.views.helper import decorators
from soc.views.models import mentor
import soc.cache.logic
from soc.modules.ghop.logic.models import mentor as ghop_mentor_logic
from soc.mod... |
"""Test harness for the logging module. Shows use of a user-defined Logger subclass.
Copyright (C) 2001-2002 Vinay Sajip. All Rights Reserved.
"""
import sys
import locale
locale.setlocale(locale.LC_ALL, '')
from logging import *
LOG_FORMAT = "%(asctime)s %(levelname)-5s %(message)s"
DATE_FORMAT = "%x %X"
class My... |
"""
funcatexit.py - allow programmer to define multiple exit functions to be
executed upon normal cases termination. Can be used for the environment clean
up functions. The basic idea is like atexit from python libs.
"""
__all__ = ["register", "run_exitfuncs", "unregister"]
import traceback
from avocado.core import ... |
#!/usr/bin/env python
import os
import shutil
import pandas as pd
import bloscpack as bp
try:
import ujson as json
except:
import json
"""
For reading and writing to the blosc store blst format. Nuances that users should take note:
* Column names are always saved as strings irrespective of there original dat... |
from flask.ext.restful import reqparse
import six
class ArgumentDoc(reqparse.Argument):
def __init__(self, name, default=None, dest=None, required=False,
ignore=False, type=six.text_type, location=('values',),
choices=(), action='store', help=None, operators=('=',),
... |
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
import json
# COMMON CODE FOR MIGRATION
import re
from ansible.module_utils.basic import get_exception
from ansible.module_utils.netcfg import NetworkConfig, ConfigLine
from ansible.modul... |
"""
Basic test for the Qrc() builder, called explicitly.
"""
import TestSCons
test = TestSCons.TestSCons()
test.dir_fixture("image")
test.file_fixture('SConscript')
test.file_fixture('../../qtenv.py')
test.file_fixture('../../../__init__.py','site_scons/site_tools/qt4/__init__.py')
test.run()
test.pass_test()
# Loc... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'community'}
from ansible.module_utils.oneview import OneViewModule
class ManagedSanFactsModule(OneViewModule):
argument_spec = dict(
name=dict(required=False, type='str')... |
"""ropevim, a vim mode for using rope refactoring library"""
from __future__ import print_function
import os
import re
import sys
import tempfile
import ropemode.decorators
import ropemode.environment
import ropemode.interface
import vim
# Save the opportunity for some other Python interpreters (pypy?)
python_cmd =... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
from units.compat.mock import patch
from ansible.modules.network.routeros import routeros_command
from units.modules.utils import set_module_args
from .routeros_module import TestRouterosModule, load_fixture
class Te... |
#encoding: utf-8
from django.test import TestCase
from video.management.commands.sub_commands.AddVideo import AddVideo
class AddVideo_test(AddVideo):
def __init__(
self, options, testCase, getMemberObjectReturn, getYoutubeVideosReturn,
getIsVideoExistsReturn, saveVideoReturn
):
self._... |
from __future__ import print_function
import array
from socket import *
PORT = 96
DISCOVER_PROTO_ID = 0x99
DISCOVER_ALL = 0xff # 0xff means all devices
DISCOVER_REQUEST = 0x01
DISCOVER_RESPONSE = 0x02
DISCOVER_REQUEST_SIZE = 4
DISCOVER_RESPONSE_SIZE = 35
def check_sum(data):
chksum = 0
for c in data[... |
#!/usr/bin/env python
# Helper script when freezing Pmw applications. It concatenates all
# Pmw megawidget files into a single file, 'Pmw.py', in the current
# directory. The script must be called with one argument, being the
# path to the 'lib' directory of the required version of Pmw.
# To freeze a Pmw appli... |
"""
Test the views served by third_party_auth.
"""
import ddt
from lxml import etree
from onelogin.saml2.errors import OneLogin_Saml2_Error
import unittest
from .testutil import AUTH_FEATURE_ENABLED, SAMLTestCase
# Define some XML namespaces:
from third_party_auth.tasks import SAML_XML_NS
XMLDSIG_XML_NS = 'http://www... |
from django.contrib.gis.db.backends.base.adapter import WKTAdapter
from django.contrib.gis.db.backends.base.operations import \
BaseSpatialOperations
from django.contrib.gis.db.backends.utils import SpatialOperator
from django.contrib.gis.db.models import aggregates
from django.db.backends.mysql.operations import D... |
from graphics.widgets.checkbox_item_output_f import CheckboxItemOutputF
from utils.train.data_augmentation import DataAugmentation
import constants.output_constants as const
import tkinter as tk
class DataAugmentationOutputF(tk.Frame):
def __init__(self,
parent,
disabled=Fal... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import inspect
import time
import traceback
import sqlalchemy as sa
from twisted.internet import threads
from twisted.python import log
from twisted.python import threadpool
from buildbot.db.buildrequests im... |
from mock import __version__
import os
NAME = 'mock'
MODULES = ['mock']
DESCRIPTION = 'A Python Mocking and Patching Library for Testing'
URL = "http://www.voidspace.org.uk/python/mock/"
readme = os.path.join(os.path.dirname(__file__), 'README.txt')
LONG_DESCRIPTION = open(readme).read()
CLASSIFIERS = [
'Deve... |
from service.settings import GraphSettings
def checkLockRange(src, distance):
if distance is None:
return True
if GraphSettings.getInstance().get('ignoreLockRange'):
return True
return distance <= src.item.maxTargetRange
def checkDroneControlRange(src, distance):
if distance is None:... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import random
from ansible.plugins.lookup import LookupBase
# useful for introducing chaos ... or just somewhat reasonably fair selection
# amongst available mirrors
#
# tasks:
# - debug: msg=$item
# with_rando... |
"""Large file support
.. deprecated:: 3.4
The VARBLOCK format is NOT recommended for general use, has been deprecated since
Python-RSA 3.4, and will be removed in a future release. It's vulnerable to a
number of attacks:
1. decrypt/encrypt_bigfile() does not implement `Authenticated encryption`_ nor
... |
from xmodule.course_module import CourseDescriptor
from xmodule.x_module import XModuleDescriptor
import factory
from factory.helpers import lazy_attribute
class SplitFactory(factory.Factory):
"""
Abstracted superclass which defines modulestore so that there's no dependency on django
if the caller passes ... |
"Functions that help with dynamically creating decorators for views."
from functools import wraps, update_wrapper, WRAPPER_ASSIGNMENTS
class classonlymethod(classmethod):
def __get__(self, instance, owner):
if instance is not None:
raise AttributeError("This method is available only on the vie... |
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
int_or_none,
qualities,
unified_strdate,
)
class CCCIE(InfoExtractor):
IE_NAME = 'media.ccc.de'
_VALID_URL = r'https?://(?:www\.)?media\.ccc\.de/[^?#]+/[^?#/]*?_(?P<id>[0-9]{8,})._[^?#/]*\.h... |
#!/usr/bin/env python
"""Script to commit the doc build outputs into the github-pages repo.
Use:
gh-pages.py [tag]
If no tag is given, the current output of 'git describe' is used. If given,
that is how the resulting directory will be named.
In practice, you should use either actual clean tags from a current bui... |
from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import parse_duration
class DHMIE(InfoExtractor):
IE_DESC = 'Filmarchiv - Deutsches Historisches Museum'
_VALID_URL = r'https?://(?:www\.)?dhm\.de/filmarchiv/(?:[^/]+/)+(?P<id>[^/]+)'
_TESTS = [{
'url': 'http:... |
import os
from .. import constants, logger
from . import (
base_classes,
texture,
material,
geometry,
object as object_,
utilities,
io,
api
)
from bpy import context
class Scene(base_classes.BaseScene):
"""Class that handles the contruction of a Three scene"""
def __init__(self... |
"""
Task Manager for Xen API asynchronous tasks.
Stores all tasks in a simple dictionary in module's own local storage to
avoid the 'instance()' methods.
Tasks are indexed by UUID.
"""
from xen.xend.XendTask import XendTask
from xen.xend import uuid
import threading
tasks = {}
tasks_lock = threading.Lock()
def cr... |
#!/usr/bin/env python
#coding:utf-8
# Email : <EMAIL>
# Last modified : 2015-09-15 08:31:23
# Description :
from __future__ import print_function
from gale.utils import set_close_exec, ObjectDict, single_pattern
from gale.e import IPCError
from gevent import socket
import gevent
import json
from multiprocess... |
"""
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... |
from IECore import *
class deformationBlur(ParameterisedProcedural):
#=====
# Init
def __init__(self) :
ParameterisedProcedural.__init__( self, "DeformationBlur procedural." )
geo1 = PathParameter( name="geo1", description="Geometry #1",
... |
import random
import string;
import hashlib;
class UserAccount:
'Represents a computer user account'
def __init__(self, uid_fname="John", uid_lname="Doe", uid_format="LLLLLFFN", pwd_length=7, pwd_complexity="High", email_format="F.L", uid=None, pwd=None):
'''Initialize a person based on a provided cri... |
# 05.10.2007, c
# last revision: 25.02.2008
from sfepy import data_dir
filename_mesh = data_dir + '/meshes/3d/special/cube_sphere.mesh'
# Whole domain $Y$.
region_1000 = {
'name' : 'Y',
'select' : 'all',
}
# Domain $Y_1$.
region_1 = {
'name' : 'Y1',
'select' : 'elements of group 1',
}
# Domain $Y_2$... |
"""dagrun start end
Revision ID: 4446e08588
Revises: 561833c1c74b
Create Date: 2015-12-10 11:26:18.439223
"""
# revision identifiers, used by Alembic.
revision = '4446e08588'
down_revision = '561833c1c74b'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgrade():
op.... |
#!/usr/bin/env python
import os
import sys
import threading
import subprocess
import cherrypy
import json
import itertools
import logging
import time
import re
import xmlrpclib
import math
from threading import Timer
def popen(cmd):
cmd = cmd.split()
logger = logging.getLogger('translation_log.popen')
logg... |
#!/usr/bin/python -u
import sys
import libxml2
# Memory debug specific
libxml2.debugMemory(1)
log = ""
class callback:
def startDocument(self):
global log
log = log + "startDocument:"
def endDocument(self):
global log
log = log + "endDocument:"
def startElement(self, tag... |
"""Module for build host support."""
import os
import pipes
import signal
import subprocess
import cr
# Controls what verbosity level turns on command trail logging
_TRAIL_VERBOSITY = 2
def PrintTrail(trail):
print 'Command expanded the following variables:'
for key, value in trail:
if value == None:
... |
import nova.scheduler.utils
import nova.servicegroup
from nova import test
from nova.tests import fixtures as nova_fixtures
from nova.tests.functional.api import client
import nova.tests.unit.image.fake
from nova.tests.unit import policy_fixture
class TestServerValidation(test.TestCase):
REQUIRES_LOCKING = True
... |
from dateutil.relativedelta import relativedelta
from openerp import fields, models, api
class HrContract(models.Model):
_inherit = 'hr.contract'
@api.onchange('trial_date_start', 'type_id')
@api.multi
def onchange_trial_date_start(self):
self.ensure_one()
if self.trial_date_start and... |
import builders
import unittest2 as unittest
class BuildersTest(unittest.TestCase):
def test_path_from_name(self):
tests = {
'test': 'test',
'Mac 10.6 (dbg)(1)': 'Mac_10_6__dbg__1_',
'(.) ': '____',
}
for name, expected in tests.items():
self... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import django.utils.timezone
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0003_auto_20151215_1537'),
]
operations = [
migrations.AlterField(
model_na... |
import string
import sys
import types
import Tkinter
import Pmw
class Counter(Pmw.MegaWidget):
def __init__(self, parent = None, **kw):
# Define the megawidget options.
INITOPT = Pmw.INITOPT
optiondefs = (
('autorepeat', 1, None),
('buttonaspect', 1.0, INITOPT),
('da... |
#!/usr/bin/env python
import unittest
from unittest.mock import MagicMock
import string
import random
import types
import pytest
from i3pystatus.core.exceptions import ConfigAmbigiousClassesError, ConfigInvalidModuleError
from i3pystatus.core import util, ClassFinder
def test_lchop_prefixed():
assert util.lcho... |
STDOUT = -11
STDERR = -12
import ctypes
from ctypes import LibraryLoader
try:
windll = LibraryLoader(ctypes.WinDLL)
from ctypes import wintypes
except (AttributeError, ImportError):
windll = None
SetConsoleTextAttribute = lambda *_: None
else:
from ctypes import (
byref, Structure, c_char,... |
import os
import os.path
from fnmatch import fnmatch
import targz
##def DoxyfileParse(file_contents):
## """
## Parse a Doxygen source file and return a dictionary of all the values.
## Values will be strings and lists of strings.
## """
## data = {}
##
## import shlex
## lex = shlex.shlex(instream = fil... |
from gnuradio import gr
class pfb_decimator_ccf(gr.hier_block2):
'''
Make a Polyphase Filter decimator (complex in, complex out, floating-point taps)
This simplifies the interface by allowing a single input stream to connect to this block.
It will then output a stream that is the decimated output stre... |
#!/bin/env python
import os,sys,shutil,time
def lineSearch(logfile,*args):
searchTimeout = 10.
searchTimeAccum = 0.
doLoop = True
while doLoop:
line = logfile.readline()
if not line:
time.sleep(0.1)
searchTimeAccum += 0.1
continue
foundAll = True
for arg in args:
if line... |
#!/usr/bin/env python3
import sys
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import AutoMinorLocator
def main():
if len(sys.argv) != 5:
print("Usage: plot [phot file] [period] [star name] [output file]",
file=sys.stderr)
exit()
filename, period, n... |
"""Uninstalls Chrome.
This script reads the uninstall command from registry, calls it, and verifies
the output status code.
"""
import _winreg
import optparse
import subprocess
import sys
def main():
parser = optparse.OptionParser(description='Uninstall Chrome.')
parser.add_option('--system-level', action='stor... |
from airflow.contrib.hooks.ssh_hook import SSHHook
from airflow.exceptions import AirflowException
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
class SFTPOperation(object):
PUT = 'put'
GET = 'get'
class SFTPOperator(BaseOperator):
"""
SFTPOperator for t... |
"""Native adapter for serving CherryPy via mod_python
Basic usage:
##########################################
# Application in a module called myapp.py
##########################################
import cherrypy
class Root:
@cherrypy.expose
def index(self):
return 'Hi there, Ho there, Hey there'
# ... |
from ...const import GRAMPS_LOCALE as glocale
from ...utils.grampslocale import GrampsLocale
from ...display.name import NameDisplay
from ...config import config
#-------------------------------------------------------------------------
#
# Report
#
#--------------------------------------------------------------------... |
"""
Copyright (c) 2017, Jairus Martin.
Distributed under the terms of the MIT License.
The full license is in the file LICENSE, distributed with this software.
Created on May 20, 2017
@author: jrm
"""
from atom.api import (
Typed, ForwardTyped, Bool, Tuple, Float, Int, Enum, observe, set_default
)
from enaml.c... |
m5.util.addToPath('../configs/common')
from cpu2000 import twolf
import os
workload = twolf(isa, opsys, 'smred')
root.system.cpu[0].workload = workload.makeLiveProcess()
cwd = root.system.cpu[0].workload[0].cwd
#Remove two files who's presence or absence affects execution
sav_file = os.path.join(cwd, workload.input_s... |
"""Tests for tf.learn."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import re
import tensorflow.python.platform # pylint: disable=unused-import,g-bad-import-order
import numpy as np
import six
import tensorflow as tf
from tensorflow.python.framewor... |
"""SCons.Tool.sgiar
Tool-specific initialization for SGI ar (library archive). If CC
exists, static libraries should be built with it, so the prelinker has
a chance to resolve C++ template instantiations.
There normally shouldn't be any need to import this module directly.
It will usually be imported through ... |
"""Test class for VirtualBox Driver Modules."""
import mock
from oslo_config import cfg
from pyremotevbox import exception as pyremotevbox_exc
from pyremotevbox import vbox as pyremotevbox_vbox
from ironic.common import boot_devices
from ironic.common import exception
from ironic.common import states
from ironic.cond... |
import json
import requests
from post import Post
from user import User
TOP_POSTS_URL = "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty"
TOP_POSTS_ITEM = "https://hacker-news.firebaseio.com/v0/item/%s.json?print=pretty"
NEW_POSTS_URL = "https://hacker-news.firebaseio.com/v0/newstories.json?print... |
"""
Settings and configuration for Django.
Values will be read from the module specified by the DJANGO_SETTINGS_MODULE environment
variable, and then from django.conf.global_settings; see the global settings file for
a list of all possible variables.
"""
import os
import re
import time # Needed for Windows
import... |
# encoding: utf-8
"""
Enable pygtk to be used interacive by setting PyOS_InputHook.
Authors: Brian Granger
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2008-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license ... |
import gi
gi.require_version('Nautilus', '3.0')
from gi.repository import Nautilus, GObject, Gtk, Gdk, Gio
from trackertag import TrackerTag
import os
import datetime
class ColumnExtension(GObject.GObject, Nautilus.MenuProvider, Nautilus.InfoProvider, Nautilus.LocationWidgetProvider):
def __init__(self):
... |
{
'name': 'Employee Turn-over Report',
'version': '1.0',
'category': 'Generic Modules/Human Resources',
'description': """
Employee Turn-over by Department
================================
""",
'author': "Michael Telahun Makonnen <<EMAIL>>,Odoo Community Association (OCA)",
'website': 'http... |
from __future__ import absolute_import
from __future__ import print_function
from buildbot.process.properties import Properties
from buildbot.test.fake.state import State
class Change(State):
project = ''
repository = ''
branch = ''
category = ''
codebase = ''
properties = {}
def __init... |
#FLM: RoboFab Intro, Font Groups
#
#
# demo of RoboFab font groups
#
#
# RoboFab font objects have several objects associated with them
# kerning, info, groups, etc. Let's talk about groups. Groups are,
# well groups of glyph names. These can be useful for lots of things
# like kerning and OpenType features. The numb... |
"""This module implements dynamic profiles.
A Dynamic profile is a way of discovering certain parameters via running a
matching signature.
"""
from rekall import obj
from rekall.plugins.tools import disassembler
class DisassembleMatcher(object):
"""A matching engine for disassembler rules.
This matcher sear... |
from django.conf import settings
from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^$', 'shr.url.views.homepage'),
(r'^login/?$', 'shr.oauthlogin.views.connection'),
(r'^... |
from odoo.tests import common
class TestConfig(common.SavepointCase):
@classmethod
def setUpClass(cls):
super(TestConfig, cls).setUpClass()
cls.wizard = cls.env['res.config.settings'].create({})
cls.partner = cls.env['res.partner'].create({
'firstname': "First",
... |
"""Mode creation page (used to add modes to courses during testing)."""
import re
import urllib
from bok_choy.page_object import PageObject
from . import BASE_URL
class ModeCreationPage(PageObject):
"""The mode creation page.
When allowed by the Django settings file, visiting this page allows modes to be
... |
# -*- coding: utf-8 -*-
import unittest
from pynes import sprite
class SpriteTest(unittest.TestCase):
def __init__(self, testcase_name):
unittest.TestCase.__init__(self, testcase_name)
f = open('fixtures/nerdynights/scrolling/mario.chr', 'rb')
content = f.read()
self.bin = [ord(... |
"""
Implements the SSH v2 key agent protocol. This protocol is documented in the
SSH source code, in the file
U{PROTOCOL.agent<http://www.openbsd.org/cgi-bin/cvsweb/src/usr.bin/ssh/PROTOCOL.agent>}.
Maintainer: Paul Swartz
"""
import struct
from twisted.conch.ssh.common import NS, getNS, getMP
from twisted.conch.er... |
import abc
import six
@six.add_metaclass(abc.ABCMeta)
class AbstractVersionHandler(object):
@abc.abstractmethod
def get_config_items(self):
return
@abc.abstractmethod
def get_applicable_target(self, name):
return
@abc.abstractmethod
def get_cluster_spec(self, cluster, user_... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
import traceback
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_nati... |
"""Unit Tests for volume transfers."""
import datetime
import mock
from cinder import context
from cinder import db
from cinder import exception
from cinder import test
from cinder.tests.unit import utils
from cinder.transfer import api as transfer_api
class VolumeTransferTestCase(test.TestCase):
"""Test cases... |
import tensorflow as tf
import numpy as np
import unittest
import shutil
import os
from dnc.dnc import DNC
from dnc.memory import Memory
from dnc.controller import BaseController
class DummyController(BaseController):
def network_vars(self):
self.W = tf.Variable(tf.truncated_normal([self.nn_input_size, 64... |
from symengine.utilities import raises
from symengine import Integer, I, S, Symbol, pi, Rational
from symengine.lib.symengine_wrapper import (perfect_power, is_square, integer_nthroot)
def test_integer():
i = Integer(5)
assert str(i) == "5"
assert int(i) == 5
assert float(i) == 5.0
assert complex... |
# test - +
print( -97989513389222316022151446562729620153292831887555425160965597396
& 23716683549865351578586448630079789776107310103486834795830390982)
print( -53817081128841898634258263553430908085326601592682411889506742059
& 37042558948907407488299113387826240429667200950043601129661240876)
print( -2... |
"""
Classes and functions for interacting with the Mesos HTTP RESTful API
"""
from urllib.parse import urlparse
from copy import deepcopy
import requests
import tenacity
import ujson
from mesos.exceptions import MesosException
from mesos.exceptions import MesosHTTPException
from mesos.exceptions import MesosAuthen... |
"""Various utilities used in tests."""
import contextlib
import os
import shutil
import sys
import tempfile
import six
import unittest2
SkipOnWindows = unittest2.skipIf(
os.name == 'nt', 'Does not run on windows')
@contextlib.contextmanager
def TempDir(change_to=False):
if change_to:
original_dir ... |
import sys
import xml.dom.minidom as minidom
TEXT_NODE = minidom.Node.TEXT_NODE
def get_text(node):
c = node.firstChild
if c is None or c.nodeType != TEXT_NODE:
raise ValueError("node %r does not contain text" % (node,))
return c.data
def get_children(node):
return [_ for _ in node.childNode... |
import os
import sys
import traceback
from .. import constants, logger, exceptions, dialogs
from . import scene, geometry, api, base_classes
def _error_handler(func):
def inner(filepath, options, *args, **kwargs):
level = options.get(constants.LOGGING, constants.DEBUG)
version = options.get('... |
"""Tests for certbot_nginx.parser."""
import glob
import os
import re
import shutil
import unittest
from certbot import errors
from certbot_nginx import nginxparser
from certbot_nginx import obj
from certbot_nginx import parser
from certbot_nginx.tests import util
class NginxParserTest(util.NginxTest):
"""Nginx... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.compat.tests import unittest
from ansible.compat.tests.mock import patch, MagicMock
from ansible.errors import AnsibleError, AnsibleParserError
from ansible.executor.playbook_iterator import PlaybookIterator
from ansi... |
import sys
import re
import os
import subprocess
import threading
from sys import stdout, stderr, argv
# Running this script
# 1. To rebuild all dependencies:
# $ build.py deps
# 2. To build all targets without rebuilding dependencies
# $ build.py build
# 3. To build a single target without rebuilding dependencies
# $... |
import contextlib
from oslo_config import cfg
from oslo_db import api as oslo_db_api
from oslo_db import exception as db_exc
from oslo_db.sqlalchemy import session
from oslo_utils import uuidutils
from sqlalchemy import exc
from neutron.common import exceptions as n_exc
from neutron.db import common_db_mixin
_FACAD... |
from __future__ import unicode_literals
import logging
import traceback
from django.conf import settings
from django.core.paginator import InvalidPage, Paginator
from django.http import (HttpResponse, HttpResponseNotModified,
HttpResponseServerError, Http404)
from django.shortcuts import get_... |
"""
@author Konrad Cybulski
@since 14/08/2016
@modified 16/08/2016
Code written utilising pseudocode provided
in 'Social norms of cooperation in small-scale
societies' by Santos, Santos, Pacheco
"""
import numpy as np
from InstanceVariables import InstanceVariables
"""
Static Variables
"""
# B G
s... |
import datetime as dt
import time as tm
import pytz as tz
# get current time - note that there is no timezone
now = dt.datetime.now()
print(now.year, now.month, now.day, now.hour, now.minute, now.second, now.microsecond, now.tzinfo)
# make new date objects and play date arithmetic with it
last = dt.datetime(2020, ... |
# -*- coding: utf-8 -*-
from dCore import *
from dConstants import *
from dConfig import *
from dLog import *
from dWx import wx
def DamnFadeIn(frame):
if not frame.CanSetTransparent() or not DV.prefs.get('splashscreen') == 'True':
frame.Show()
return
frame.SetTransparent(0)
frame.Show()
frame.fadeTimer = wx.T... |
"Dummy cache backend"
from django.core.cache.backends.base import BaseCache
class DummyCache(BaseCache):
def __init__(self, host, *args, **kwargs):
BaseCache.__init__(self, *args, **kwargs)
def add(self, key, value, timeout=None, version=None):
key = self.make_key(key, version=version)
... |
from __future__ import unicode_literals
import frappe
from collections import Counter
from frappe.core.doctype.user.user import STANDARD_USERS
def execute():
frappe.reload_doc("core", "doctype", "system_settings")
system_settings = frappe.get_doc("System Settings")
# set values from global_defauls
global_default... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django_extensions.db.fields
class Migration(migrations.Migration):
dependencies = [
('food', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Commen... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.