code stringlengths 1 199k |
|---|
"""
All constants centralised in one file.
"""
import os
import socket
from ipapython.dn import DN
from ipapython.version import VERSION, API_VERSION
try:
FQDN = socket.getfqdn()
except Exception:
try:
FQDN = socket.gethostname()
except Exception:
FQDN = None
NAME_REGEX = r'^[a-z][_a-z0-9]*[... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = """
---
author: Ansible Networking Team
cliconf: iosxr
short_description: Use iosxr cliconf to run command on Cisco IOS XR platform
description:
- This iosxr plugin provides low level abstraction apis for
sendi... |
import glob
import subprocess
FORMAT = "pdf"
def exportPdf(srcFile):
# folder = srcFile
cmd = "jupyter nbconvert --to %s \"%s\"" % (FORMAT, srcFile)
print(cmd)
print(subprocess.Popen(cmd, stdout=subprocess.PIPE).stdout.read())
lstFiles = []
lstFile = [filename for glob.iglob('**/*.ipynb', recursive=Tru... |
import os
from ckan.tests.legacy import TestController
class TestSolrSchemaVersionCheck(TestController):
@classmethod
def setup_class(cls):
cls.root_dir = os.path.dirname(os.path.realpath(__file__))
def _get_current_schema(self):
current_schema = os.path.join(self.root_dir,'..','..','..','co... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
"metadata_version": "1.1",
"status": ["preview"],
"supported_by": "community",
}
DOCUMENTATION = """
---
module: hcloud_volume
short_description: Create and manage block volumes on the Hetzner Cloud.
v... |
"""Manage IPython.parallel clusters in the notebook."""
from tornado import web
from IPython.config.configurable import LoggingConfigurable
from IPython.utils.traitlets import Dict, Instance, Float
from IPython.core.profileapp import list_profiles_in
from IPython.core.profiledir import ProfileDir
from IPython.utils imp... |
import sys
import os
import json
import requests
LAST_LINE_FILE = "lastLine.txt"
SEARCHING_MODE = 0
EXCEPTION_MODE = 1
logFile = None
slackURL = None
lastLine = 0
exceptions = []
def processCommandLine ():
global logFile, slackURL
if len(sys.argv) != 3:
print("Usage: extract_exception.py <logFile> <slac... |
from utils import string_to_boolean
from utils import rank
from utils import get_class
from utils import split_arg_str
from utils import get_cosine_similarity
from utils import get_binomial_ci
from utils import normalize_to_unit_sphere
from utils import sample_unit_sphere |
"""A non-blocking, single-threaded HTTP server.
Typical applications have little direct interaction with the `HTTPServer`
class except to start a server at the beginning of the process
(and even that is often done indirectly via `tornado.web.Application.listen`).
This module also defines the `HTTPRequest` class which i... |
import sys
sys.path.append('../../../src')
import os, abc, time, datetime, math, random
import numpy as np
import tensorflow as tf
import scipy.io.wavfile as wav
from PIL import Image
from python_speech_features import mfcc
from swl.machine_learning.tensorflow.neural_net_trainer import NeuralNetTrainer
from swl.machine... |
import ujson
from socorro.unittest.testbase import TestCase
from nose.tools import eq_, ok_
from mock import Mock, patch
from configman import ConfigurationManager
from configman.dotdict import DotDict
from socorro.processor.processor_2015 import (
Processor2015,
rule_sets_from_string
)
from socorrolib.lib.util... |
"""Create ZUPC.zupc_id
Revision ID: 8cfcc4665458
Revises: 918717b2e507
Create Date: 2021-02-02 10:45:01.412883
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
revision = '8cfcc4665458'
down_revision = '918717b2e507'
branch_labels = None
depends_on = None
def upgrade():
... |
from __future__ import absolute_import
from __future__ import division # Ensures that a/b is always a float.
import warnings
import unittest
import numpy as np
from numpy.testing import assert_equal, assert_almost_equal
from qinfer import UniformDistribution
from qinfer.tests.base_test import (
DerandomizedTestCase... |
"""
Test models, managers, and validators.
"""
import ddt
from completion.test_utils import CompletionWaffleTestMixin
from completion.waffle import ENABLE_COMPLETION_TRACKING_SWITCH
from django.urls import reverse
from edx_toggles.toggles.testutils import override_waffle_switch
from rest_framework.test import APIClient... |
from django.db import models
from reversion.admin import VersionAdmin
from base.models.enums import education_group_language
from osis_common.models.osis_model_admin import OsisModelAdmin
class EducationGroupLanguageAdmin(VersionAdmin, OsisModelAdmin):
list_display = ('type', 'order', 'education_group_year', 'langu... |
from openerp import models, fields, api
class HrPayslip(models.Model):
_inherit = 'hr.payslip'
# ---------- Fields management
invoices = fields.One2many('account.invoice', 'slip_id',
string='Invoices')
expenses = fields.One2many('hr.expense.expense', 'slip_id',
... |
import datetime
import json
import mock
from nose.plugins.attrib import attr
from pytz import UTC
from django.utils.timezone import UTC as django_utc
from django_comment_client.tests.factories import RoleFactory
from django_comment_client.tests.unicode import UnicodeTestMixin
import django_comment_client.utils as utils... |
ies = []
ies.append({ "iei" : "43", "value" : "Full name for network", "type" : "Network name", "reference" : "9.9.3.24", "presence" : "O", "format" : "TLV", "length" : "3-n"})
ies.append({ "iei" : "45", "value" : "Short name for network", "type" : "Network name", "reference" : "9.9.3.24", "presence" : "O", "format" : ... |
from myhdl import *
def bench_AssignSignal():
a = Signal(bool(0))
p = Signal(bool(0))
b = Signal(intbv(0)[8:])
q = Signal(intbv(0)[8:])
p.assign(a)
q.assign(b)
@instance
def stimulus():
a.next = 0
b.next = 0
yield delay(10)
for i in range(len(b)):
... |
from peacock.Input.InputFile import InputFile
from peacock.utils import Testing
from peacock import PeacockException
class Tests(Testing.PeacockTester):
def setUp(self):
super(Tests, self).setUp()
self.tmp_file = "tmp_input.i"
self.basic_input = "[foo]\n[./bar]\ntype = bar\nother = 'bar'[../... |
from __future__ import absolute_import
import myhdl
from myhdl import *
@block
def adapter(o_err, i_err, o_spec, i_spec):
nomatch = Signal(bool(0))
other = Signal(bool(0))
o_err_bits = []
for s in o_spec:
if s == 'other':
o_err_bits.append(other)
elif s == 'nomatch':
... |
from spack import *
class FuseOverlayfs(AutotoolsPackage):
"""An implementation of overlay+shiftfs in FUSE for rootless containers."""
homepage = "https://github.com/containers/fuse-overlayfs"
url = "https://github.com/containers/fuse-overlayfs/archive/v1.1.2.tar.gz"
version('1.1.2', sha256='1c0fa6... |
from .connector import Connector, ConnectorAsync
from .locator import Locator
from .worker import Worker |
from test.support import run_unittest, verbose
from platform import linux_distribution
import unittest
import locale
import sys
import codecs
enUS_locale = None
def get_enUS_locale():
global enUS_locale
if sys.platform == 'darwin':
import os
tlocs = ("en_US.UTF-8", "en_US.ISO8859-1", "en_US")
... |
import re
import cmds as cmds_lib
import validate
class Service(object):
def validateCmds(self, root, path):
cmds = validate.array(root, path, validate.is_any_type({'string', 'object'}), [])
for i, cmd in enumerate(cmds):
cmd_path = path + [i]
if isinstance(cmd, basestring):
... |
import unittest2
from mock import MagicMock, patch
from raxas.scaling_group import ScalingGroup
from raxas.core_plugins.newrelic import NewRelic
from novaclient.v1_1.servers import Server
from newrelic_api import Applications, Servers
class NewRelicTest(unittest2.TestCase):
def __init__(self, *args, **kwargs):
... |
'''
Test for deleting vm image check vm snapshot.
@author: SyZhao
'''
import os
import apibinding.inventory as inventory
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 ... |
from .client import ImageVersionsClient
from .async_client import ImageVersionsAsyncClient
__all__ = (
"ImageVersionsClient",
"ImageVersionsAsyncClient",
) |
from __future__ import absolute_import
from google.cloud.datalabeling_v1beta1 import DataLabelingServiceClient
from google.cloud.datalabeling_v1beta1 import enums
from google.cloud.datalabeling_v1beta1 import types
__all__ = ("enums", "types", "DataLabelingServiceClient") |
from __future__ import absolute_import, division, print_function, unicode_literals
from .azure_common import BaseTest
from c7n_azure.actions.base import AzureBaseAction, AzureEventAction
from c7n_azure.session import Session
from mock import patch, MagicMock, ANY
from c7n.utils import local_session
class AzureBaseActio... |
import datetime
from src.utils import logger, tools, db
import pandas
log = logger.create_logger(__name__)
last_update_half = None
def test():
now = datetime.datetime.now()
now = now.replace(hour=0, microsecond=0, second=0, minute=0)
print(now)
return
def code():
print("x\n")
global last_update_... |
"""Module for testing constraints in commands involving vendor."""
import unittest
if __name__ == "__main__":
import utils
utils.import_depends()
from brokertest import TestBrokerCommand
class TestVendorConstraints(TestBrokerCommand):
def testdelvendorwithmodel(self):
command = "del vendor --vendor ... |
'''
@author: YeTian 2017-12-23
Test on centos71 mini iso (upgrade kernel 3.10.0.327 and iproute 54) installed zstack 2.2.3 release 516, upgrade the latest zstack
and add zone cluster host ps bs l2 l3 image offering and create a vm with falt-network
'''
import os
import tempfile
import uuid
import time
import zstackwo... |
from time import mktime
from sqlalchemy.exc import IntegrityError
from sqlalchemy import and_, not_
from webob.exc import HTTPPreconditionFailed, HTTPNotFound, HTTPConflict
from webob import Response
from lunr.api.controller.base import BaseController, NodeError
from lunr.db import NoResultFound
from lunr.db.models imp... |
import asyncio
import unittest
from unittest import mock
from aiohttp import CIMultiDict
from aiohttp.web import (
MsgType, Request, WebSocketResponse, HTTPMethodNotAllowed, HTTPBadRequest)
from aiohttp.protocol import RawRequestMessage, HttpVersion11
from aiohttp import errors, websocket
class TestWebWebSocket(uni... |
import contrib.kafka.filters.network.source.protocol.generator as generator
import sys
import os
def main():
"""
Kafka code generator script
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Generates C++ code from Kafka protocol specification for Kafka codec.
Usage:
launcher.py MESSAGE_TYPE OUTPUT_FILES INPUT_FILES
where:... |
"""Script to download votes files to the data/ directory.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from six.moves import urllib
import os
import tarfile
FILE_URI = 'https://storage.googleapis.com/pate-votes/votes.gz'
DATA_DIR = 'data/'
def download... |
"""
Encapsulation for invoking system compiler.
"""
from builtins import object
from subprocess import Popen, PIPE
import tempfile
import hashlib
import pprint
import time
import os
import re
from pych.exceptions import CompilationError
from pych.utils import prepend_path
import pych.specializer
from pych.types import ... |
import os
import itertools
import platform
import subprocess
import sys
import lit.util
from lit.llvm import llvm_config
from lit.llvm.subst import FindTool
from lit.llvm.subst import ToolSubst
def _get_lldb_init_path(config):
return os.path.join(config.test_exec_root, 'Shell', 'lit-lldb-init')
def _disallow(config... |
from __future__ import absolute_import
__all__ = ['GitHubContextCheck']
from flask import current_app
from freight import http
from freight.exceptions import CheckFailed, CheckPending
from .base import Check
ERR_CHECK = '{} context is {}'
ERR_MISSING_CONTEXT = '{} context was not found'
class GitHubContextCheck(Check):... |
'''
------------------------------------------------------------------------------
Copyright 2017 Esri
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
Unl... |
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
('common', '0001_initial'),
migration... |
from rally.benchmark.context import base
from rally.benchmark.context.cleanup import manager as resource_manager
from rally.benchmark.scenarios.heat import utils as heat_utils
from rally.common.i18n import _
from rally.common import log as logging
from rally.common import utils as rutils
from rally import consts
from r... |
r"""Parses lint report and dump filtered messages in hjson format.
"""
import argparse
import logging as log
import sys
from pathlib import Path
from LintParser import LintParser
def main():
parser = argparse.ArgumentParser(
description="""This script parses Verilator lint log and report files
from ... |
from django.conf.urls.defaults import *
def dummy_view(request):
from django.http import HttpResponse
return HttpResponse()
urlpatterns = patterns('',
url(r'^$', dummy_view, name='modeldict-home'),
) |
'''
@author: bpuype
copyright 2014-2015 FP7 FELIX, iMinds
'''
from urlparse import urlparse
def add_basic_auth(uri, username=None, password=None):
parsed = urlparse(uri.lower())
if username:
if password:
new_url = "%s://%s:%s@%s%s" % (parsed.scheme,
... |
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('share', '0044_merge_20170628_1811'),
]
operations = [
# Resync the subject PK sequence with the table.
# An old load script manually assigned ids.
... |
FOOTER = """
<center>
<br/>
<br/>
<br/>
<br/>
<div id="footer">©2011-2018 Open Source Electronic Health Record Alliance<br />This work is licensed under a <a href="https://creativecommons.org/licenses/by/3.0/">Creative Commons Attribution 3.0 Unported License</a> <a href="https://creativecommons.org/licenses/... |
from __future__ import (nested_scopes, generators, division, absolute_import, with_statement,
print_function, unicode_literals)
from contextlib import contextmanager
import os
from pants.backend.jvm.targets.jvm_binary import JvmBinary
from pants.backend.jvm.tasks.jar_task import JarTask
from pan... |
import time
from twisted.internet import reactor
from twisted.internet.protocol import DatagramProtocol
from twisted.internet.error import ConnectionDone
from twisted.protocols.basic import LineOnlyReceiver, Int32StringReceiver
from twisted.protocols.policies import TimeoutMixin
from carbon import log, events, state, m... |
import socket
from http.client import HTTPConnection
from typing import Dict, List, Optional, Tuple, Union
from xmlrpc import client
class UnixStreamHTTPConnection(HTTPConnection):
def connect(self) -> None:
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sock.connect(self.host)
c... |
"""
This is a tool to extract useful information from given record files. It does
self-check the validity of the uploaded data and able to inform developer's when
the data is not qualified, and reduce the size of uploaded data significantly.
"""
from datetime import datetime
import argparse
import os
import sys
import ... |
import os
import sys
import click
from rackspace_monitoring.providers import get_driver
from rackspace_monitoring.types import Provider
import requests
@click.group()
@click.option("--username", required=True)
@click.option("--api-key", required=True)
@click.pass_context
def cli(ctx, api_key, username):
ctx.obj = {... |
"""saltshaker URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/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-b... |
"""This example gets all images and videos. To upload an image, run
upload_image.py. To upload video, see:
http://adwords.google.com/support/aw/bin/answer.py?hl=en&answer=39454.
Tags: MediaService.get
"""
__author__ = 'api.kwinter@gmail.com (Kevin Winter)'
import os
import sys
sys.path.insert(0, os.path.join('..', '..'... |
from django import forms
class CommentForm(forms.Form):
"""Comment Form class clear"""
visitor = forms.CharField(max_length=20)
email = forms.EmailField(max_length=20, required=False)
content = forms.CharField(max_length=200, widget=forms.Textarea())
def clean_content(self):
"""check content... |
"""\
Implementation of the 'dots' Serializer.
"""
import re
from .flat_serializer import FlatSerializer
__author__ = "Simone Campagna"
__copyright__ = 'Copyright (c) 2015 Simone Campagna'
__license__ = 'Apache License Version 2.0'
__all__ = [
'join_dots_key',
'normalize_dots_key',
'split_dots_key',
'Dot... |
from django.conf import settings
from django.db import migrations, models
def modify_job_templates(apps, schema_editor):
if not settings.MIGRATE_INITIAL_DATA:
return
JobTemplate = apps.get_model('dashboard', 'JobTemplate')
JobTemplate.objects.filter(job_template_type="pulltrans").update(
job... |
from horizon import tables as horizon_tables
from cloudvalidation.ostf_tests import tables
from cloudvalidation.api import cloudv
class TestDescriptor(object):
def __init__(self, test, report):
self._report = report
self.test = test
self.report = report['report']
self.duration = repo... |
"""
Created on February 22 2019
@author: talbpaul
Template interface for the test UQ template input.
"""
from __future__ import print_function, unicode_literals
import os
import configparser
from collections import OrderedDict
from UQTemplate.UQTemplate import UQTemplate
print('Loading template ...')
temp = UQTemplate(... |
from __future__ import absolute_import, unicode_literals
import contextlib
import logging
from mopidy import exceptions
from mopidy.compat import urllib
from mopidy.core import listener
from mopidy.internal import deprecation, validation
from mopidy.models import Playlist, Ref
logger = logging.getLogger(__name__)
@cont... |
"""Tests for tf.layers.base."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import copy
import numpy as np
from tensorflow.python.eager import context
from tensorflow.python.eager import def_function
from tensorflow.python.framework import constant_op
fro... |
import unittest, sys, time
sys.path.extend(['.','..','../..','py'])
import h2o, h2o_cmd, h2o_import as h2i, h2o_glm, h2o_common, h2o_exec as h2e
import h2o_print
DO_GLM = False
LOG_MACHINE_STATS = False
print "Assumes you ran ../build_for_clone.py in this directory"
print "Using h2o-nodes.json. Also the sandbox dir"
cl... |
"""Tests for /query api endpoint."""
from sqlalchemy import func
from flask import json
from ddt import ddt
from ddt import data
from ggrc import app
from ggrc import views
from ggrc import models
from ggrc import db
from integration.ggrc import TestCase
from integration.ggrc.models import factories
@ddt
class TestAudi... |
__author__ = 'Shamal Faily'
class Target:
def __init__(self,tName,tEffectiveness,tRat):
self.theName = tName
self.theEffectiveness = tEffectiveness
self.theRationale = tRat
def name(self): return self.theName
def effectiveness(self): return self.theEffectiveness
def rationale(self): return self.theR... |
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('indicators', '0005_auto_20180211_0410'),
]
operations = [
migrations.AlterField(
model_name='collecteddata',... |
"""Config flow for MQTT."""
from collections import OrderedDict
import queue
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import (
CONF_DISCOVERY,
CONF_HOST,
CONF_PASSWORD,
CONF_PAYLOAD,
CONF_PORT,
CONF_PROTOCOL,
CONF_USERNAME,
)
from .const impo... |
from __future__ import absolute_import
import os
import shutil
from typing import List, Any, Tuple
from django.conf import settings
from django.contrib.staticfiles.storage import ManifestStaticFilesStorage
from pipeline.storage import PipelineMixin
from zerver.lib.str_utils import force_str
class AddHeaderMixin(object)... |
from pyparsing import (
Forward, Combine, Optional, Word, Literal, CaselessKeyword,
CaselessLiteral, Group, FollowedBy, LineEnd, OneOrMore, ZeroOrMore,
alphas, alphanums, printables, delimitedList, quotedString, Regex,
__version__, Suppress, Empty
)
grammar = Forward()
expression = Forward()
intNumber =... |
"""This module provides plugins for basic duplicate code detection."""
from __future__ import print_function
from hairball.plugins import HairballPlugin
class DuplicateScripts(HairballPlugin):
"""Plugin that detects duplicate scripts within a project."""
def __init__(self):
"""Initialize an instance of ... |
import json
import logging
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import last_modified as cache_last_modified
from django.views.decorators.cache import never_cache as force_cache_validation
from django.core.cache import get_cache
from... |
import numpy
import Orange.data
from Orange.statistics import distribution, basic_stats
from .transformation import Transformation, Lookup
__all__ = ["ReplaceUnknowns", "Average"]
class ReplaceUnknowns(Transformation):
"""
A column transformation which replaces unknown values with a fixed `value`.
Parameter... |
from troposphere import GetAtt, Template, Tags
from troposphere.dlm import (LifecyclePolicy, PolicyDetails, Schedule,
RetainRule, CreateRule)
from troposphere.iam import Role
from awacs.aws import Allow, Statement, Principal, Policy
from awacs.sts import AssumeRole
t = Template()
t.add_vers... |
import os
import argparse
import logging
import multiprocessing
import fileinput
import traceback
from functools import partial, update_wrapper
import json
import base64
from external_cmd import TimedExternalCmd
import pysam
import pybedtools
import extract_pairs
from defaults import *
FORMAT = '%(levelname)s %(asctime... |
"""
Defines an abstract APITask class with various helpful features like error handling
and explosions.
"""
import datetime
import hashlib
import requests
import time
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
from billiard import current_process
from celery ... |
from __future__ import absolute_import
import atexit
import functools
from . import server
from . import interpreter
def setup(app_name, atexit_register=atexit.register, **kwargs):
"""Non-standalone user setup."""
import os
import sys
base = '/var/tmp/remotecontrol.%s.%s' % (app_name, os.getpid())
s... |
'''
Pushes stored user favorites to Scout for alert tracking.
'''
import json
import logging
import urlparse
import datetime
from optparse import make_option
from django.contrib.auth.models import User
from django.core.management.base import NoArgsCommand
from billy.core import settings, user_db
from billy.utils import... |
default_app_config = 'machina.apps.forum_permission.registry_config.PermissionRegistryConfig' |
""" Fundamental Physical Constants
These constants are taken from CODATA Recommended Values of the
Fundamental Physical Constants: 2002. They may be found at
physics.nist.gov/constants. The values are stored in the dictionary
physical_constants as a tuple containing the value, the units, and
the rel... |
import os,re,subprocess
from waflib import Task,Errors,TaskGen,Configure,Node,Logs
from brick_general import ChattyBrickTask
from TclParser import *
def configure(conf):
"""This function gets called by waf upon loading of this module in a configure method"""
conf.load('brick_general')
if not conf.env.BRICK_LOGFILES:... |
"""Asynchronous event tracking for Mixpanel"""
VERSION = (0, 5, 0, '')
__version__ = ".".join(map(str, VERSION[:-1]))
__release__ = ".".join(map(str, VERSION))
__author__ = "Wes Winham"
__contact__ = "wes@policystat.com"
__homepage__ = "http://github.com/winhamwr/mixpanel-celery/"
__docformat__ = "restructuredtext" |
import subprocess
import sys
import os
import setup_util
def start(args, logfile, errfile):
setup_util.replace_text("php-laravel/application/config/database.php", "localhost", ""+ args.database_host +"")
setup_util.replace_text("php-laravel/deploy/nginx.conf", "root .*\/FrameworkBenchmarks/php-laravel", "root " + a... |
"""
Tests for implementations of L{IReactorUNIX}.
"""
from stat import S_IMODE
from os import stat, close
from tempfile import mktemp
from socket import AF_INET, SOCK_STREAM, socket
from pprint import pformat
from hashlib import md5
try:
from socket import AF_UNIX
except ImportError:
AF_UNIX = None
from zope.in... |
import pytest
import redis
@pytest.fixture(autouse=True)
def celery_eager():
from celery import current_app
current_app.conf.CELERY_ALWAYS_EAGER = True
current_app.conf.CELERY_EAGER_PROPAGATES_EXCEPTIONS = True
@pytest.fixture
def redis_reset():
redis.Redis().flushall()
@pytest.fixture
def cassandra_res... |
"""Service for tracking isolates and looking them up by builder and commit.
An isolate is a way to describe the dependencies of a specific build.
More about isolates:
https://github.com/luci/luci-py/blob/master/appengine/isolate/doc/client/Design.md
"""
import json
import webapp2
from dashboard.common import utils
from... |
import logging
import psutil
import signal
from pylib import android_commands
def _KillWebServers():
for s in [signal.SIGTERM, signal.SIGINT, signal.SIGQUIT, signal.SIGKILL]:
signalled = []
for server in ['lighttpd', 'webpagereplay']:
for p in psutil.process_iter():
try:
if not server ... |
import doctest
import unittest
import trac.ticket
from trac.ticket.tests import api, model, query, wikisyntax, notification, \
conversion, report, roadmap
from trac.ticket.tests.functional import functionalSuite
def suite():
suite = unittest.TestSuite()
suite.addTest(api.suite())
... |
from datetime import date
from rapidsms.contrib.locations.models import LocationType, Location
from survey.models import Investigator, Household, Backend
from survey.models.households import HouseholdMember
from survey.models.unknown_dob_attribute import UnknownDOBAttribute
from survey.tests.base_test import BaseTest
c... |
"""
tinycss.token_data
------------------
Shared data for both implementations (Cython and Python) of the tokenizer.
:copyright: (c) 2012 by Simon Sapin.
:license: BSD, see LICENSE for more details.
"""
from __future__ import unicode_literals
import functools
import operator
import re
import string
... |
"""
This module contains the definition of ``FiberSource``, which is a continuous
representation of a fiber. All the fibers created are supposed to connect two
cortical areas. Currently, the only supported shape for the "cortical surface"
is a sphere.
"""
import numpy as np
from scipy.interpolate import BPoly
class Fib... |
"""Test forms."""
from wilfully.public.forms import LoginForm
from wilfully.user.forms import RegisterForm
class TestRegisterForm:
"""Register form."""
def test_validate_user_already_registered(self, user):
"""Enter username that is already registered."""
form = RegisterForm(username=user.userna... |
"""Program to convert power logging config from a servo_ina device
to a sweetberry config.
"""
from __future__ import print_function
import os
import sys
def fetch_records(basename):
"""Import records from servo_ina file.
servo_ina files are python imports, and have a list of tuples with
the INA data.
(inaty... |
"""
Tests path_bin.
"""
import difflib
import logging
import unittest
import os
from md_utils.md_common import find_backup_filenames, silent_remove, diff_lines
from md_utils.path_make import process_infile, main, bin_data
__author__ = 'hmayes'
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__... |
import operator
from cms.utils import get_cms_setting
from cms.utils.compat.type_checks import string_types
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from cms.utils.compat.dj import force_unicode
from django.db.models.query_utils import Q
def get_toolbar_plugin_struct(plug... |
from logging.config import fileConfig
from logging import getLogger
from os import listdir
from os.path import abspath, join, dirname, splitext
from pkg_resources import resource_filename
import click
_CONTEXT_SETTINGS = dict(
# allow case insensitivity for the (sub)commands and their options
token_normalize_fu... |
import requests
import json
from config import MailChimpConfig
config = MailChimpConfig()
endpoint = config.api_root
response = requests.get(endpoint, auth=('apikey', config.apikey))
print response.url
try:
response.raise_for_status()
response_json = response.json()
except requests.exceptions.HTTPError as err:
pr... |
from unittest.mock import patch
from django.test.utils import override_settings
from hc.api.models import Channel
from hc.test import BaseTestCase
@override_settings(LINENOTIFY_CLIENT_ID="t1", LINENOTIFY_CLIENT_SECRET="s1")
class AddLineNotifyCompleteTestCase(BaseTestCase):
url = "/integrations/add_linenotify/"
... |
from __future__ import division
from sympy import I, Rational, Symbol, pi, sqrt
from sympy.geometry import Line, Point, Point3D, Line3D
from sympy.geometry.entity import rotate, scale, translate
from sympy.matrices import Matrix
from sympy.utilities.pytest import raises
x = Symbol('x', real=True)
y = Symbol('y', real=T... |
"""Quadratic Program Solver based on CPLEX.
"""
import re
from sys import stdout, stderr
from numpy import array, NaN, Inf, ones, zeros, shape, finfo, arange, r_
from numpy import flatnonzero as find
from scipy.sparse import csr_matrix as sparse
try:
from cplex import Cplex, cplexlp, cplexqp
except ImportError:
... |
from __future__ import print_function
from __future__ import absolute_import
from .process_submissions import *
import django
def _dojob(j):
django.db.connection.close()
#j = Job.objects.get(id=jid)
print('Running', j)
try_dojob(j, j.user_image)
if __name__ == '__main__':
#job = Job.objects.get(id=3... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.