code stringlengths 1 199k |
|---|
import sys
import os
for path in [os.getcwd(),"SchemaExamples"]:
sys.path.insert( 1, path ) #Pickup libs from shipped lib directory
import logging
logging.basicConfig(level=logging.INFO) # dev_appserver.py --log_level debug .
log = logging.getLogger(__name__)
from schemaexamples import SchemaExamples, Example
SchemaE... |
"""Handling e-mail messages."""
import datetime
import email.header
import email.message
import logging
import typing as t
import dateutil.parser
from .connection import Connection
_LOG = logging.getLogger(__name__)
def recode_header(raw_data: t.Union[bytes, str]) -> str:
"""Normalize the header value."""
decod... |
import proto # type: ignore
from google.ads.googleads.v9.enums.types import (
response_content_type as gage_response_content_type,
)
from google.ads.googleads.v9.resources.types import (
campaign_budget as gagr_campaign_budget,
)
from google.protobuf import field_mask_pb2 # type: ignore
from google.rpc import... |
import sys
data = sys.argv[1]
java_file = open("vsense-ide/VSenseSDK/src/vsense_app/VSenseApp.java", "w")
java_file.write(data)
'''def isfloat(x):
try:
a = float(x)
except ValueError:
return False
else:
return True
def isint(x):
try:
a = float(x)
b = int(a)
except ValueError:
return False
else:
retu... |
from application.extensions import db
from configs.enum import TAG_TYPES
__all__ = ['Tag']
class Tag(db.Document):
meta = {
'db_alias': 'inventory_db',
'indexes': ['en']
}
en = db.StringField(required=True, unique=True)
cn = db.StringField()
kind = db.StringField(required=True, choic... |
from siconos.kernel import \
Model, MoreauJeanOSI, TimeDiscretisation, \
FrictionContact, NewtonImpactFrictionNSL
import siconos.kernel as sk
from siconos.mechanics.contact_detection.bullet import \
btConvexHullShape, btVector3, btCollisionObject, \
btBoxShape, btMatrix3x3, \
BulletSpaceFilter, \... |
"""
Views for managing Nova floating IPs.
"""
import logging
from django import http
from django.contrib import messages
from django.utils.translation import ugettext as _
from horizon import api
from horizon import forms
from .forms import FloatingIpAssociate, FloatingIpAllocate
LOG = logging.getLogger(__name__)
class... |
"""template URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-ba... |
"""Test for MetricsPlotsAndValidationsEvaluator."""
import os
from absl.testing import parameterized
import apache_beam as beam
from apache_beam.testing import util
import numpy as np
import tensorflow as tf
from tensorflow_model_analysis import constants
from tensorflow_model_analysis.addons.fairness.metrics import li... |
from setuptools import setup, find_packages
setup(
name="sentinel",
version="3.0.2",
author="Joe Stahl (@happy-jo)",
url="https://github.com/PUNCH-Cyber/stoq-plugins-public",
license="Apache License 2.0",
description="Send reults to Azure Sentinel (Log Analytics Workspace) using the Azure Log An... |
def setup_ntp_test(request, bigip):
def teardown():
n.servers = servers
n.update()
request.addfinalizer(teardown)
n = bigip.sys.ntp.load()
servers = n.servers
return n, servers
class iTestGlobal_Setting(object):
def itest_RUL(self, request, bigip):
# Load
ip = '19... |
from __future__ import absolute_import, division, print_function, unicode_literals
from logging import getLogger
from os.path import realpath
import re
import struct
from ..base.constants import PREFIX_PLACEHOLDER
from ..common.compat import on_win
from ..exceptions import CondaIOError, BinaryPrefixReplacementError
fro... |
import commands
import logging
import json
import time
from core.alive import alive
from core.voiceapplication import VoiceApplication
from core.voicesynthetizer import VoiceSynthetizer
from pprint import pprint
class VoiceApp(object):
def __init__(self, voicesynthetizer):
self.modulename = 'Voice Applicati... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import datetime
import logging
import os
import shutil
import unittest
import six
import socket
from tempfile import mkdtemp
from airflow import AirflowException, settings... |
import shutil
import os.path
import pytest
import hashlib
import operator
from unittest import TestCase
from pyspark.sql.functions import col, concat, max, min, array, udf, lit
from pyspark.sql.types import StructType, StructField, StringType, IntegerType, ArrayType, \
DoubleType
from bigdl.orca import OrcaContext
... |
''' Uses the SymCC-AFL hybrid from SymCC. '''
import os
import time
import shutil
import threading
import subprocess
from fuzzers.afl import fuzzer as afl_fuzzer
from fuzzers.aflplusplus import fuzzer as aflplusplus_fuzzer
def get_symcc_build_dir(target_directory):
"""Return path to uninstrumented target directory.... |
import os
import random
from collections import defaultdict
import xml.etree.ElementTree
def parse_annotations(dir):
all_files = [f for f in os.listdir(dir) if os.path.isfile(os.path.join(dir, f)) and f.lower().endswith('.xml')]
filenames = defaultdict(list)
for f in all_files:
target_file = os.path... |
"""ggrc.views
Handle non-RESTful views, e.g. routes which return HTML rather than JSON
"""
import collections
import json
from flask import flash
from flask import g
from flask import render_template
from flask import url_for
from werkzeug.exceptions import Forbidden
from ggrc import models
from ggrc import settings
fr... |
import datetime
import cotyledon
import threading
from racoon.storage import connection
from oslo_config import cfg
from oslo_log import log
from oslo_utils import timeutils
CONF = cfg.CONF
LOG = log.getLogger(__name__)
class SearcherService(cotyledon.Service):
def __init__(self, worker_id):
super(SearcherS... |
import unittest
import numpy as np
import SimpleITK as sitk
import miapy.data.conversion as img
class TestImageProperties(unittest.TestCase):
def test_is_two_dimensional(self):
x = 10
y = 10
image = sitk.Image([x, y], sitk.sitkUInt8)
dut = img.ImageProperties(image)
self.asse... |
"""
Assorted utilities for working with neural networks in AllenNLP.
"""
import copy
from collections import defaultdict, OrderedDict
from itertools import chain
import json
import logging
from os import PathLike
import re
from typing import Any, Dict, List, Optional, Sequence, Tuple, TypeVar, Union, NamedTuple
import ... |
__author__ = 'emalishenko'
from model.group import Group
from random import randrange
def test_modify_group_name(app):
group = Group(name="To be modified")
if app.group.count() == 0:
app.group.create(Group(name="New group name"))
old_groups = app.group.get_group_list()
index = randrange(len(old_... |
"""
"""
import pygimli as pg
import pybert as pb
class DCMultiElectrodeModellingC(pb.DCMultiElectrodeModelling):
def __init__(self, mesh, data, verbose):
super().__init__(mesh, data, verbose)
self.setComplex(True)
self._J = pg.matrix.BlockMatrix()
self.setJacobian(self._J)
se... |
from abc import ABCMeta, abstractmethod
import unittest
from ray.rllib.utils.from_config import from_config
from ray.rllib.utils.test_utils import check
from ray.rllib.utils.framework import try_import_tf, try_import_torch
tf = try_import_tf()
tf.enable_eager_execution()
torch, _ = try_import_torch()
class TestFrameWor... |
import khmer
from khmer import LabelHash
from screed.fasta import fasta_iter
import screed
import khmer_tst_utils as utils
from nose.plugins.attrib import attr
def teardown():
utils.cleanup()
def test_n_labels():
lh = LabelHash(20, 1e7, 4)
filename = utils.get_test_data('test-labels.fa')
lh.consume_fast... |
from google import pubsub_v1
async def sample_pull():
# Create a client
client = pubsub_v1.SubscriberAsyncClient()
# Initialize request argument(s)
request = pubsub_v1.PullRequest(
subscription="subscription_value",
max_messages=1277,
)
# Make the request
response = await cli... |
from ncclient import manager
import ncclient
import xml.etree.ElementTree as ET
host = "192.168.1.1"
username="root"
password="root"
with manager.connect_ssh(host=host, port=830, username=username, password=password, hostkey_verify=False ) as m:
print m.get_config(source='startup').data_xml |
"""
Server-side Keystone notification payload processing logic.
"""
from barbican.common import utils
from barbican import i18n as u
from barbican.model import repositories as rep
from barbican.tasks import resources
LOG = utils.getLogger(__name__)
class KeystoneEventConsumer(resources.BaseTask):
"""Event consumer ... |
import re
import nltk
regex_url = re.compile(
r'^(?:http|ftp)s?://' # http:// or https://
# domain...
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+'
r'(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # opt... |
"""
Created on Thu Nov 23 11:23:03 2017
@author: tih
"""
import numpy as np
import os
import scipy.interpolate
import gdal
from openpyxl import load_workbook
import osr
from datetime import datetime, timedelta
import pandas as pd
import shutil
import glob
from netCDF4 import Dataset
import warnings
import SEBAL
def mai... |
import cPickle
import errno
import itertools
import os
import sys
import tempfile
import traceback
from conary import files, trove, callbacks
from conary.deps import deps
from conary.lib import util, openpgpfile, sha1helper, openpgpkey
from conary.repository import changeset, errors, filecontents
from conary.repository... |
def isSentenceCorrect(sentence):
pattern = '^[A-Z][^\?\!\.]*[!.?]{1}$'
return re.match(pattern, sentence) is not None |
import abc
import six
import yaml
from nailgun import consts
from nailgun.errors import errors
from nailgun.expression import Expression
from nailgun.logger import logger
from nailgun import objects
from nailgun.orchestrator import deployment_serializers
from nailgun.orchestrator import tasks_templates as templates
fro... |
import click
import sys
import time
from solar.core import actions
from solar.core import resource
from solar.core import signals
from solar.core import validation
from solar.core.resource import virtual_resource as vr
from solar import errors
from solar import events as evapi
from solar.interfaces.db import get_db
PRO... |
from __future__ import annotations
from typing import *
import asyncio
import contextlib
import datetime
import logging
import os
import os.path
import pathlib
import resource
import signal
import socket
import sys
import tempfile
import uuid
import uvloop
import click
import setproctitle
from . import logsetup
logsetu... |
_HTML_TYPES = {
'a': 'HTMLAnchorElement',
'abbr': 'HTMLUnknownElement',
'acronym': 'HTMLUnknownElement',
'address': 'HTMLUnknownElement',
'applet': 'HTMLUnknownElement',
'area': 'HTMLAreaElement',
'article': 'HTMLUnknownElement',
'aside': 'HTMLUnknownElement',
'audio': 'HTMLAudioElem... |
import sh
from claw import configuration
from claw import tests
class StatusTest(tests.BaseTestWithInit):
def test_basic(self):
test_version = 'TEST_VERSION'
port = self.server({'version': lambda: {'version': test_version}})
self.claw.generate(tests.STUB_CONFIGURATION)
conf = configu... |
rightPort = "COM9"
if ('virtual' in globals() and virtual):
virtualArduinoRight = Runtime.start("virtualArduinoRight", "VirtualArduino")
virtualArduinoRight.connect(rightPort)
Voice="cmu-bdl-hsmm" #Male US voice
mouth = Runtime.start("i01.mouth", "MarySpeech")
mouth.setVoice(Voice)
i01 = Runtime.create("i01", "... |
from distutils.core import setup
setup(name='ctctwspylib',
version='0.1.1a1',
description='A clone of the original lib from SourceForge (https://sourceforge.net/projects/ctctwspylib/)',
author='Serdar Tumgoren',
author_email='zstumgoren@gmail.com',
url='https://github.com/zstumgoren/ctctws... |
"""
This Python module contains tests for the prepifg.py PyRate module.
"""
import shutil
import os
from os.path import exists, join
import sys
import subprocess
import tempfile
from math import floor
from itertools import product
from pathlib import Path
import pytest
import numpy as np
from numpy import isnan, nanmax... |
import csv
import tushare as ts
import datetime
import os
def getStockHistoryData(stockId,timeToMarket):
if not re.match('^\d{8}$',timeToMarket) :
timeToMarket = '20000101'
endDate = datetime.datetime.strptime(timeToMarket,'%Y%m%d')
toDate = datetime.datetime.now()
fromDate = toDate - datetime.t... |
import unittest
from mock import patch
from mock import MagicMock as Mock
from pyrax.clouddatabases import CloudDatabaseBackupManager
from pyrax.clouddatabases import CloudDatabaseDatabase
from pyrax.clouddatabases import CloudDatabaseFlavor
from pyrax.clouddatabases import CloudDatabaseInstance
from pyrax.clouddatabas... |
def enum(*sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named)
return type('Enum', (), enums)
def InitDebugTagTypes():
return enum( 'GroupToParagraph', 'MergeSubtitles', 'PrintSubtitles', 'File' )
def InitDebugTags():
DebugTagType = InitDebugTagTypes()
debugTags = []
debu... |
""" Builtin vars node.
Not used much, esp. not in the form with arguments. Maybe used in some meta programming,
and hopefully can be predicted, because at run time, it is hard to support.
"""
from .ExpressionBases import ExpressionChildHavingBase
class ExpressionBuiltinVars(ExpressionChildHavingBase):
kind = "EXPRE... |
import feedparser
import socket
from urllib.request import Request, urlopen
class Bot:
def __init__(self, host, port, nick, ident, realname, testchannel):
self.host = host
self.port = port
self.nick = nick
self.ident = ident
self.realname = realname
self.testchannel =... |
__author__ = "Markus Gumbel"
__copyright__ = "The authors"
__license__ = "Apache 2"
__email__ = "m.gumbel@hs-mannheim.de"
__status__ = "Test"
from math import pi as PI
from Core.CellType import CellType
from Core.ExecConfig import ExecConfig
from Core.ModelConfig import ModelConfig
from Steppable.InitializerSteppable i... |
from jinja2 import Environment, FileSystemLoader
import os
import pathlib
from typing import List
root_directory = pathlib.Path(
os.path.realpath(os.path.dirname(os.path.realpath(__file__)))
).parent.parent
print(root_directory)
jinja_env = Environment(
loader=FileSystemLoader(str(root_directory / "templates" /... |
from keystoneclient.v2_0 import client as keystoneclient
from heatclient import client as heatclient
from Deployer import Deployer
import uuid
import logging
HEAT_VERSION = '1'
class HeatclientProvider():
@staticmethod
def get_heatclient(extras):
# first, a connection to keystone has to be established i... |
N = int(input())
for i in range(0,N):
nums = input().split(" ")
X = int(nums[0])
Y = int(nums[1])
if(Y == 0):
print("divisao impossivel")
else:
print("{0:.1f}".format(X/Y)) |
"""Classes and global objects related to resolving U{XML
Namespaces<http://www.w3.org/TR/2006/REC-xml-names-20060816/index.html>}."""
import pyxb_114
import os
import fnmatch
import pyxb_114.utils.utility
import archive
import utility
class _Resolvable_mixin (pyxb_114.cscRoot):
"""Mix-in indicating that this object... |
"""
django-critic: urls
"""
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('critic.views',
url(r'^add/$',
'add_rating',
name='critic_add_rating'),
url(r'^render/(?P<content_type_id>\d+)/(?P<object_id>\d+)/$',
'render_rating',
name='critic_rating_render... |
import logging
from distutils.version import LooseVersion
from moksha.common.lib.converters import asbool
from moksha.hub.reactor import reactor
try:
# stomper is not ready for py3
try:
# Try first to use modern stomp-1.1
import stomper.stomp_11 as stomper
except ImportError:
# Faili... |
ATTR_NOT_SPECIFIED = object()
SHARED = 'shared'
import logging
import netaddr
import re
from quantum.common import exceptions as q_exc
LOG = logging.getLogger(__name__)
def is_attr_set(attribute):
return attribute not in (None, ATTR_NOT_SPECIFIED)
def _validate_boolean(data, valid_values=None):
if data in [True... |
"""Gym-specific (non-Atari) utilities.
Some network specifications specific to certain Gym environments are provided
here.
Includes a wrapper class around Gym environments. This class makes general Gym
environments conformant with the API Dopamine is expecting.
"""
from __future__ import absolute_import
from __future__... |
"""
This tool checks GitHub for the latest version of Modis and can produce the name
of the current official version and the difference between that version and the
version currently being used.
"""
import logging
import requests
from modis.tools import config
logger = logging.getLogger(__name__)
def infostr():
"""... |
import os
import subprocess
os.system("kubectl delete -f cloudone-controller-glusterfs.json")
os.system("kubectl delete -f cloudone-service.json")
p = subprocess.Popen(['kubectl', 'get', 'pod'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, err = p.communicate()
output_line_list = output.split("\n")
for outpu... |
"""Tests for tensorflow.python.framework.importer."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
from google.protobuf import text_format
from tensorflow.core.framework import op_def_pb2
from tensorflow.python.fr... |
import unittest
from pyramid import testing
class ViewTests(unittest.TestCase):
def setUp(self):
self.config = testing.setUp()
def tearDown(self):
testing.tearDown()
def test_my_view(self):
from .views import my_view
request = testing.DummyRequest()
info = my_view(req... |
from __future__ import unicode_literals, division, absolute_import, print_function
import functools
import itertools
import operator
import sys
import os
import codecs
import types
from . import unipath as path
from .const import PY2, PY3, PY35, PYPY, OS_WIN, ASCII_CHARS, URL_SAFE, IRI_UNSAFE
def _add_doc(func, doc):
... |
import logging
import os
import sys
def wire():
here = os.path.dirname(os.path.abspath(__file__))
parent = os.path.dirname(here)
lib = os.path.join(parent, "lib")
sys.path.append(lib)
config = os.path.join(parent, "config")
sys.path.append(config)
wire()
from ss2config import *
import selfserve.tokens
os.ch... |
"""Keepalived configuration datamodel
Revision ID: 1e4c1d83044c
Revises: 5a3ee5472c31
Create Date: 2015-08-06 10:39:54.998797
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy import sql
revision = '1e4c1d83044c'
down_revision = '5a3ee5472c31'
def upgrade():
op.create_table(
u'vrrp_auth_met... |
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('mysql+mysqldb://root:root@localhost/test?charset=utf8', convert_unicode=True)
db_session = scoped_session(sessionmaker(autocommit=False,
... |
from oslo_config import cfg
from stevedore import driver
from cloudkitty import config # noqa
from cloudkitty import service
CONF = cfg.CONF
STORAGES_NAMESPACE = 'cloudkitty.storage.backends'
def init_storage_backend():
CONF.import_opt('backend', 'cloudkitty.storage', 'storage')
backend = driver.DriverManager(... |
"""
Django settings for SegmentationService project.
Generated by 'django-admin startproject' using Django 1.11.2.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
i... |
import tushare as ts
df = ts.get_h_data('600848',start='2016-08-05',end='2016-08-23', autype='hfq')
print("#0", df)
df = ts.get_hist_data('600848',start='2016-08-05',end='2016-08-23')
print("#1", df)
df = ts.get_hist_data('600848',start='2016-08-05',end='2016-08-23', ktype='W')
print("#2", df)
df = ts.get_hist_data('60... |
import sys
def kaprekar(n):
n_digit_count = len(str(n))
m_str = str(n*n)
r_str = m_str[-n_digit_count:]
l_str = m_str[:-n_digit_count]
l = 0 if len(l_str) == 0 else int(l_str)
r = int(r_str)
return l + r == n
p = int(sys.stdin.readline())
q = int(sys.stdin.readline())
exists = False
for i in... |
from pymongo import MongoClient
import datetime
import pymongo
client = MongoClient()
client = MongoClient('mongodb://mongodb_server:27017')
db = client['test']
posts = db.posts
post_data = {
'title': 'Python and MongoDB',
'content': 'PyMongo is fun, you guys',
'author': 'Scott'
}
result = posts.insert_one(... |
import sys
import synapseclient
syn = synapseclient.login(silent=True)
files = syn.restGET('/entity/md5/%s' % sys.argv[1])
for item in files['results']:
print sys.argv[1], item['name'], item['id'], item['versionNumber'] |
"""Tests for asserts module."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.autograph.converters import asserts
from tensorflow.python.autograph.converters import functions
from tensorflow.python.autograph.core import converter_test... |
import mock
import os
import sh
import shutil
import tempfile
from six.moves import configparser
import dlrn.shell
from dlrn.build import build
from dlrn.build import build_rpm_wrapper
from dlrn.config import ConfigOptions
from dlrn import db
from dlrn.tests import base
from dlrn import utils
class FakePkgInfo(object):... |
import mock
import six
import webob
import ddt
from cinder.api.contrib import types_manage
from cinder import context
from cinder import exception
from cinder import test
from cinder.tests.unit.api import fakes
from cinder.tests.unit import fake_constants as fake
from cinder.volume import volume_types
DEFAULT_VOLUME_TY... |
from __future__ import print_function
import time
from RF24 import *
import RPi.GPIO as GPIO
irq_gpio_pin = None
radio = RF24(22, 0);
def try_read_data(channel=0):
if radio.available():
while radio.available():
len = radio.getDynamicPayloadSize()
receive_payload = radio.read(len)
... |
from tensorforce import TensorforceError
from tensorforce.core import tf_function
from tensorforce.core.optimizers import UpdateModifier
class OptimizerWrapper(UpdateModifier):
"""
Optimizer wrapper, which performs additional update modifications, argument order indicates
modifier nesting from outside to in... |
import os
import json
import shutil
import tempfile
from solar.core.handlers import base
from solar.core.handlers.base import SOLAR_TEMP_LOCAL_LOCATION
from solar.core.handlers.base import TempFileHandler
from solar.core.log import log
from solar.core.provider import SVNProvider
ROLES_PATH = '/etc/ansible/roles'
class ... |
from __future__ import unicode_literals
import mock
from moto.packages.httpretty.core import HTTPrettyRequest, fake_gethostname, fake_gethostbyname
def test_parse_querystring():
core = HTTPrettyRequest(headers='test test HTTP/1.1')
qs = 'test test'
response = core.parse_querystring(qs)
assert response =... |
import ldap
from ldap import filter as ldap_filter
from keystone.common.ldap import fakeldap
from keystone.common import logging
from keystone import exception
LOG = logging.getLogger(__name__)
LDAP_VALUES = {'TRUE': True, 'FALSE': False}
CONTROL_TREEDELETE = '1.2.840.113556.1.4.805'
LDAP_SCOPES = {'one': ldap.SCOPE_ON... |
__author__ = 'dominiczippilli'
def foo():
pass |
"""Loop utilities."""
import jax
import jax.numpy as jnp
def _while_loop_scan(cond_fun, body_fun, init_val, max_iter):
"""Scan-based implementation (jit ok, reverse-mode autodiff ok)."""
def _iter(val):
next_val = body_fun(val)
next_cond = cond_fun(next_val)
return next_val, next_cond
def _fun(tup, it... |
from __future__ import unicode_literals
from django.apps import AppConfig
class SensorConfig(AppConfig):
name = 'sensor' |
"""
WSGI config for BRB 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_MODU... |
"""The data range file system implementation."""
from dfvfs.lib import definitions
from dfvfs.lib import errors
from dfvfs.path import data_range_path_spec
from dfvfs.vfs import data_range_file_entry
from dfvfs.vfs import root_only_file_system
class DataRangeFileSystem(root_only_file_system.RootOnlyFileSystem):
"""Cl... |
"""
PyCOMPSs Testbench
========================
"""
import unittest
from modules.testNoReturn import testNoReturn
from modules.testNoReturnClasses import testNoReturnClasses
def main():
suite = unittest.TestLoader().loadTestsFromTestCase(testNoReturn)
suite.addTest(unittest.TestLoader().loadTestsFromTestCase(te... |
import logging
from six import moves
from tempest_lib import exceptions as lib_exc
from testtools import matchers
from tempest.api.messaging import base
from tempest.common.utils import data_utils
from tempest import test
LOG = logging.getLogger(__name__)
class TestQueues(base.BaseMessagingTest):
@test.attr(type='s... |
import pytest, requests, json
from kubernetes.client.rest import ApiException
from suite.resources_utils import (
wait_before_test,
replace_configmap_from_yaml,
get_last_reload_time,
get_test_file_name,
write_to_json,
)
from suite.custom_resources_utils import (
read_custom_resource,
)
from suit... |
from __future__ import unicode_literals
from __future__ import absolute_import
"""
pypuppetdb PuppetDB API library
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
pypuppetdb is a library to work with PuppetDB's REST API. It provides a way
to query PuppetDB and a set of additional methods and objects to make working
with PuppetDB's API... |
from neutron.api import extensions
from neutron.api.v2 import attributes as attr
from neutron.api.v2 import resource_helper
from oslo_log import log as logging
LOG = logging.getLogger(__name__)
def _validate_list_of_port_dicts(values, data):
if not isinstance(values, list):
msg = _("'%s' is not a list") % d... |
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this ... |
import errno
import os
import re
import subprocess
import sys
git_refnames = "$Format:%d$"
git_full = "$Format:%H$"
tag_prefix = ""
parentdir_prefix = "myproject-"
versionfile_source = "cameo/_version.py"
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):
assert isinstance(commands, list)
... |
from operator import attrgetter
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType
from pyangbind.lib.yangtypes import RestrictedClassType
from pyangbind.lib.yangtypes import TypedListType
from pyangbind.lib.yangtypes import YANGBool
from pyangbind.lib.yangtypes import YANGListType
from pyangbind.lib.ya... |
import unittest
from datetime import datetime, timedelta
from rx import Observable
from rx.testing import TestScheduler, ReactiveTest, is_prime, MockDisposable
from rx.disposables import Disposable, SerialDisposable
from rx.subjects import Subject
on_next = ReactiveTest.on_next
on_completed = ReactiveTest.on_completed
... |
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('lexicon', '0089_fix_citation'),
]
operations = [
migrations.RemoveField(
model_name='meaninglist',
name='data',
),
] |
from bambino.appenv import Repository, WebAppDir
from contextlib import contextmanager
from path import path
import os
import shutil
import subprocess
import tempfile
import unittest
class TestAppEnvIdentification(unittest.TestCase):
def setUp(self):
sb = self.sandbox = path(tempfile.mkdtemp())
ae1 ... |
import simuvex
from simuvex.s_type import SimTypeString
class strcpy(simuvex.SimProcedure):
#pylint:disable=arguments-differ
def run(self, dst, src):
self.argument_types = {0: self.ty_ptr(SimTypeString()),
1: self.ty_ptr(SimTypeString())}
self.return_type = self.ty... |
"""
Based on https://djangosnippets.org/snippets/1179/
"""
from re import compile
from django.conf import settings as django_settings
from django.contrib.auth.views import redirect_to_login
from django.urls import reverse
from django_auth_adfs.exceptions import MFARequired
from django_auth_adfs.config import settings
L... |
import sys, os
sys.path.insert(0, '..')
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx']
intersphinx_mapping = {'python': ('http://docs.python.org/3.2', None),
'pymongo': ('http://api.mongodb.org/python/current/', None)}
templates_path = ['_templates']
source_suffix = '.rst'
master_d... |
import tempfile
import subprocess
import numpy as np
from os.path import dirname
class SelfTuningSpectralClustering():
# src_pat ex.) "^.*/X_(\d{3}).csv$"
def __init__(self,n_clusters_max):
self.exe=dirname(__file__)+"/self_tuning_spectral_clustering"
self.n_clusters_max=n_clusters_max
def m... |
"""
Implements parsing of Grako's EBNF idiom for grammars, and grammar model
creation using the .grammars module.
GrakoParserRoot is the bootstrap parser. It uses the facilities of parsing.Parser
as generated parsers do, but it does not conform to the patterns in the generated
code. Why? Because having Grako bootstrap ... |
from AnyQt.QtWidgets import QGroupBox, QHBoxLayout, QVBoxLayout
from Orange.widgets import gui
from Orange.widgets import settings
from Orange.widgets.widget import OWWidget
from orangecontrib.text.corpus import Corpus
class Input:
CORPUS = 'Corpus'
class Output:
CORPUS = 'Corpus'
class OWBaseVectorizer(OWWidge... |
def SimIRStmt_CAS(engine, state, stmt):
# first, get the expression of the add
with state.history.subscribe_actions() as addr_actions:
addr = engine.handle_expression(state, stmt.addr)
# figure out if it's a single or double
double_element = (stmt.oldHi != 0xFFFFFFFF) and (stmt.expdHi is not Non... |
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'dot_app.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.