code stringlengths 1 199k |
|---|
import copy
import gzip
import jinja2
import json
import mock
import os
import pytest
import shutil
import swiftclient.exceptions
import tarfile
import tempfile
import zpmlib
try:
from cStringIO import StringIO as BytesIO
except ImportError:
from io import BytesIO
from zpmlib import zpm, commands
class TestFind... |
from __future__ import print_function
from keras.preprocessing import sequence
from keras.models import Sequential
from keras.layers import Dense, SpatialDropout1D,Dropout, Activation
from keras.layers import Embedding
from keras.layers import Conv1D, GlobalMaxPooling1D
from sklearn.metrics import roc_curve, auc
import... |
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
class Person(User):
internal_id = models.CharField(max_length=25, null=True, blank=True)
verified = models.NullBooleanField(default=False)
approval_date = models.DateTimeField(null=True... |
"""Tests for resized_fuse."""
import tensorflow as tf
from deeplab2.model.layers import resized_fuse
class ResizedFuseTest(tf.test.TestCase):
def test_resize_and_fuse_features(self):
batch, height, width, channels = 2, 11, 11, 6
smaller_height, smaller_width, smaller_channels = 6, 6, 3
larger_height1, lar... |
class Drawable(object):
def draw(self, display_screen, dT):
pass |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('common', '0002_citation'),
]
operations = [
migrations.AddField(
model_name='citation',
name='page_name',
field=models.TextField(default=None),
p... |
import pcbnew
from . import toggle_visibility
class ToggleVisibilityPlugin(pcbnew.ActionPlugin):
def defaults(self):
self.name = "Toggle visibility of value/reference (of selected modules)"
self.category = "A descriptive category name"
self.description = "This plugin toggles the visibility o... |
from collections import deque, OrderedDict
import numpy as np
from rlkit.core.eval_util import create_stats_ordered_dict
from rlkit.data_management.path_builder import PathBuilder
from rlkit.samplers.data_collector.base import StepCollector
class MdpStepCollector(StepCollector):
def __init__(
self,
... |
import itchat, time, re
from itchat.content import *
import urllib2, urllib
import json
from watson_developer_cloud import ConversationV1
response={'context':{}}
@itchat.msg_register([TEXT])
def text_reply(msg):
global response
request_text = msg['Text'].encode('UTF-8')
conversation = ConversationV1(
username='9... |
"""Abstract API specification for XManager implementations.
Each implementation of the XManager API should override the abstract methods.
Users are normally expected to have the following pair of imports:
```
from xmanager import xm
from xmanager import xm_foo
```
"""
import abc
import asyncio
from concurrent import fu... |
"""
Provides functions for evaluating the 'fitness'
of ec2 instances. This module really just provides
functions for deciding which instance is best to be
killed by the autoscaler.
"""
def sort_by_system_instance_health(instances):
return sorted(
instances,
key=lambda i: (
i.instance_sta... |
"""VexFlow labeled data generation.
Wraps the node.js generator, which generates a random measure of music as SVG,
and the ground truth glyphs present in the image as a `Page` message.
Each invocation generates a batch of images. There is a tradeoff between the
startup time of node.js for each invocation, and keeping t... |
from orchestra.workflow import Step
from orchestra.workflow import Workflow
from simple_workflow.crawl import crawl_page
crawl_step = Step(
slug='crawl',
name='Web Crawling',
description='Find an awesome image on a website',
worker_type=Step.WorkerType.MACHINE,
creation_depends_on=[],
function=c... |
import base64
from xdrlib import Packer, Unpacker
from ..type_checked import type_checked
from .liquidity_pool_withdraw_result_code import LiquidityPoolWithdrawResultCode
__all__ = ["LiquidityPoolWithdrawResult"]
@type_checked
class LiquidityPoolWithdrawResult:
"""
XDR Source Code::
union LiquidityPoolW... |
from google.cloud import aiplatform
def get_model_evaluation_text_classification_sample(
project: str,
model_id: str,
evaluation_id: str,
location: str = "us-central1",
api_endpoint: str = "us-central1-aiplatform.googleapis.com",
):
"""
To obtain evaluation_id run the following commands wher... |
"""Support for HomematicIP Cloud switches."""
import logging
from homematicip.aio.device import (
AsyncBrandSwitchMeasuring, AsyncFullFlushSwitchMeasuring, AsyncMultiIOBox,
AsyncOpenCollector8Module, AsyncPlugableSwitch,
AsyncPlugableSwitchMeasuring)
from homematicip.aio.group import AsyncSwitchingGroup
fro... |
from oslo.config import cfg
from nova.openstack.common.gettextutils import _
from nova.openstack.common import log as logging
from nova.scheduler.solvers import constraints
CONF = cfg.CONF
CONF.import_opt("max_instances_per_host",
"nova.scheduler.filters.num_instances_filter")
LOG = logging.getLogger(__name__)
... |
"""
ZFS Storage Appliance Cinder Volume Driver
"""
import ast
import math
from oslo_config import cfg
from oslo_log import log
from oslo_serialization import base64
from oslo_utils import units
import six
from cinder import exception
from cinder import utils
from cinder.i18n import _, _LE, _LI, _LW
from cinder.image im... |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Cloud'
db.create_table(u'cloudslave_cloud', (
('name', self.gf('django.db.models.fields.CharField')(max_len... |
"""Copyright 2009 Chris Davis
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distrib... |
import arcpy
from arcpy import env
env.workspace = "C:\Users\Ewan\Desktop\SFTPDST5\MapFiles"
try:
# Set the local variable
in_Table = "Topography.csv"
x_coords = "x"
y_coords = "y"
out_Layer = "Topography_Layer"
saved_Layer = "c:\Users\Ewan\Desktop\SFTPDST5\Mapfiles\Topography.lyr"
# Set the... |
from sqlalchemy import *
from sqlalchemy import sql, schema
from sqlalchemy.sql import compiler
from test.lib import *
class QuoteTest(fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = 'default'
@classmethod
def setup_class(cls):
# TODO: figure out which databases/which identifiers allow special... |
import logging
import io
from time import sleep
import json
import requests
from . import *
logging.basicConfig(filename='terminal.log', level=logging.DEBUG)
class PyTerminal():
"""
This class allows the execution of a command in the same way as the web-cli does. The return is a
CommandOutput instance which... |
import os
import pytest
from mock import patch
from polyaxon.env_vars.keys import (
POLYAXON_KEYS_GIT_CREDENTIALS,
POLYAXON_KEYS_RUN_INSTANCE,
)
from polyaxon.exceptions import PolyaxonContainerException
from polyaxon.init.git import (
create_code_repo,
get_clone_url,
has_cred_access,
has_ssh_ac... |
"""
SlipStream Client
=====
Copyright (C) 2015 SixSq Sarl (sixsq.com)
=====
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by... |
import sys
import os
import shlex
sys.path.insert(0, os.path.abspath(".."))
sys.path.insert(0, os.path.abspath("."))
__version__ = ""
needs_sphinx = "1.5.5"
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.autosummary",
"sphinx.ext.intersphinx",
"sphinx.ext.coverage",
"sphinx.ext.doctest",
"sphi... |
"""Script for deploying cloud functions."""
from __future__ import print_function
import subprocess
import sys
from turbinia import config
index_file = './index.yaml'
if len(sys.argv) > 1:
function_names = [sys.argv[1]]
else:
function_names = ['gettasks', 'closetasks']
config.LoadConfig()
for cloud_function in func... |
"""
MoinMoin - Supporting function for Python magic
@copyright: 2002 Juergen Hermann <jh@web.de>
@license: GNU GPL, see COPYING for details.
"""
def isImportable(module):
""" Check whether a certain module is available.
"""
try:
__import__(module)
return 1
except ImportError:... |
import matplotlib as mpl
mpl.use('Agg')
import survivalstan
from stancache import stancache
import numpy as np
from nose.tools import ok_
from functools import partial
num_iter = 1000
from .test_datasets import load_test_dataset
model_code = survivalstan.models.exp_survival_model
make_inits = None
def test_model():
... |
from .data_connector import DataConnector
from .runtime_data_connector import RuntimeDataConnector
from .file_path_data_connector import FilePathDataConnector
from .configured_asset_file_path_data_connector import (
ConfiguredAssetFilePathDataConnector,
)
from .inferred_asset_file_path_data_connector import (
I... |
"""Initial migration
Revision ID: 464e951dc3b8
Revises: None
Create Date: 2014-08-05 17:41:34.470183
"""
revision = '464e951dc3b8'
down_revision = None
from alembic import op # noqa: E402
import sqlalchemy as sa # noqa: E402
def upgrade():
op.create_table(
'states',
sa.Column('name', sa.String(len... |
"""Provides the logic used by all the search_next commands."""
import re
from aquilon.utils import force_int
int_re = re.compile(r'^(\d+)')
def search_next(session, cls, attr, value, start, pack, locked=False,
**filters):
q = session.query(cls).filter(attr.startswith(value))
if filters:
... |
"""Handles tarring up documentation directories."""
import subprocess
from docuploader import shell
def compress(directory: str, destination: str) -> subprocess.CompletedProcess:
"""Compress the given directory into the tarfile at destination."""
# Note: we don't use the stdlib's "tarfile" module for performanc... |
"""Utilities used for translating operators from Onnx to Mxnet."""
from __future__ import absolute_import as _abs
from .... import symbol
from .... import module
from .... import context
from .... import ndarray as nd
from .... import io
def _fix_attribute_names(attrs, change_map):
"""
Change attribute name... |
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^webcam/', include('webCam.urls')),
] |
"""
Kill Bill
Kill Bill is an open-source billing and payments platform # noqa: E501
OpenAPI spec version: 0.22.22-SNAPSHOT
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import re # noqa: F401
import six
from killbill.api_client import ApiC... |
from django import forms
class PartnerLogoForm(forms.Form):
partner_logo = forms.ImageField(
label='Select a file',
) |
import sys
import unittest
import os
import os.path
import urllib2
import time
sys.path.append('.')
import s3iam
from urlparse import urlparse
class S3GrabberTest(unittest.TestCase):
def test_example_sign(self):
"""Test with example data"""
req = urllib2.Request("https://johnsmith.s3.amazonaws.com/p... |
from synaps.monitor.api import API
from synaps.utils import (validate_email, validate_international_phonenumber,
validate_instance_action,
validate_groupnotification_action)
import json
class Datapoint(object):
"""
The Datapoint data type encapsulates the st... |
import json
import re
from lib.utils import util
def parse_record(parent_field, record):
field_names = []
field_values = []
for name in record:
if isinstance(record[name], dict):
new_parent_field = parent_field.copy()
new_parent_field.append(name)
names = " ".join... |
"""This example updates budget delivery method for a given campaign. To get
campaigns, run get_campaigns.py.
Tags: CampaignService.mutate
"""
__author__ = 'api.kwinter@gmail.com (Kevin Winter)'
import os
import sys
sys.path.insert(0, os.path.join('..', '..', '..', '..', '..'))
from adspygoogle import AdWordsClient
camp... |
import os
import sys
import socket
import netaddr
from netaddr import AddrFormatError, IPAddress
from pycalico.datastore_datatypes import IPPool
from pycalico.ipam import IPAMClient
from pycalico.util import get_host_ips, validate_asn
DEFAULT_IPV4_POOL = IPPool("192.168.0.0/16")
DEFAULT_IPV6_POOL = IPPool("fd80:24e2:f9... |
from ex import *
from ex.alg.common import svdex
def RPCA(D, lam = None, tol = 1e-7, maxIter = 500):
'''Yi Ma's robust pca
return (L, SingularValues(L))
'''
m, n = D.shape
maxmn, minmn = (max(m, n), min(m, n))
lam = float(lam) if lam is not None else 1.0
log.info('RPCA for %dx%d matrix. lamb... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from isl import augment
from isl import test_util
from isl import util
flags = tf.flags
test = tf.test
lt = tf.contrib.labeled_tensor
FLAGS = flags.FLAGS
class CorruptTest(test_util.Base)... |
from functools import wraps
from logging import getLogger
logger = getLogger(__name__)
__author__ = 'marcos.costa'
class request_logger(object):
def __init__(self, method=None):
self.method = method
def __call__(self, func):
method = self.method
if method is None:
method = fu... |
import npyscreen
import os
import re
import sys
import time
from docker.errors import DockerException
from npyscreen import notify_confirm
from threading import Thread
from vent.api.actions import Action
from vent.api.menu_helpers import MenuHelper
from vent.helpers.meta import Containers
from vent.helpers.meta import ... |
"""
This is CoGroupByKey load test with Synthetic Source. Besides of the standard
input options there are additional options:
* project (optional) - the gcp project in case of saving
metrics in Big Query (in case of Dataflow Runner
it is required to specify project of runner),
* metrics_namespace (optional) - name of B... |
import asyncio
import itertools
from . import exceptions
async def get_files_for_tasks(task_list, file_list, max_workers):
no_files_found = True
async def process(task_fname):
task, fname = task_fname
try:
fobj = await task.file(fname)
except exceptions.SlaveDoesNotExist:
... |
from oslo_config import cfg
from oslo_log import log
from oslo_utils import timeutils
from ceilometer.agent import plugin_base
from ceilometer.i18n import _LW
from ceilometer import neutron_client
from ceilometer import sample
LOG = log.getLogger(__name__)
cfg.CONF.import_group('service_types', 'ceilometer.neutron_clie... |
"""Bleeding-edge version of Unicode Character Database.
Provides an interface similar to Python's own unicodedata package, but with
the bleeding-edge data. The implementation is not efficient at all, it's
just done this way for the ease of use. The data is coming from bleeding
edge version of the Unicode Standard not y... |
__project_group_id__ = "org.apache.systemml"
__project_artifact_id__ = "systemml"
__project_version__ = "0.13.0-incubating-SNAPSHOT" |
'''
author: Jimmy
contact: 234390130@qq.com
file: storage.py
time: 2017/9/4 下午3:18
description:
'''
__author__ = 'Jimmy'
import pymongo
from ctp.ctp_struct import *
from bson import json_util as jsonb
from utils.tools import *
def _getDataBase():
client = pymongo.MongoClient(host='127.0.0... |
"""
Test the "snabb lwaftr monitor" subcommand. Needs a NIC name and a TAP interface.
1. Execute "snabb lwaftr run" in on-a-stick mode and with the mirror option set.
2. Run "snabb lwaftr monitor" to set the counter and check its output.
"""
from random import randint
from subprocess import call, check_call
import unit... |
import uuid
import pytest
from kazoo.testing import KazooTestCase
from kazoo.tests.util import CI_ZK_VERSION
class KazooQueueTests(KazooTestCase):
def _makeOne(self):
path = "/" + uuid.uuid4().hex
return self.client.Queue(path)
def test_queue_validation(self):
queue = self._makeOne()
... |
"""
Exception for errors when there's an error in the Result
"""
from qiskit.exceptions import QiskitError
class ResultError(QiskitError):
"""Exceptions raised due to errors in result output.
It may be better for the Qiskit API to raise this exception.
Args:
error (dict): This is the error record as... |
from setuptools import setup, find_packages
setup(
name="HtmlNode",
version="0.1.8",
packages=find_packages(),
description="A simple Python HTML generator",
author="Hing-Lung Lau",
author_email="lung220@gmail.com",
url="http://github.com/hllau/html_node",
license="Apache v2",
keyword... |
import sys
sys.path.insert(1, "../../")
import h2o
def vec_show(ip,port):
# Connect to h2o
h2o.init(ip,port)
iris = h2o.import_frame(path=h2o.locate("smalldata/iris/iris_wheader.csv"))
print "iris:"
iris.show()
###################################################################
res = 2 - iri... |
class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
def helper(inorderL, inorderR):
# base case
if inorderL >= inorderR:
return None
nonlocal postorder
curr = postorder.pop()
root = TreeNode(cu... |
from insights.parsers.hostname import Hostname
from insights.tests import context_wrap
HOSTNAME = "rhel7.example.com"
HOSTNAME_SHORT = "rhel7"
def test_hostname():
data = Hostname(context_wrap(HOSTNAME))
assert data.fqdn == "rhel7.example.com"
assert data.hostname == "rhel7"
assert data.domain == "examp... |
"""
DLRN API
DLRN API client
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
class Params(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the cl... |
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'Conclusion.title'
db.alter_column(u'itest_conclusion', 'title', self.gf('django.db... |
from f5.bigip.tm.asm.policies.character_sets import Character_Sets
from f5.sdk_exception import UnsupportedOperation
import mock
import pytest
@pytest.fixture
def FakeChar():
fake_policy = mock.MagicMock()
fake_e = Character_Sets(fake_policy)
fake_e._meta_data['bigip'].tmos_version = '11.6.0'
return fak... |
from typing import Optional, List
def a(x):
# type: (List[int]) -> List[str]
return <warning descr="Expected type 'List[str]', got 'List[List[int]]' instead">[x]</warning>
def b(x):
# type: (int) -> List[str]
return <warning descr="Expected type 'List[str]', got 'List[int]' instead">[1,2]</warning>
def ... |
from wx import wx
from Converter import Converter
class GameMenuViewModel(object):
def __init__(self, viewSetter):
self.viewSetter = viewSetter
def displayGameMenu(self):
wx.CallAfter(self.viewSetter.setView, "GameMenu")
def animateCurrentPrices(self, currentPricesJavaMap):
wx.CallAf... |
class Backend(object):
'''
Backend type with a plugin and zero or more parameters (Parameter functionality is TBD.
Links to categories handled by this backend
'''
def __init__(self, plugin, params):
self._plugin = plugin
self._params = params
self._categories = []
@proper... |
"""Unit tests for base class NrfMatterDevice."""
from unittest import mock
from absl.testing import parameterized
from gazoo_device import errors
from gazoo_device.base_classes import nrf_matter_device
from gazoo_device.capabilities import device_power_default
from gazoo_device.capabilities import pwrpc_common_default
... |
"""Test suite for the custom import logic."""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import os
import sys
import require
def test_patch_replaces_and_restores():
"""Ensure the import function is patched and ... |
import pigpio
class Car(object):
PINS = ['left_pin', 'right_pin', 'forward_pin', 'backward_pin',
'enable_moving', 'enable_turning']
def __init__(self, left_pin, right_pin, forward_pin, backward_pin,
enable_moving, enable_turning, start_power=65):
self._left_pin = left_pin
... |
from __future__ import division
from mapproxy.compat.image import Image, transform_uses_center
from mapproxy.image import ImageSource, image_filter
from mapproxy.srs import make_lin_transf, bbox_equals
class ImageTransformer(object):
"""
Transform images between different bbox and spatial reference systems.
... |
import numpy as np
a = np.array([1,2])
b = np.array([3,4])
np.inner(a, b)
a.dot(b)
a = np.array([1,2])
b = np.array([3,4])
np.outer(a, b)
m = np.array([[1,2], [3,4]])
np.linalg.inv(m)
m = np.array([[1,2], [3,4]])
minv = np.linalg.inv(m)
m.dot(minv)
m = np.array([[1,2], [3,4]])
np.diag(m)
m = np.array([1,2])
np.diag(m)
... |
import contextlib
import inspect
import os
import shutil
import tempfile
import fixtures
import mock
from oslo_concurrency import lockutils
from oslo_config import cfg
from oslo_config import fixture as config_fixture
from oslo_utils import units
from oslo_utils import uuidutils
from nova import context
from nova impor... |
from luigi.contrib.ssh import RemoteContext
import unittest
import subprocess
class TestMockedRemoteContext(unittest.TestCase):
def test_subprocess_delegation(self):
""" Test subprocess call structure using mock module """
orig_Popen = subprocess.Popen
self.last_test = None
def Popen... |
"""remove_issue tests."""
import unittest
import flask
import webtest
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.tests.test_libs import helpers as test_helpers
from clusterfuzz._internal.tests.test_libs import test_utils
from handlers.testcase_detail import remove_issue
from libs ... |
import logging
import secrets
from typing import List, Optional, Tuple
from django.conf import settings
from django.http import HttpRequest, HttpResponse
from django.shortcuts import redirect, render
from django.utils.cache import patch_cache_control
from zerver.context_processors import get_valid_realm_from_request
fr... |
import json
from typing import TYPE_CHECKING, Optional
from boxsdk.util.text_enum import TextEnum
from boxsdk.exception import BoxAPIException
from .base_object import BaseObject
if TYPE_CHECKING:
from boxsdk.object.user import User
from boxsdk.object.terms_of_service_user_status import TermsOfServiceUserStatus... |
import json
import os
import time
import psutil
import pyautogui
pubg_url = 'steam://rungameid/578080'
PROCNAME = "TslGame.exe"
CRASH_PROCNAME = "BroCrashReporter.exe"
debug_directory = "debug_screenshots"
start_state = "HELLO"
play_state = "PLAYING"
play_timer_max = 60 * 3
matching_state = "MATCHING"
matching_timer_ma... |
from datetime import datetime, timedelta
import logging
from lxml import etree
from mock import patch, Mock
import os
from rdflib import URIRef, Graph as RdfGraph, XSD, Literal
from rdflib.namespace import Namespace
import re
import tempfile
import six
from eulfedora import models
from eulfedora.api import ApiFacade
fr... |
from __future__ import unicode_literals
from netaddr import EUI, AddrFormatError
from django import forms
from django.core.exceptions import ValidationError
class MACAddressFormField(forms.Field):
default_error_messages = {
'invalid': "Enter a valid MAC address.",
}
def to_python(self, value):
... |
from bcc import BPF, _get_num_open_probes, TRACEFS
import os
import sys
from unittest import main, TestCase
class TestKprobeCnt(TestCase):
def setUp(self):
self.b = BPF(text="""
int wololo(void *ctx) {
return 0;
}
""")
self.b.attach_kprobe(event_re="^vfs_.*", fn_nam... |
from django.db import migrations, models
import django.db.models.deletion
def non_reversible_migration(apps, schema_editor):
"""Operation to "reverse" an unreversible change"""
pass
def remove_non_sadd_disaggregations(apps, schema_editor):
DisaggregationType = apps.get_model('indicators', 'DisaggregationTyp... |
import logging
import os
import shutil
import subprocess
import time
from apptools.preferences.preference_binding import bind_preference
from pyface.confirmation_dialog import confirm
from pyface.constant import OK, YES
from pyface.directory_dialog import DirectoryDialog
from pyface.message_dialog import warning
from t... |
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../.."))
os.environ['DJANGO_SETTINGS_MODULE'] = 'rest_framework_nested.runtests.settings'
import django
from django.conf import settings
from django.test.utils import get_runner
def usage():
return """
Usage: python runtests.py [UnitT... |
import json
import re
import uuid
import webob.dec
import webob.exc
from ooi import utils
import ooi.wsgi
application_url = "https://foo.example.org:8774/ooiv1"
tenants = {
"foo": {"id": uuid.uuid4().hex,
"name": "foo"},
"bar": {"id": uuid.uuid4().hex,
"name": "bar"},
"baz": {"id": u... |
import fixtures
import mock
from oslo_utils.fixture import uuidsentinel as uuids
from oslo_utils import timeutils
from nova.api.openstack.compute import admin_actions
from nova.compute import vm_states
from nova.tests.unit.api.openstack import fakes
from nova.tests.unit import fake_instance
from nova.tests.unit.policie... |
print "I could have code like this." # and the comment after is ignored
print "This will run." |
import commands
import sys
from docopt import docopt
from sdutil.log_util import getLogger
from sdutil.date_util import *
reload(sys)
sys.setdefaultencoding('utf-8')
from elasticsearch import Elasticsearch
from pdb import *
import requests
import json
logger = getLogger(__name__, __file__)
"""
host like:"http://172.17.... |
r"""Run training loop.
"""
import os
import random
import time
from absl import app
from absl import flags
from absl import logging
import numpy as np
import tensorflow as tf
from tf_agents.policies import random_tf_policy
from tf_agents.replay_buffers import tf_uniform_replay_buffer
from tf_agents.specs.tensor_spec im... |
"""
Test that SBProcess.LoadImageUsingPaths works correctly.
"""
from __future__ import print_function
import os
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
@skipIfWindows # The Windows platform doesn't implement DoLoadImage.
class Load... |
"""
Author: AsherYang
Email: ouyangfan1991@gmail.com
Date: 2018/6/27
Desc: 后台管理数据库操作类
"""
import sys
sys.path.append('../')
from util import DbUtil
from util.DateUtil import DateUtil
class AdminDao:
def __init__(self):
pass
# 根据管理员电话号码查询管理员信息
def queryByTel(self, admin_tel):
query = 'SE... |
"""The tests for the emulated Hue component."""
import asyncio
import json
from unittest.mock import patch
import pytest
from homeassistant import bootstrap, const, core
import homeassistant.components as core_components
from homeassistant.components import (
emulated_hue, http, light, script, media_player, fan
)
f... |
from __future__ import unicode_literals
from django.db import migrations, models
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('reddit', '0004_auto_20160518_0017'),
]
operations = [
migrations.AlterField(
model_name='redditcredentials',... |
def run(*args, **kwargs):
_run(*args, **kwargs)
def _run(task=None):
if task is None:
return
task() |
import eventlet
from oslo_config import cfg
import oslo_messaging as messaging
from osprofiler import profiler
from senlin.common import consts
from senlin.common import context
JsonPayloadSerializer = messaging.JsonPayloadSerializer
TRANSPORT = None
NOTIFICATION_TRANSPORT = None
NOTIFIER = None
class RequestContextSer... |
"""
Class for parallelizing RandomizedSearchCV jobs in scikit-learn
"""
from sklearn.model_selection import ParameterSampler
from spark_sklearn.base_search import SparkBaseSearchCV
class RandomizedSearchCV(SparkBaseSearchCV):
"""Randomized search on hyper parameters.
RandomizedSearchCV implements a "fit" and a ... |
from common import *
import testdata
class oldstyle:
def __init__(self, value): self.value = value
def __repr__(self): return "oldstyle(%s)" % self.value
def __add__(self, other): return self.value + other
def __sub__(self, other): return self.value - other
... |
from .fields import BitField, Field
from nettest.exceptions import NettestError
import struct
class PacketMeta(type):
def __new__(cls, name, bases, attrs):
fields = attrs.get('fields')
if fields is None:
raise NettestError(_("packet class must have 'fields' field"))
_fields = []
... |
from setuptools import setup, find_packages
exec(open('react/version.py').read())
setup(
name='react',
description='Generate fragments of a molecule using smirks',
version=__version__,
packages=find_packages(),
url='https://github.com/3D-e-Chem/python-modified-tanimoto',
author='Stefan Verhoeven... |
import pyxb.binding.generate
import pyxb.utils.domutils
from xml.dom import Node
import os.path
schema_path = os.path.abspath(os.path.join(os.path.dirname(__file__),
'../schemas/particle.xsd'))
code = pyxb.binding.generate.GeneratePython(schema_location=schema_path)
rv = compile(code, 'test', 'e... |
from flask.ext import restful
from . import api
class Welcome(restful.Resource):
def get(self):
return api.send_static_file('index.html') |
import inspect
try:
import ordereddict as collections
except ImportError: # pragma: no cover
import collections # pragma: no cover
class DictSerializableModel(object):
"""A model mixin: class dictionarizable-undictionarizable class mixin.
A class that can be deserialized from a dictionary and... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.