code stringlengths 1 199k |
|---|
class StopSendingException(Exception):
"""
pre_send exception
""" |
import nose
import sys
import os
import warnings
import tempfile
from contextlib import contextmanager
import datetime
import numpy as np
import pandas
import pandas as pd
from pandas import (Series, DataFrame, Panel, MultiIndex, Categorical, bdate_range,
date_range, Index, DatetimeIndex, isnull)
fr... |
import time
import os
import ContentDb
from Debug import Debug
from Config import config
class ContentDbDict(dict):
def __init__(self, site, *args, **kwargs):
s = time.time()
self.site = site
self.cached_keys = []
self.log = self.site.log
self.db = ContentDb.getContentDb()
... |
NAME = 'ZenPacks.community.DistributedCollectors'
VERSION = '1.7'
AUTHOR = 'Egor Puzanov'
LICENSE = ''
NAMESPACE_PACKAGES = ['ZenPacks', 'ZenPacks.community']
PACKAGES = ['ZenPacks', 'ZenPacks.community', 'ZenPacks.community.DistributedCollectors']
INSTALL_REQUIRES = []
COMPAT_ZENOSS_VERS = '>=2.5'
PREV_ZENPACK_NAME = ... |
import os
from abjad import abjad_configuration
from abjad.demos import desordre
def test_demos_desordre_01():
lilypond_file = desordre.make_desordre_lilypond_file() |
import numpy as np
import os
from galry import log_debug, log_info, log_warn, get_color
from fontmaps import load_font
from visual import Visual
__all__ = ['TextVisual']
VS = """
gl_Position.x += (offset - text_width / 2) * spacing.x / window_size.x;
gl_Position.y -= index * spacing.y / window_size.y;
gl_Position.xy = ... |
"""
- This simulation seeks to emulate the CUBA benchmark simulations of (Brette
et al. 2007) using the Brian2 simulator for speed benchmark comparison to
DynaSim. However, this simulation does NOT include synapses, for better
comparison to Figure 5 of (Goodman and Brette, 2008).
- The time taken to simulate will... |
import bpy
def load_font(font_path):
""" Load a new TTF font into Blender, and return the font object """
# get the original list of fonts (before we add a new one)
original_fonts = bpy.data.fonts.keys()
# load new font
bpy.ops.font.open(filepath=font_path)
# get the new list of fonts (after we added a new one)
... |
"""
WSGI config for horario project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_... |
"""
Python script "setup.py"
by Matthew Garcia, PhD student
Dept. of Forest and Wildlife Ecology
University of Wisconsin - Madison
matt.e.garcia@gmail.com
Copyright (C) 2015-2016 by Matthew Garcia
Licensed Gnu GPL v3; see 'LICENSE_GnuGPLv3.txt' for complete terms
Send questions, bug reports, any related requests to mat... |
from mediadrop.lib.test.pythonic_testcase import *
from mediadrop.plugin.events import Event, FetchFirstResultEvent, GeneratorEvent
class EventTest(PythonicTestCase):
def setUp(self):
self.observers_called = 0
self.event = Event()
def probe(self):
self.observers_called += 1
def test_... |
from Cryptodome.Util.py3compat import bord
from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib,
VoidPointer, SmartPointer,
create_string_buffer,
get_raw_buffer, c_size_t,
c... |
from PyQt5 import QtCore
qt_resource_data = b"\
\x00\x00\x01\xf1\
\x00\
\x00\x09\x00\x78\x9c\xdd\x96\x51\x6f\x9b\x30\x10\xc7\xdf\xfb\x29\
\x3c\x1e\x9a\x4d\x15\xd0\x49\x7b\x98\x52\x48\x34\x92\x4c\xea\xd4\
\xaa\x54\x69\x55\xf5\xd1\x98\x0b\x71\x01\xdb\x35\x26\x09\xdf\x7e\
\x86\xb0\x96\xa4\x2c\xa4\x1d\x4f\xe3\xc5\xd8\x77\x... |
../../../../../../../share/pyshared/orca/scripts/apps/nautilus/script.py |
import pluma, gobject, gtk, os
from zen_editor import ZenEditor
zencoding_ui_str = """
<ui>
<menubar name="MenuBar">
<menu name="EditMenu" action="Edit">
<placeholder name="EditOps_5">
<menu action="ZenCodingMenuAction">
<menuitem name="ZenCodingExpand" action="ZenCodingExpandAction"/>
... |
class Charset(object):
common_name = 'NotoKufiArabic-Regular'
native_name = ''
def glyphs(self):
glyphs = []
glyphs.append(0x0261) #uni0759.fina
glyphs.append(0x007F) #uni0625
glyphs.append(0x00D4) #uni0624
glyphs.append(0x0005) #uni0627
glyphs.append(0x00... |
import web
import sam.common
import sam.models.links
class Details:
def __init__(self, db, subscription, ds, address, timestamp_range=None, port=None, page_size=50):
self.db = db
self.sub = subscription
self.table_nodes = "s{acct}_Nodes".format(acct=self.sub)
self.table_links = "s{ac... |
"""File format specific behavior."""
from weblate.formats.convert import (
HTMLFormat,
IDMLFormat,
OpenDocumentFormat,
PlainTextFormat,
WindowsRCFormat,
)
from weblate.formats.helpers import BytesIOMode
from weblate.formats.tests.test_formats import AutoFormatTest
from weblate.trans.tests.utils impo... |
from gi.repository import Gtk
def show_error_dialog(parent, primary, secondary):
p = "<span weight=\"bold\" size=\"larger\">%s</span>" % primary
dialog = Gtk.MessageDialog(parent,Gtk.DialogFlags.MODAL,
Gtk.MessageType.ERROR,Gtk.ButtonsType.CLOSE,"")
dialog.set_markup(p);
d... |
from common import base
class Plugin(base.BASE):
__name__ = 'csdn'
__title__ = 'CSDN'
__url__ = 'http://www.csdn.net/'
def register(self, target):
self.information = {
'email': {
'url': 'http://passport.csdn.net/account/register',
'method': 'get',
... |
''' HTTP client '''
import logging
from .stream_handler import StreamHandler
from .http_client_stream import HttpClientStream
from .http_message import HttpMessage
from . import utils
from . import utils_net
class HttpClient(StreamHandler):
''' Manages one or more HTTP streams '''
def __init__(self, poller):
... |
import unittest
import random
import sys
import os
ETEPATH = os.path.abspath(os.path.split(os.path.realpath(__file__))[0]+'/../')
sys.path.insert(0, ETEPATH)
from ete2 import Tree, TreeStyle, NodeStyle, PhyloTree, faces, random_color
from ete2.treeview.faces import *
from ete2.treeview.main import _NODE_TYPE_CHECKER, F... |
import os
import sys
import xml.etree.ElementTree as ET
import math
import time
import random
import copy
from optparse import OptionParser
from optparse import OptionGroup
import imp
import socket
import signal
import traceback
import datetime
from sonLib.bioio import logger
from sonLib.bioio import setLoggingFromOpti... |
""" path.py - An object representing a path to a file or directory.
Example:
from path import path
d = path('/home/guido/bin')
for f in d.files('*.py'):
f.chmod(0755)
This module requires Python 2.5 or later.
URL: http://www.jorendorff.com/articles/python/path
Author: Jason Orendorff <jason.orendorff\x40gmail\... |
class Charset(object):
common_name = 'NotoSansHebrew-Regular'
native_name = ''
def glyphs(self):
chars = []
chars.append(0x0000) #null ????
chars.append(0x200C) #uni200C ZERO WIDTH NON-JOINER
chars.append(0x000D) #nonmarkingreturn ????
chars.append(0x200E) #uni200... |
"""
Foundational classes and functions.
"""
import re
from constants import NAME_REGEX, NAME_ERROR
from constants import TYPE_ERROR, SET_ERROR, DEL_ERROR, OVERRIDE_ERROR
class ReadOnly(object):
"""
Base class for classes that can be locked into a read-only state.
Be forewarned that Python does not offer tru... |
from __future__ import absolute_import, division, print_function
from cryptography import utils
from cryptography.exceptions import (
AlreadyFinalized, UnsupportedAlgorithm, _Reasons
)
from cryptography.hazmat.backends.interfaces import HashBackend
from cryptography.hazmat.primitives import interfaces
@utils.regist... |
from .base import Browser, ExecutorBrowser, require_arg
from .base import get_timeout_multiplier # noqa: F401
from ..executors import executor_kwargs as base_executor_kwargs
from ..executors.executorwebdriver import (WebDriverTestharnessExecutor, # noqa: F401
WebDriverRefTe... |
import cyclone.auth
import cyclone.escape
import cyclone.web
import datetime
import time
import os
from beaker.cache import cache_managers
from toughradius.manage.base import BaseHandler
from toughlib.permit import permit
from toughradius.manage import models
from toughradius.manage.settings import *
from toughradius.c... |
{
'name': 'Account Invoice Check Total',
'summary': """
Check if the verification total is equal to the bill's total""",
'version': '10.0.1.0.0',
'license': 'AGPL-3',
'author': 'Acsone SA/NV,Odoo Community Association (OCA)',
'website': 'https://acsone.eu/',
'depends': [
'acc... |
import logging
unicode_string = u"Татьяна"
utf8_string = "'Татьяна' is an invalid string value"
logging.warning(unicode_string)
logging.warning(utf8_string)
try:
raise Exception(utf8_string)
except Exception,e:
print "--- (Log a traceback of the exception):"
logging.exception(e)
print "--- Everything ok... |
from __future__ import division
from django.utils.translation import ugettext_lazy as _
from telemeta.models.core import *
from telemeta.models.resource import *
from telemeta.models.collection import *
class MediaCorpus(MediaBaseResource):
"Describe a corpus"
element_type = 'corpus'
children_type = 'collec... |
"""Prints a "hello world" statement."""
def main():
"""Utterly standard."""
print("Hello cruel world.")
if __name__ == "__main__":
main() |
"""
Django Views for service status app
"""
from __future__ import absolute_import
import json
import time
from celery.exceptions import TimeoutError
from django.http import HttpResponse
from djcelery import celery
from openedx.core.djangoapps.service_status.tasks import delayed_ping
def index(_):
"""
An empty ... |
"""
Useful utilities for management commands.
"""
from django.core.management.base import CommandError
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
def get_mutually_exclusive_required_option(options, *selections):
"""
Validates that exactly one of the 2 given options is spe... |
from openerp import models, fields, api
def format_code(code_seq):
code = map(int, str(code_seq))
code_len = len(code)
while len(code) < 14:
code.insert(0, 0)
while len(code) < 16:
n = sum([(len(code) + 1 - i) * v for i, v in enumerate(code)]) % 11
if n > 1:
f = 11 - ... |
import os, sys, glob, pickle, subprocess
sys.path.insert(0, os.path.dirname(__file__))
from clang import cindex
sys.path = sys.path[1:]
def configure_libclang():
llvm_libdirs = ['/usr/lib/llvm-3.2/lib', '/usr/lib64/llvm']
try:
libdir = subprocess.check_output(['llvm-config', '--libdir']).decode('utf-8')... |
from __future__ import print_function
import FreeCAD
import Path
import PathScripts.PathDressup as PathDressup
import PathScripts.PathGeom as PathGeom
import PathScripts.PathLog as PathLog
import PathScripts.PathUtil as PathUtil
import PathScripts.PathUtils as PathUtils
import math
from PySide import QtCore
from lazy_l... |
import sys
def setup(core, object):
object.setAttachment('radial_filename', 'ring/unity')
object.setAttachment('objType', 'ring')
object.setStfFilename('static_item_n')
object.setStfName('item_ring_set_commando_utility_b_01_01')
object.setDetailFilename('static_item_d')
object.setDetailName('item_ring_set_command... |
import sys
from services.spawn import MobileTemplate
from services.spawn import WeaponTemplate
from resources.datatables import WeaponType
from resources.datatables import Difficulty
from resources.datatables import Options
from java.util import Vector
def addTemplate(core):
mobileTemplate = MobileTemplate()
mobileTe... |
''' Auto-generated ui widget plugin '''
from projexui.qt.QtDesigner import QPyDesignerCustomWidgetPlugin
from projexui.qt.QtGui import QIcon
import projex.resources
from projexui.widgets.xviewwidget import XViewWidget as Base
setattr(Base, '__designer_mode__', True)
DEFAULT_XML = '''<ui language="c++" displayname="XVie... |
import enum
import inspect
import pydoc
import unittest
from collections import OrderedDict
from enum import Enum, IntEnum, EnumMeta, unique
from io import StringIO
from pickle import dumps, loads, PicklingError, HIGHEST_PROTOCOL
try:
class Stooges(Enum):
LARRY = 1
CURLY = 2
MOE = 3
except E... |
import numpy as np
import time
import casadi as C
import nmheMaps
from ocputils import Constraints
from newton import Newton
from collocation import LagrangePoly
class Nmhe(object):
def __init__(self,dae,nk):
self.dae = dae
self.nk = nk
self._gaussNewtonObjF = []
mapSize = len(self.d... |
from flask import Flask, request
import nltk
import json
from nltk_contrib import timex
import time
import sys
import getopt
USAGE = """
nltk-rest --port -p <port> -v units -u [--help -h]
Expose NLTK over REST as a server using Python Flask. Submit content to the
`/nltk` endpoint in the REST body request.
-h, --help Pr... |
"""List Command."""
from __future__ import print_function
from biggraphite.cli import command
from biggraphite.glob_utils import graphite_glob
def list_metrics(accessor, pattern, graphite=True):
"""Return the list of metrics corresponding to pattern.
Exit with error message if None.
Args:
accessor: ... |
from sys import maxsize
class Group:
def __init__(self, group_name=None, group_header=None, group_footer=None, id=None):
self.group_name = group_name
self.group_header = group_header
self.group_footer = group_footer
self.id = id
def __repr__(self):
return '%s:%s' % (self.... |
import os
import gevent
import logging
import kazoo.client
import kazoo.exceptions
import kazoo.handlers.gevent
import kazoo.recipe.election
from kazoo.client import KazooState
from kazoo.retry import KazooRetry
from bitarray import bitarray
from cfgm_common.exceptions import ResourceExhaustionError, ResourceExistsErro... |
import itk
from sys import argv, stderr
import os
itk.auto_progress(2)
def main():
if len(argv) < 10:
errMsg = "Missing parameters\n" \
"Usage: %s\n" % (argv[0],) + \
" inputImage outputImage\n" \
" seedX seedY InitialDistance\n" \
" Sigma... |
import sys
import os
import ctypes
from .libpath import find_lib_path
class XLearnError(Exception):
"""Error thrown by xlearn trainer"""
pass
def _load_lib():
"""Load xlearn shared library"""
lib_path = find_lib_path()
if len(lib_path) == 0:
return None
lib = ctypes.cdll.LoadLibrary(lib_... |
"""Cron job implementation of Zulip's incoming email gateway's helper
for forwarding emails into Zulip.
https://zulip.readthedocs.io/en/latest/production/email-gateway.html
The email gateway supports two major modes of operation: An email
server (using postfix) where the email address configured in
EMAIL_GATEWAY_PATTER... |
"""
Provides functionality to emulate keyboard presses on host machine.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/keyboard/
"""
import voluptuous as vol
from homeassistant.const import (
SERVICE_MEDIA_NEXT_TRACK, SERVICE_MEDIA_PLAY_PAUSE,
SE... |
"""Metadata request handler."""
import hashlib
import hmac
import os
from oslo_config import cfg
from oslo_log import log as logging
import six
import webob.dec
import webob.exc
from nova.api.metadata import base
from nova import conductor
from nova import exception
from nova.i18n import _
from nova.i18n import _LE
fro... |
""" Test for the remove.py module in the vcontrol/rest/providers directory """
from os import remove as delete_file
from web import threadeddict
from vcontrol.rest.providers import remove
PROVIDERS_FILE_PATH = "../vcontrol/rest/providers/providers.txt"
class ContextDummy():
env = threadeddict()
env['HTTP_HOST']... |
"""Online evaluation metric module."""
from __future__ import absolute_import
import math
from collections import OrderedDict
import numpy
from .base import numeric_types, string_types
from . import ndarray
from . import registry
def check_label_shapes(labels, preds, wrap=False, shape=False):
"""Helper function for... |
import re
import sys
class URI():
def __init__( self, root_path ):
super().__init__()
if root_path[-1] != '/' or root_path[0] != '/':
raise ValueError( 'root_path must start and end with "/"' )
self.root_path = root_path
self.uri_regex = re.compile( r'^({0}|/)(([a-zA-Z0-9\-_.!~*<>]+/)*)([a-zA-Z0... |
import bz2
import gzip
import os
import random
import shutil
import sys
from helpers import unittest
import mock
import luigi.format
from luigi import LocalTarget
from luigi.local_target import LocalFileSystem
from luigi.target import FileAlreadyExists, MissingParentDirectory
from target_test import FileSystemTargetTes... |
"""'functions call' command."""
from googlecloudsdk.api_lib.functions import util
from googlecloudsdk.calliope import base
from googlecloudsdk.core import properties
class Call(base.Command):
"""Call function synchronously for testing."""
@staticmethod
def Args(parser):
"""Register flags for this command."""
... |
"""The ReCollect Waste integration."""
from __future__ import annotations
from datetime import date, timedelta
from aiorecollect.client import Client, PickupEvent
from aiorecollect.errors import RecollectError
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassista... |
from collections import OrderedDict
from unittest import TestCase
from cypy.graph import Node, relationship_type, Path
from cypy.encoding import cypher_repr, cypher_escape
KNOWS = relationship_type("KNOWS")
LOVES = relationship_type("LOVES")
HATES = relationship_type("HATES")
KNOWS_FR = relationship_type(u"CONNAÎT")
cl... |
import sys
import copy
def solutionWorks(currentSolution, stacksAfterSolution, initialStacks, finalStacks):
for x in range(len(currentSolution)):
i, j = currentSolution[x]
stacksAfterSolution[j].append(stacksAfterSolution[i].pop())
if str(stacksAfterSolution) == str(finalStacks):
return ... |
""" Tests for swift.common.storage_policies """
import contextlib
import six
import logging
import unittest
import os
import mock
from functools import partial
from six.moves.configparser import ConfigParser
from tempfile import NamedTemporaryFile
from test.unit import patch_policies, FakeRing, temptree, DEFAULT_TEST_E... |
"""Support for Switchbot bot."""
from __future__ import annotations
import logging
from typing import Any
from switchbot import Switchbot # pylint: disable=import-error
import voluptuous as vol
from homeassistant.components.switch import (
DEVICE_CLASS_SWITCH,
PLATFORM_SCHEMA,
SwitchEntity,
)
from homeassi... |
"""Support for Zigbee switches."""
import voluptuous as vol
from homeassistant.components.switch import SwitchDevice
from homeassistant.components.zigbee import (
ZigBeeDigitalOut, ZigBeeDigitalOutConfig, PLATFORM_SCHEMA)
DEPENDENCIES = ['zigbee']
CONF_ON_STATE = 'on_state'
DEFAULT_ON_STATE = 'high'
DEPENDENCIES = ... |
from math import sqrt
def getActionScore(action):
if action == "rec":
return 0
elif action == "click" :
return 1
else:
return 2
def compute_interaction(data):
interaction = {}
for line in data:
(userA,userB,times,action) = line.split(' ')
action = action[:-1]
key = userB + " " + actio... |
def make_name(name: str) -> str:
# Sample function parameter name in delete_specialist_pool_sample
name = name
return name |
import subprocess
import pytest
from utils import *
@all_available_simulators()
def test_filter(tmp_path, simulator):
unit_test = tmp_path.joinpath('some_unit_test.sv')
unit_test.write_text('''
module some_unit_test;
import svunit_pkg::*;
`include "svunit_defines.svh"
string name = "some_ut";
svunit_tes... |
import asyncio
async def display_date(who, num):
i = 0
while True:
if i > num:
return
print('{}: Before loop {}'.format(who, i))
await asyncio.sleep(1)
i += 1
loop = asyncio.get_event_loop()
asyncio.ensure_future(display_date('AAA', 4))
asyncio.ensure_future(display_d... |
from __future__ import (nested_scopes, generators, division, absolute_import, with_statement,
print_function, unicode_literals)
from contextlib import contextmanager
import os
import unittest2 as unittest
from pants.fs.fs import expand_path
from pants.util.contextutil import environment_as, push... |
import random
import socket
import base64
import time
from threading import Lock
import six
import dns
import dns.exception
import dns.zone
import eventlet
from dns import rdatatype
from oslo_log import log as logging
from oslo_config import cfg
from designate import context
from designate import exceptions
from design... |
"""Defines input readers for MapReduce."""
__all__ = [
"AbstractDatastoreInputReader",
"ALLOW_CHECKPOINT",
"BadReaderParamsError",
"BlobstoreLineInputReader",
"BlobstoreZipInputReader",
"BlobstoreZipLineInputReader",
"COUNTER_IO_READ_BYTES",
"COUNTER_IO_READ_MSEC",
"DatastoreEntityIn... |
from ducktape.mark import parametrize
from ducktape.utils.util import wait_until
from kafkatest.services.console_consumer import ConsoleConsumer
from kafkatest.services.kafka import KafkaService
from kafkatest.services.verifiable_producer import VerifiableProducer
from kafkatest.services.zookeeper import ZookeeperServi... |
import shelve
import os
import re
from resource_api.interfaces import Resource as BaseResource, Link as BaseLink, AbstractUriPolicy
from resource_api.schema import StringField, DateTimeField, IntegerField
from resource_api.service import Service
from resource_api.errors import ValidationError
RE_SHA1 = re.compile("^[a-... |
'''
Integration Test for scheduler reboot VM in HA mode.
@author: Quarkonics
'''
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_state as test_state
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.operations.resource_operations as res_ops
import zstackwoodpecker.zstack_t... |
import os.path
import sys
import types
import getopt
from getopt import GetoptError
import text_file
import regex_utils
import string_utils as str_utils
def grep(target, pattern, number = False, model = 'e'):
'''
grep: print lines matching a pattern
@param target:string list or text file name
@param pat... |
from tempest.common.utils import data_utils
from tempest import config
from tempest.openstack.common import log
from tempest.scenario import manager
from tempest import test
CONF = config.CONF
LOG = log.getLogger(__name__)
class TestVolumeBootPattern(manager.ScenarioTest):
"""
This test case attempts to reprodu... |
"""Log entries within the Google Stackdriver Logging API."""
import collections
import json
import re
from google.protobuf.any_pb2 import Any
from google.protobuf.json_format import MessageToDict
from google.protobuf.json_format import Parse
from google.cloud.logging.resource import Resource
from google.cloud._helpers ... |
import os
import argparse
import glob
import subprocess
import pdb
"""
This is a script to convert jp2 to png for Mitra's Data. \
We use Kakadu software for this script. Kakadu only runs on Ubuntu \
and has to have the library added to shared path.
"""
def main():
parser = argparse.ArgumentParser(description='C... |
import functools
from keystone.common import json_home
from keystone.common import wsgi
from keystone.contrib.federation import controllers
build_resource_relation = functools.partial(
json_home.build_v3_extension_resource_relation,
extension_name='OS-FEDERATION', extension_version='1.0')
build_parameter_relati... |
"""Command-line interface to the OpenStack APIs"""
import getpass
import logging
import sys
import traceback
from cliff import app
from cliff import command
from cliff import complete
from cliff import help
import openstackclient
from openstackclient.common import clientmanager
from openstackclient.common import comman... |
from model.project import Project
def test_add_project(app):
project=Project(name="students_project", description="about Project")
try:
ind = app.project.get_project_list().index(project)
app.project.delete_named_project(project)
except ValueError:
pass
old_projects = app.projec... |
import random
import unittest
import networkx
from mininet.topo import Topo
from clib.mininet_test_watcher import TopologyWatcher
from clib.mininet_test_base_topo import FaucetTopoTestBase
class FaucetFaultToleranceBaseTest(FaucetTopoTestBase):
"""
Generate a topology of the given parameters (using build_net & ... |
from common_openstack import OpenStackTest
class ServerTest(OpenStackTest):
def test_server_query(self):
factory = self.replay_flight_data()
p = self.load_policy({
'name': 'all-servers',
'resource': 'openstack.server'},
session_factory=factory)
resources =... |
from oslo_serialization import jsonutils
from oslo_utils import versionutils
from nova.db import api as db
from nova import exception
from nova.objects import base
from nova.objects import fields
@base.NovaObjectRegistry.register
class MigrationContext(base.NovaPersistentObject, base.NovaObject):
"""Data representi... |
from Headset import Headset
import logging
import time
puerto = 'COM3'
headset = Headset(logging.INFO)
try:
headset.connect(puerto, 115200)
except Exception, e:
raise e
print "Is conected? " + str(headset.isConnected())
print "-----------------------------------------"
headset.startReading(persist_data=True)
ti... |
"""
==========================
RecoBundles80 using AFQ API
==========================
An example using the AFQ API to run recobundles with the
`80 bundle atlas <https://figshare.com/articles/Advanced_Atlas_of_80_Bundles_in_MNI_space/7375883>`_.
"""
import os.path as op
import plotly
from AFQ.api.group import GroupAFQ
i... |
import struct, time
from warpnet_common_params import *
from warpnet_client_definitions import *
from twisted.internet import reactor
import binascii
STRUCTID_CONTROL = 0x13
STRUCTID_CONTROL_ACK = 0x14
STRUCTID_COMMAND = 0x17
STRUCTID_COMMAND_ACK = 0x18
STRUCTID_OBSERVE_BER = 0x24
STRUCTID_OBSERVE_BER_REQ = 0x25
STRUCT... |
from __future__ import unicode_literals
import unittest
import io
from lxml import isoschematron, etree
from packtools.catalogs import SCHEMAS
SCH = etree.parse(SCHEMAS['sps-1.3'])
def TestPhase(phase_name, cache):
"""Factory of parsed Schematron phases.
:param phase_name: the phase name
:param cache: mappi... |
import hashlib
import os.path
import sys
from requestbuilder import Arg
from requestbuilder.exceptions import ArgumentError
from requestbuilder.mixins import FileTransferProgressBarMixin
import six
from euca2ools.commands.s3 import S3Request
import euca2ools.bundle.pipes
class GetObject(S3Request, FileTransferProgressB... |
import cPickle
import gzip
import time
import os
import sys
import cPickle as pickle
import gc
import numpy as np
from time import sleep
import auc
import theano
import theano.tensor as T
from theano.tensor.signal import downsample
from theano.tensor.nnet import conv
from theano.ifelse import ifelse
import theano.print... |
"""Tests for LUBackup*"""
from ganeti import constants
from ganeti import objects
from ganeti import opcodes
from ganeti import query
from testsupport import *
import testutils
class TestLUBackupPrepare(CmdlibTestCase):
@patchUtils("instance_utils")
def testPrepareLocalExport(self, utils):
utils.ReadOneLineFile... |
from __future__ import absolute_import, print_function
import logging
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from sentry.pipeline import Pipeli... |
__all__ = ['quantity_input']
import inspect
from astropy.utils.decorators import wraps
from astropy.utils.misc import isiterable
from .core import Unit, UnitBase, UnitsError, add_enabled_equivalencies
from .physical import _unit_physical_mapping
def _get_allowed_units(targets):
"""
From a list of target units (... |
from __future__ import absolute_import
import unittest
import bokeh.resources as resources
from bokeh.resources import _get_cdn_urls
WRAPPER = """Bokeh.$(function() {
foo
});"""
WRAPPER_DEV = '''require(["jquery", "main"], function($, Bokeh) {
Bokeh.set_log_level("info");
Bokeh.$(function() {
foo
})... |
import pytest
from datetime import datetime
import pytz
import platform
import os
import numpy as np
import pandas as pd
from pandas import compat, DataFrame
from pandas.compat import range
pandas_gbq = pytest.importorskip('pandas_gbq')
PROJECT_ID = None
PRIVATE_KEY_JSON_PATH = None
PRIVATE_KEY_JSON_CONTENTS = None
if ... |
import networkx as nx
import matplotlib.pyplot as plt
try:
import pygraphviz
from networkx.drawing.nx_agraph import graphviz_layout
except ImportError:
try:
import pydot
from networkx.drawing.nx_pydot import graphviz_layout
except ImportError:
raise ImportError("This example need... |
import re
from six import text_type
"""Translate strings to and from SOAP 1.2 XML name encoding
Implements rules for mapping application defined name to XML names
specified by the w3 SOAP working group for SOAP version 1.2 in
Appendix A of "SOAP Version 1.2 Part 2: Adjuncts", W3C Working Draft
17, December 2001, <http:... |
"""
templatetricks.override_autoescaped
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Override which templates are autoescaped
http://flask.pocoo.org/snippets/41/
"""
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
from flask import Flask
class JHtmlEscapingFla... |
""" Query modules mapping functions to their query strings
structured:
module_name { query_string: function_for_query }
"""
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from future import standard_library
standard_li... |
"""
RINGFILTER determines the center coordinates of a ring, bins the ring radially and computes its power spectrum, and allows the user to select a smoothing filter for the ring. It uses T. Williams code. The code assumes all the files are in the same directory. Also assumes that if there is a config file, it is also ... |
__author__ = 'keltonhalbert, wblumberg'
from sharppy.viz import plotSkewT, plotHodo, plotText, plotAnalogues
from sharppy.viz import plotThetae, plotWinds, plotSpeed, plotKinematics #, plotGeneric
from sharppy.viz import plotSlinky, plotWatch, plotAdvection, plotSTP, plotWinter
from sharppy.viz import plotSHIP, plotSTP... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.