code stringlengths 1 199k |
|---|
import math
import paramiko
import random
import re
import time
import unicodedata
from eventlet import greenthread
from oslo_concurrency import processutils
from oslo_config import cfg
from oslo_log import log as logging
from oslo_serialization import jsonutils as json
from oslo_service import loopingcall
from oslo_ut... |
import json
import os
import stat
import subprocess
import tempfile
from oslo_log import log as logging
from oslo_utils import netutils
import pexpect
import six
from trove.common import cfg
from trove.common.db import models
from trove.common import exception
from trove.common.i18n import _
from trove.common import in... |
"""
DEV SCRIPT
This is a hacky script meant to be run mostly automatically with the option of
interactions.
dev.py is supposed to be a developer non-gui interface into the IBEIS software.
dev.py runs experiments and serves as a scratchpad for new code and quick scripts
TODO:
Test to find typical "good" descriptor s... |
"""Tests for user domain objects."""
from __future__ import absolute_import # pylint: disable=import-only-modules
from __future__ import unicode_literals # pylint: disable=import-only-modules
from core.domain import user_domain
from core.tests import test_utils
import feconf
import utils
class MockModifiableUserData(... |
'''You can easily read off two sample,line coordinates from qview, but ISIS
crop wants one sample,line and then offsets. This just takes two coordinates,
does the math, and then calls crop.'''
import argparse
import subprocess
import sys
from pathlib import Path
def crop(fr, to, samp, line, nsamp, nline):
cmd = ('... |
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_mail import Mail
from flask_moment import Moment
from flask_sqlalchemy import SQLAlchemy
from config import config
import chartkick
bootstrap = Bootstrap()
mail = Mail()
moment = Moment()
db = SQLAlchemy()
def create_app(config_name):
app = Fl... |
__author__ = "Simone Campagna"
import re
from .py23 import BASE_STRING
class Filename(object):
def __init__(self, init):
if isinstance(init, Filename):
filename = init._filename
elif isinstance(init, BASE_STRING):
filename = self._from_string(init)
else:
r... |
"""The Extended Volumes API extension."""
import webob
from webob import exc
from nova.api.openstack import common
from nova.api.openstack.compute.schemas.v3 import extended_volumes
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.api import validation
from nova import compute
fro... |
def main():
return 'main method'
def not_main():
return 'not main'
def also_not_main():
return 'also_not main'
def untested_method():
return 'untested!' |
from django.conf.urls.defaults import *
import re
urlpatterns = patterns(re.sub(r'[^.]*$', "views", __name__),
(r'^$', 'index'),
(r'^(?P<admin>admin)/(?P<user>.*?)/$', 'index'),
(r'^((?P<event_key>.*?)/)?edit/$', 'edit'),
(r'^(?P<ref_key>.*?)/((?P<event_key>.*?)/)?edit/event/$', 'editPureEvent'),
#(... |
import math, cmath
import re
import itertools
import numbers
import random
import numpy, numpy.random # sudo apt-get install python-numpy
from augustus.kernel.unitable import UniTable
import mathtools
import utilities
import color
import containers
class ContainerException(Exception):
"""Run-time errors in containe... |
import uuid
import testtools
from tempest.lib import base as test
from tempest.lib import decorators
from tempest.tests.lib import base
class TestSkipBecauseDecorator(base.TestCase):
def _test_skip_because_helper(self, expected_to_skip=True,
**decorator_args):
class TestFoo... |
"""Selection strategies for training with multiple adversarial representations.
A selector can select one representation for training at each step, and
maintain its internal state for subsequent selections. The state can also be
updated once every K epochs when the model is evaluated on the validation set.
"""
import g... |
"""Utilities for manipulating revision chains in the database."""
import d1_common.types.exceptions
import d1_gmn.app
import d1_gmn.app.did
import d1_gmn.app.model_util
import d1_gmn.app.models
def create_or_update_chain(pid, sid, obsoletes_pid, obsoleted_by_pid):
chain_model = _get_chain_by_pid(pid)
if chain_m... |
import mock
from mock import patch
import uuid
import six
from glance.common import exception
from glance.common import store_utils
from glance.openstack.common import units
import glance.quota
from glance.tests.unit import utils as unit_test_utils
from glance.tests import utils as test_utils
UUID1 = 'c80a1a6c-bd1f-41c... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
module: bigip_snmp_trap
short_description: Manipulate SNMP trap information... |
import logging
from flask import request
from flask import render_template
from relay import app
from relay.decorators import jsonify
from relay.decorators import session_required
from relay.decorators import sanitize_user
from relay.models.relays import add_relay_model
from relay.models.relays import get_relay
from re... |
import mock
from tests.cisco import enable, create_interface_vlan, configuring, configuring_interface_vlan, \
assert_interface_configuration, remove_vlan, create_vlan, set_interface_on_vlan, configuring_interface, \
revert_switchport_mode_access, create_port_channel_interface, configuring_port_channel
from test... |
import json
import os.path
from twisted.enterprise import adbapi
from calvin.runtime.south.async import async
from calvin.utilities.calvinlogger import get_logger
from calvin.runtime.south.calvinsys import base_calvinsys_object
_log = get_logger(__name__)
class PersistentBuffer(base_calvinsys_object.BaseCalvinsysObject... |
import os
import operator
import sys
import uuid
import warnings
from abc import ABCMeta, abstractmethod, abstractproperty
from multiprocessing.pool import ThreadPool
from pyspark import keyword_only, since, SparkContext
from pyspark.ml import Estimator, Predictor, PredictionModel, Model
from pyspark.ml.param.shared im... |
from django.conf.urls import url
from externals.views import (
PartnerVendorNumberAPIView,
PartnerExternalDetailsAPIView,
PartnerBasicInfoAPIView,
)
urlpatterns = [
url(r'^vendor-number/partner/$', PartnerVendorNumberAPIView.as_view(), name="vendor-number-create"),
url(r'^vendor-number/partner/(?P<p... |
"""Tests for init functions."""
from datetime import timedelta
from zoneminder.zm import ZoneMinder
from homeassistant import config_entries
from homeassistant.components.zoneminder import const
from homeassistant.components.zoneminder.common import is_client_in_data
from homeassistant.config_entries import (
ENTRY... |
"""Resource manager for using the add-apt-repository command (part of the
python-software-properties package).
"""
import sys
import os
import os.path
import re
import glob
try:
import engage.utils
except:
sys.exc_clear()
dir_to_add_to_python_path = os.path.abspath((os.path.join(os.path.dirname(__file__)... |
"""Defines the resnet model.
Adapted from
https://github.com/tensorflow/models/tree/master/official/vision/image_classification/resnet.
The following code is based on its v1 version.
"""
import tensorflow.compat.v1 as tf
_BATCH_NORM_DECAY = 0.9
_BATCH_NORM_EPSILON = 1e-5
DEFAULT_VERSION = 2
DEFAULT_DTYPE = tf.float32
C... |
import json
import re
from behave import given, when, then
from behave import use_step_matcher
use_step_matcher("re")
import sure # noqa
from jsonschema import validate
from _lazy_request import LazyRequest
import logging
logging.getLogger("requests").setLevel(logging.WARNING)
@given('(.+) are users')
def step_impl(co... |
"""
Runs an Herald XMPP framework
:author: Thomas Calmant
:copyright: Copyright 2014, isandlaTech
:license: Apache License 2.0
:version: 0.0.4
:status: Alpha
..
Copyright 2014 isandlaTech
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the ... |
"""
Functions for converting numbers with SI units to integers
"""
import copy
import re
si_multipliers = {
None: 1,
'': 1,
'k': 1000 ** 1,
'm': 1000 ** 2,
'g': 1000 ** 3,
't': 1000 ** 4,
'p': 1000 ** 5,
'e': 1000 ** 6,
'z': 1000 ** 7,
'y': 1000 ** 8,
'ki': 1024 ** 1,
'mi... |
import os
import six
import st2tests
from st2common.bootstrap.policiesregistrar import register_policy_types, register_policies
from st2common.models.api.action import ActionAPI, RunnerTypeAPI
from st2common.models.api.policy import PolicyTypeAPI, PolicyAPI
from st2common.persistence.action import Action
from st2common... |
import os
import logging
import setuptools
import distutils.cmd
import subprocess
_PACKAGE_NAME = 'python-ibank',
_PACKAGE_VERSION = '0.0.1'
_LIB_DIR = 'lib'
_BIN_DIR = 'bin'
_DESCRIPTION = ''
_HOME_DIR = os.path.expanduser('~')
print "home:",_HOME_DIR
_HOME_DIR = '/Users/csebenik'
_... |
"""A flow to run checks for a host."""
from grr.lib import aff4
from grr.lib import flow
from grr.lib import rdfvalue
from grr.lib.checks import checks
from grr.proto import flows_pb2
class CheckFlowArgs(rdfvalue.RDFProtoStruct):
protobuf = flows_pb2.CheckFlowArgs
class CheckRunner(flow.GRRFlow):
"""This flow runs ... |
class Config(object):
def __init__(self, bucket, root):
self.bucket = bucket
self.root = root |
from datetime import timedelta
from st2client.client import Client
from st2client.models import KeyValuePair
from st2common.services.access import create_token
from st2common.util.api import get_full_public_api_url
from st2common.util.date import get_datetime_utc_now
from st2common.constants.keyvalue import DATASTORE_K... |
from collections import defaultdict
import sys
from typing import Any as TypeAny
from typing import Callable
from typing import Dict
from typing import KeysView
from typing import List as TypeList
from typing import Set
from cachetools import cached
from cachetools.keys import hashkey
from ...ast import add_classes
fro... |
import contextlib
import copy
import os
import mock
from oslo.config import cfg
from testtools import matchers
import webob.exc
import neutron
from neutron.api import api_common
from neutron.api.extensions import PluginAwareExtensionManager
from neutron.api.v2 import attributes
from neutron.api.v2.attributes import ATT... |
from django.db import models
class ProductionDatasetsExec(models.Model):
name = models.CharField(max_length=200, db_column='NAME', primary_key=True)
taskid = models.DecimalField(decimal_places=0, max_digits=10, db_column='TASK_ID', null=False, default=0)
status = models.CharField(max_length=12, db_column='S... |
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
PORT = 6667
def protest (response, message):
response.send_response(200)
response.send_header('Content-type','application/json')
response.end_headers()
response.wfile.write(message)
class handler(BaseHTTPRequestHandler):
def do_GET(self):
... |
"""TFX penguin template pipeline definition.
This file defines TFX pipeline and various components in the pipeline.
"""
from typing import List, Optional
import tensorflow_model_analysis as tfma
from tfx import v1 as tfx
from tfx.experimental.templates.penguin.models import features
from ml_metadata.proto import metada... |
from __future__ import annotations
import os
import shutil
import time
import gc
import threading
from typing import Optional
from utils.utilfuncs import safeprint
def DummyAsyncFileWrite(fn, writestr, access='a'):
safeprint('Called HB file write before init {} {} {}'.format(fn, writestr, access))
AsyncFileWrite = Du... |
__author__ = 'kairong'
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import ConfigParser
import MySQLdb
import requests
import re
from socket import socket, SOCK_DGRAM, AF_INET
from multiprocessing import Process
def get_localIP():
'''获取本地ip'''
s = socket(AF_INET, SOCK_DGRAM)
s.connect(('google.com'... |
"""Service object."""
from oslo_versionedobjects import base
from oslo_versionedobjects import fields
from knob.db.sqlalchemy import api as db_api
from knob.objects import base as knob_base
class Service(
knob_base.KnobObject,
base.VersionedObjectDictCompat,
base.ComparableVersionedObject,
):
... |
from __future__ import division, print_function, absolute_import, unicode_literals
import os
import time
import threading
import tempfile
from mog_commons.command import *
from mog_commons import unittest
class TestCommand(unittest.TestCase):
def test_execute_command(self):
self.assertEqual(execute_command(... |
import base64
import itertools
import json
import logging
import os
import re
import time
from .buckets import get_bucket_client
from .params import get_param_client
from .secrets import get_secret_client
logger = logging.getLogger("zentral.conf.config")
class Proxy:
pass
class EnvProxy(Proxy):
def __init__(sel... |
from kfp.deprecated.dsl import artifact_utils
from typing import Any, List
class ComplexMetricsBase(object):
def get_schema(self):
"""Returns the set YAML schema for the metric class.
Returns:
YAML schema of the metrics type.
"""
return self._schema
def get_metrics(self... |
from django.conf import settings
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.contrib.auth import authenticate, login, logout
from django.core.context_processors import csrf
from skilltreeapp.forms import LoginForm
from django.shortcuts import render_to_response... |
"""
MCNPX Model for Cylindrical RPM8
"""
import sys
sys.path.append('../MCNPTools/')
sys.path.append('../')
from MCNPMaterial import Materials
import subprocess
import math
import mctal
import numpy as np
import itertools
import os
class CylinderRPM(object):
# Material Dictionaries
cellForStr = '{:5d} {:d} -{:4... |
import logging
import os
import re
import shutil
import socket
import tarfile
import tempfile
import time
from contextlib import closing
from distutils import spawn
from os.path import expanduser
from subprocess import Popen
import psycopg2
import requests
from psycopg2._psycopg import OperationalError
from psycopg2.ex... |
import mock
from oslo_policy import policy as oslo_policy
import webob
from nova.api.openstack.compute import keypairs as keypairs_v21
from nova.api.openstack import wsgi as os_wsgi
from nova.compute import api as compute_api
from nova import context as nova_context
from nova import exception
from nova import objects
f... |
from __future__ import unicode_literals
import datetime
from boto.ec2.elb.attributes import (
LbAttributes,
ConnectionSettingAttribute,
ConnectionDrainingAttribute,
AccessLogAttribute,
CrossZoneLoadBalancingAttribute,
)
from boto.ec2.elb.policies import (
Policies,
OtherPolicy,
)
from moto.c... |
"""Contains functions for constructing binary or multiclass rate expressions.
There are a number of rates (e.g. error_rate()) that can be defined for either
binary classification or multiclass contexts. The former rates are implemented
in binary_rates.py, and the latter in multiclass_rates.py. In this file, the
given f... |
"""Model definition for the master data set.
The entities of the master data set consist of 'edges' and 'properties' and conform to the
fact based model. <Reference>
Every entity has a unique data_unit_index. It is horizontally partitioned wrt. the
partition key and a granularity.
An edge or property mus... |
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import functools
import inspect
import re
from six.moves.urllib import parse as urlparse
import keystoneauth1.identity.v2 as v2
import keystoneauth1.identity.v3 as v3
import keystoneauth1.session as kssession
fr... |
import json
import os
import re
import datetime
class Advisories(object):
today = datetime.datetime.now().strftime("%Y-%m-%d")
def __init__(self, initial_advisories_path=None, format="txt"):
self.advisories = []
self.added_packages = {}
if initial_advisories_path is not None:
... |
import sqlalchemy
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import mapper, sessionmaker
import subprocess
class PygrationState(object):
'''Python object representing the state table'''
def __init__(self, migration=None, step_id=None, step_name=None):
self.migration = migration
... |
from collections import defaultdict
import subprocess
import os
import bisect
import re
from .common import log_fmt
class GitProcess():
GIT_BIN = None
def __init__(self, repoDir, args, text=None):
startupinfo = None
if os.name == "nt":
startupinfo = subprocess.STARTUPINFO()
... |
"""Interact with Stackdriver Logging via JSON-over-HTTP."""
import functools
from google.cloud import _http
from google.cloud.iterator import HTTPIterator
from google.cloud.logging import __version__
from google.cloud.logging._helpers import entry_from_resource
from google.cloud.logging.sink import Sink
from google.clo... |
class AllPermutations(object):
def __init__(self, arr):
self.arr = arr
def all_permutations(self):
results = []
used = []
self._all_permutations(self.arr, used, results)
return results
def _all_permutations(self, to_use, used, results):
if len(to_use) == 0:
... |
import re
from codecs import open
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def get_version():
version = ''
with open('grimreaper.py', 'r') as fd:
version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
fd.read(), re... |
"""
This component provides HA sensor support for Ring Door Bell/Chimes.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.ring/
"""
from datetime import timedelta
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLA... |
import sys
q_to_time = {}
i = 0
for line in open(sys.argv[1]):
try:
line = line.strip()
cols = line.split('\t')
q_to_time[cols[0]] = [(int(cols[2].split(' ')[0]), i)]
i += 1
except ValueError:
continue
i = 0
for line in open(sys.argv[2]):
try:
line = line.stri... |
from twext.enterprise.dal.syntax import Update
from twisted.internet.defer import inlineCallbacks
from txdav.base.propertystore.base import PropertyName
from txdav.common.datastore.sql_tables import _ABO_KIND_GROUP, schema
from txdav.common.datastore.upgrade.sql.upgrades.util import updateAddressBookDataVersion, \
... |
"""
This module has the class for controlling Mini-Circuits RCDAT series
attenuators over Telnet.
See http://www.minicircuits.com/softwaredownload/Prog_Manual-6-Programmable_Attenuator.pdf
"""
from mobly.controllers import attenuator
from mobly.controllers.attenuator_lib import telnet_client
class AttenuatorDevice(obje... |
import core
logger = core.log.getLogger("monitoring-utils")
class MonitoringUtils(object):
def __init__(self):
pass
@staticmethod
def check_existing_tag_in_topology(root, node, node_type, node_urns,
domain=None):
tag_exists = False
try:
... |
'''
Custom generic form fields for use with Django forms.
----
'''
import re
from django.core.validators import RegexValidator
from django.forms import CharField, ChoiceField
from django.forms.widgets import Select, TextInput, Widget
from django.utils.safestring import mark_safe
W3C_DATE_RE = re.compile(r'^(?P<year>\d{... |
import httplib
import logging
from error import HapiError
class NullHandler(logging.Handler):
def emit(self, record):
pass
def get_log(name):
logger = logging.getLogger(name)
logger.addHandler(NullHandler())
return logger |
import serial
from sys import platform as platform
import serial.tools.list_ports
import serial.threaded
from pymouse import PyMouse
from Voice.GoogleTTS import speak
import threading
import math
import copy
import time
import json
data_repository_right = {
"id" : [],
"name" : [],
"shortcuts" : [],
"tim... |
from unittest import mock
import oslo_messaging
import six
import testtools
from sahara import conductor as cond
from sahara import context
from sahara import exceptions as exc
from sahara.plugins import base as pl_base
from sahara.plugins import provisioning as pr_base
from sahara.service import api as service_api
fro... |
import re
import datetime
from collections import OrderedDict
TimePattern = re.compile("^[0-9]{4}\-[0-9]{2}\-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{3}Z$")
TimeFormat = "%Y-%m-%dT%H:%M:%S.%fZ"
TimePatternSimple = re.compile("^[0-9]{4}\-[0-9]{2}\-[0-9]{2} [0-9]{2}:[0-9]{2}$")
TimeFormatSimple = "%Y-%m-%d %H:%M"
def c... |
"""replace.py
Tool for replacing variable names in Damon.
Copyright (c) 2009 - 2011, Mark H. Moulton for Pythias Consulting, LLC.
Purpose: This tool was developed to replace CamelCase argument
variables with all lower case equivalents across all Damon modules.
It is being retained because it is readily adaptable to ot... |
"""
@author: mango
@contact: w4n9@sina.com
@create: 16/7/4
hail hydra!
"""
__author__ = "mango"
__version__ = "0.1"
from kazoo.client import KazooClient
import logging
logging.basicConfig()
class ZookeeperClient(object):
def __init__(self, zk_host):
self.zk_hosts = zk_host
self.zk = KazooClient(host... |
"""A simple multi-agent env with two agents playing rock paper scissors.
This demonstrates running the following policies in competition:
(1) heuristic policy of repeating the same move
(2) heuristic policy of beating the last opponent move
(3) LSTM/feedforward PG policies
(4) LSTM policy with custom en... |
from os.path import dirname
import numpy as np
from ..os import open_file, exists_isdir, makedirs
from ..log import get_logger
logger = get_logger()
def read_or_write(data_f, fallback=None):
"""Loads the data file if it exists. Otherwise, if fallback is provided,
call fallback and save its return to disk.
A... |
from core_tests_base import CoreTestsBase, FakeTessagon, FakeTileSubClass
class TestTile(CoreTestsBase):
# Note: these tests are highly dependent on the behavior of
# FakeTessagon and FakeAdaptor
def test_add_vert(self):
tessagon = FakeTessagon()
tile = FakeTileSubClass(tessagon, u_range=[... |
import numpy
import os
class TicTacToePlayer:
def __init__(self, playerType, playerName, ttt_game_settings):
if playerType not in ['AI', 'Terminal']:
raise(ValueError())
self.type=playerType
self.name=playerName
self.board_size = ttt_game_settings['board_size']
self.nr_of_positions = ttt_game_settings['bo... |
import os
import numpy as np
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
import shap
import mlflow
X, y = load_iris(return_X_y=True, as_frame=True)
model = RandomForestClassifier()
model.fit(X, y)
with mlflow.start_run() as run:
mlflow.shap.log_explanation(model.predic... |
_lang = {
'_MODULE_NOT_EXIST_':'无法加载模块',
'_ERROR_ACTION_':'非法操作',
'_LANGUAGE_NOT_LOAD_':'无法加载语言包',
'_TEMPLATE_NOT_EXIST_':'模板不存在',
'_MODULE_':'模块',
'_ACTION_':'操作',
'_ACTION_NOT_EXIST_':'控制器不存在或者没有定义',
'_MODEL_NOT_EXIST_':'模型不存在或者没有定义',
'_VALID_ACCESS_':'没有权限',
'_XML_TAG_ERROR_':... |
"""Basic Zephyr manager."""
from empower.core.app import EmpowerApp
from empower.core.app import DEFAULT_PERIOD
from empower.main import RUNTIME
from empower.datatypes.etheraddress import EtherAddress
from empower.core.resourcepool import ResourcePool
from empower.lvapp.lvappconnection import LVAPPConnection
import tim... |
class StoreChangeLogger:
def __init__(self, store_name, context) -> None:
self.topic = f'{context.application_id}-{store_name}-changelog'
self.context = context
self.partition = context.task_id.partition
self.record_collector = context.state_record_collector
def log_change(self, ... |
"""Drift utils test."""
from absl.testing import absltest
from absl.testing import parameterized
from dd_two_player_games import drift_utils
from dd_two_player_games import gan
LEARNING_RATE_TUPLES = [
(0.01, 0.01),
(0.01, 0.05),
(0.05, 0.01),
(0.0001, 0.5)]
class DriftUtilsTest(parameterized.TestCase):... |
"""Deferred tasks for bootstrapping the GnG app."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import datetime
import functools
import inspect
import logging
import os
import sys
from distutils import version
from google.appengine.ext import deferred
fro... |
from __future__ import unicode_literals
import c3nav.mapdata.fields
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('mapdata', '0047_remove_mapupdate_changed_geometries'),
]
operations = [
migrations.CreateMod... |
from test.lib.testing import eq_
from sqlalchemy.orm import mapper, relationship, create_session, \
clear_mappers, sessionmaker, class_mapper
from sqlalchemy.orm.mapper import _mapper_registry
from sqlalchemy.orm.session import _sessions
import operator
from test.lib import testing, engines
from sqlalchemy import M... |
from tempest import test # noqa
from tempest_lib.common.utils import data_utils # noqa
from tempest_lib import exceptions as lib_exc # noqa
from manila_tempest_tests import clients_share as clients
from manila_tempest_tests.tests.api import base
class ShareTypesAdminNegativeTest(base.BaseSharesAdminTest):
def _c... |
import cirq
import cirq_google
def test_equality():
assert cirq_google.PhysicalZTag() == cirq_google.PhysicalZTag()
assert hash(cirq_google.PhysicalZTag()) == hash(cirq_google.PhysicalZTag())
def test_syc_str_repr():
assert str(cirq_google.PhysicalZTag()) == 'PhysicalZTag()'
assert repr(cirq_google.Phys... |
import os
import string
import textwrap
import six
from six.moves.configparser import ConfigParser
from swift.common.utils import (
config_true_value, SWIFT_CONF_FILE, whataremyips, list_from_csv)
from swift.common.ring import Ring, RingData
from swift.common.utils import quorum_size
from swift.common.exceptions im... |
from oslo_utils import excutils
import paramiko
from cinder import exception
from cinder.i18n import _, _LE
from cinder.openstack.common import log as logging
from cinder import utils
from cinder.zonemanager.drivers.brocade import brcd_fabric_opts as fabric_opts
import cinder.zonemanager.drivers.brocade.fc_zone_constan... |
"""Handle all shell commands/arguments/options."""
import importlib
import os
import pkgutil
import sys
import click
context_settings = dict(auto_envvar_prefix='MonitorStack')
class Context(object):
"""Set up a context object that we can pass."""
def __init__(self):
"""Initialize class."""
self.... |
from lxml import etree
from nxpy.interface import Interface
from nxpy.vlan import Vlan
from nxpy.flow import Flow
from util import tag_pattern
class Device(object):
# Singleton
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(
... |
"""SQLAlchemy models for heat data."""
import uuid
from oslo_db.sqlalchemy import models
from oslo_utils import timeutils
import six
import sqlalchemy
from sqlalchemy.ext import declarative
from sqlalchemy.orm import backref
from sqlalchemy.orm import relationship
from sqlalchemy.orm import session as orm_session
from ... |
"""
Copyright 2017-present Airbnb, Inc.
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, softwa... |
from PIL import Image#需要pillow库
import glob, os
in_dir ='background'#源图片目录
out_dir = in_dir+'_out'#转换后图片目录
if not os.path.exists(out_dir): os.mkdir(out_dir)
def main():
for files in glob.glob(in_dir+'/*'):
filepath,filename = os.path.split(files)
im = Image.open(files)
w,h = im.size
... |
"""
Created on Mon Apr 27 09:30:47 2015
@author: martin
"""
from Bio.Seq import Seq
from Bio.Alphabet import IUPAC
from Bio.SubsMat.MatrixInfo import blosum62
def score_match(a,b, matrix):
if b == '*' :
return -500000000000000000000000000
elif a == '-' :
return 0
elif (a,b) not in matrix:
... |
from google.cloud import aiplatform_v1
def sample_create_context():
# Create a client
client = aiplatform_v1.MetadataServiceClient()
# Initialize request argument(s)
request = aiplatform_v1.CreateContextRequest(
parent="parent_value",
)
# Make the request
response = client.create_con... |
import sys
from CTFd import create_app
app = create_app()
app.run(debug=True, host="0.0.0.0", port=int(sys.argv[1])) |
from optparse import make_option
from django.core.management.base import BaseCommand
from messytables import XLSTableSet, headers_guess, headers_processor, offset_processor
from data.models import Source, Course, MerlotCategory
class Command(BaseCommand):
help = "Utilities to merge our database with MERLOT"
arg... |
ncOFF = 0
ncLEFT = -1
ncRIGHT = +1
ncCW = -1
ncCCW = +1
ncMIST = 1
ncFLOOD = 2
class Creator:
def __init__(self):
pass
############################################################################
## Internals
def file_open(self, name):
self.file = open(name, 'w')
self.filename =... |
"""
Given an array of integers, every element appears twice except for one. Find
that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it
without using extra memory?
"""
__author__ = 'yelongyu1024@gmail.com'
class Solution(object):
def __init__(self, nums):
self.... |
import subprocess, os, sys
from reverseZone_naming import reverseZone_name
from netaddr import *
zone_files_path="/etc/bind/zones"
def remove_reverse_record():
host_name_to_be_removed= sys.argv[1]
reverse_zone_file_name,reverse_zone_name=reverseZone_name()
os.chdir(zone_files_path)
readFiles = open(reverse_zone_fil... |
__all__ = ["gauth", "gcalendar", "lectio", "lesson", "run"] |
"""beanstalkc - A beanstalkd Client Library for Python"""
import logging
import socket
import sys
__license__ = '''
Copyright (C) 2008-2016 Andreas Bolka
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 ... |
""".. Ignore pydocstyle D400.
===============
Signal Handlers
===============
"""
from asgiref.sync import async_to_sync
from django.conf import settings
from django.db import transaction
from django.db.models.signals import post_delete, post_save
from django.dispatch import receiver
from resolwe.flow.managers import m... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.