content stringlengths 4 20k |
|---|
from warcat.tool import ListTool, VerifyTool, SplitTool, ExtractTool, ConcatTool
import glob
import os.path
import tempfile
import unittest
class TestTool(unittest.TestCase):
test_dir = os.path.join('example')
def test_list(self):
tool = ListTool([os.path.join(self.test_dir, 'at.warc')])
tool... |
import zipfile
from io import BytesIO
from django.conf import settings
from django.http import HttpResponse
from django.template import loader
# NumPy supported?
try:
import numpy
except ImportError:
numpy = False
def compress_kml(kml):
"Returns compressed KMZ from the given KML string."
kmz = Bytes... |
# -*- coding: utf-8 -*-
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 'VideoUploadConfig'
db.create_table('contentstore_videouploadconfig', (
('id', se... |
"""
HTTP server that implements the Python WSGI protocol (PEP 333, rev 1.21).
Based on wsgiref.simple_server which is part of the standard library since 2.5.
This is a simple server for use in testing or debugging Django apps. It hasn't
been reviewed for security issues. DON'T USE IT FOR PRODUCTION USE!
"""
from __f... |
"""Utility methods for testing"""
import hashlib
import imp
from mock import Mock, patch
from apache_beam.utils import retry
DEFAULT_HASHING_ALG = 'sha1'
def compute_hash(content, hashing_alg=DEFAULT_HASHING_ALG):
"""Compute a hash value from a list of string."""
content.sort()
m = hashlib.new(hashing_alg)
... |
from __future__ import print_function
import unittest
import warnings
warnings.resetwarnings()
warnings.simplefilter("ignore")
class TestBasic(unittest.TestCase):
def setUp(self):
import warnings
super().setUp()
warnings.simplefilter('ignore')
def test_table(self):
from r... |
# read both pickle data that starts with the defined string
# write packs of < 50MB pickle data
# write triples in packs of < 50MB
import social as S, percolation as P, os, re
import importlib, datetime
importlib.reload(S.tw)
importlib.reload(P.utils)
ddir="../data/tw/"
#a=P.utils.pRead2(ddir+ "{}.pickle".format(sid)... |
"""
Browser set up for acceptance tests.
"""
# pylint: disable=E1101
# pylint: disable=W0613
from lettuce import before, after, world
from splinter.browser import Browser
from logging import getLogger
from django.core.management import call_command
from django.conf import settings
from selenium.common.exceptions impo... |
__author__ = "Samvid Mistry"
import sys
from PySide.QtGui import *
from PySide.QtCore import *
from MUtilities import MColors
from MBase.MAnimationThread import MAnimationThread
from MComponents.MTestComponent import MTestComponent
class MainWindow(QWidget):
def __init__(self):
QWidget.__init__(self)
... |
import markdown
ElementTree = markdown.etree.ElementTree
QName = markdown.etree.QName
Comment = markdown.etree.Comment
PI = markdown.etree.PI
ProcessingInstruction = markdown.etree.ProcessingInstruction
HTML_EMPTY = ("area", "base", "basefont", "br", "col", "frame", "hr",
"img", "input", "isindex", "link... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants.option.ranked_value import RankedValue
class OptionValueContainer(object):
"""A container for option values.
Implements the following functionality:
... |
from textwrap import dedent
from typing import Optional, Union
from unittest.case import TestCase
from service_client.utils import IncompleteFormatter, random_token, build_parameter_object
class TestIncompleteFormatter(TestCase):
def setUp(self):
self.formatter = IncompleteFormatter()
def test_all_... |
from gi.repository import Gtk, Gtk.Gdk
from gi.repository import GObject
from math import floor
from BoardView import BoardView
from pychess.Utils.const import *
from pychess.Utils.Cord import Cord
ALL = 0
class SetupBoard (Gtk.EventBox):
__gsignals__ = {
'cord_clicked' : (SIGNAL_RUN_FIRST, TYPE_NO... |
"""
Test the noise tolerance of Layer 2 in isolation.
Perform an experiment to see if L2 eventually recognizes an object.
Test with various noise levels and with various column counts and synapse
sample sizes.
"""
from collections import defaultdict
import json
import math
import random
import os
import time
import ... |
import os
import time
from jujubigdata import utils
from path import Path
from charms.layer.apache_bigtop_base import Bigtop
from charms import layer
from charmhelpers.core import hookenv, host, unitdata
from charmhelpers.fetch.archiveurl import ArchiveUrlFetchHandler
from charmhelpers.payload import archive
class S... |
# -*- coding: utf-8 -*-
from openerp.tests import common
from datetime import datetime
class TestSaleMrpFlow(common.TransactionCase):
def setUp(self):
super(TestSaleMrpFlow, self).setUp()
# Useful models
self.SaleOrderLine = self.env['sale.order.line']
self.SaleOrder = self.env['... |
from rdflib.graph import Graph
from rdflib.term import URIRef
from swipy.store import SWIStore
from os import path, stat
owl_test = path.join(path.dirname(__file__), "owl.rdf")
skos_test = path.join(path.dirname(__file__), "skos.rdf")
cofog_test = path.join(path.dirname(__file__), "cofog-1999.rdf")
entail_test = path.... |
from __future__ import print_function
import sys
from optparse import OptionParser
from rdkit import Chem
from rdkit import DataStructs
from collections import defaultdict
#input format
#query_substructs,query_smiles,SMILES,ID,Tversky_sim
#algorithm
#read in query_substructs and smiles
#feed to atomcontrib function t... |
import requests
from cloudbot import hook
from cloudbot.util import web
# Define some constants
base_url = 'https://maps.googleapis.com/maps/api/'
geocode_api = base_url + 'geocode/json'
# Change this to a ccTLD code (eg. uk, nz) to make results more targeted towards that specific country.
# <https://developers.goog... |
from .entity import Entity
from ..errors import (InvalidEndpointOperation, InvalidEndpoint,
InvalidArguments)
class Note(Entity):
"""PagerDuty note entity."""
@classmethod
def fetch(*args, **kwargs):
"""Disable this endpoint, not valid v2."""
raise InvalidEndpoint('N... |
# pylint: skip-file
# flake8: noqa
class PolicyUserException(Exception):
''' PolicyUser exception'''
pass
class PolicyUserConfig(OpenShiftCLIConfig):
''' PolicyUserConfig is a DTO for user related policy. '''
def __init__(self, namespace, kubeconfig, policy_options):
super(PolicyUserConfig,... |
from numba import cuda
from numba.cuda.cudadrv.driver import driver
from numba import numpy_support as nps
import math
def transpose(a, b=None):
"""Compute the transpose of 'a' and store it into 'b', if given,
and return it. If 'b' is not given, allocate a new array
and return that.
This implements th... |
import boto
from boto.services.service import Service
from boto.services.message import ServiceMessage
import os
import mimetypes
class SonOfMMM(Service):
def __init__(self, config_file=None):
Service.__init__(self, config_file)
self.log_file = '%s.log' % self.instance_id
self.log_path = o... |
import copyreg
import unittest
from test import support
from test.pickletester import ExtensionSaver
class C:
pass
class WithoutSlots(object):
pass
class WithWeakref(object):
__slots__ = ('__weakref__',)
class WithPrivate(object):
__slots__ = ('__spam',)
class WithSingleString(object):
__slot... |
"""Common operations on Posix pathnames.
Instead of importing this module directly, import os and refer to
this module as os.path. The "os.path" name is an alias for this
module on Posix systems; on other systems (e.g. Mac, Windows),
os.path provides the same operations in a manner specific to that
platform, and is a... |
import time
from collections import OrderedDict
from importlib import import_module
from django.apps import apps
from django.core.checks import Tags, run_checks
from django.core.management.base import BaseCommand, CommandError
from django.core.management.sql import (
emit_post_migrate_signal, emit_pre_migrate_sign... |
from openerp.osv import fields, osv
from openerp.tools.translate import _
class hired_employee(osv.osv_memory):
_name = 'hired.employee'
_description = 'Create Employee'
def case_close(self, cr, uid, ids, context=None):
"""
@param self: The object pointer
@param cr: the current row... |
import gdb
# This small code snippet deals with problem of strings in Python 2.x
# and Python 3.x. Python 2.x has str and unicode classes which are
# sub-classes of basestring. In Python 3.x all strings are encoded
# and basestring has been removed.
try:
basestring
except NameError:
basestring = str
class F... |
"""
Run all unit tests for the aeneas package.
"""
from __future__ import absolute_import
from __future__ import print_function
import glob
import os
import sys
import unittest
__author__ = "Alberto Pettarin"
__email__ = "<EMAIL>"
__copyright__ = """
Copyright 2012-2013, Alberto Pettarin (www.albertopettarin.it)
... |
"""
Verifies that the user can override the compiler and linker using
CC/CXX/NM/READELF environment variables.
"""
import TestGyp
import os
import copy
import sys
here = os.path.dirname(os.path.abspath(__file__))
if sys.platform == 'win32':
# cross compiling not supported by ninja on windows
# and make not suppo... |
def export_to_jdbc(self, connection_url, table_name):
"""
Write current frame to JDBC table
Parameters
----------
:param connection_url: (str) JDBC connection url to database server
:param table_name: (str) JDBC table name
Example
-------
<skip>
>>> from sparktk import T... |
from __future__ import absolute_import, unicode_literals
from operator import attrgetter
from django.core.exceptions import FieldError
from django.db import connection
from django.test import TestCase
from django.test.utils import CaptureQueriesContext
from django.utils import six
from .models import (Chef, CommonIn... |
import numpy as np
from bhmm.hmm.generic_hmm import HMM
from bhmm.util import config
from bhmm.util.statistics import confidence_interval_arr
class SampledHMM(HMM):
""" Sampled HMM with a representative single point estimate and error estimates
Parameters
----------
estimated_hmm : :class:`HMM <gene... |
#!/usr/bin/env python
import sys
def supported(from_int, from_modifier, to_int, to_modifer):
if from_modifier != to_modifer:
return False
if from_int > to_int:
return False
return True
def gen_tests_for_int(from_int, from_modifier, int_types, modifiers):
for to_int in range(len(int_types... |
import re
import time
import logging
from autotest.client.shared import error
from autotest.client.shared import utils
from virttest import utils_misc
from virttest import env_process
from virttest import utils_test
@error.context_aware
def run(test, params, env):
"""
Configure watchdog, crash the guest and ... |
"""
Compatibility constants and functions. This module works on Python 1.5 to 2.5.
This module provides:
- True and False constants ;
- any() and all() function ;
- has_yield and has_slice values ;
- isinstance() with Python 2.3 behaviour ;
- reversed() and sorted() function.
True and False constants
===============... |
"""Functional tests for ExtractImagePatches op."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.framework import constant_op
from tensorflow.python.ops import array_ops
from tensorflow.python.platform import tes... |
"""
Admin site models for managing :class:`.ConfigurationModel` subclasses
"""
from django.forms import models
from django.contrib import admin
from django.contrib.admin import ListFilter
from django.core.cache import get_cache, InvalidCacheBackendError
from django.core.urlresolvers import reverse
from django.http imp... |
import base.tester
import base.utils as utils
import base.paths as paths
from base.net import Declarations
import os.path
import build
from copy import copy
class CheckStatement(base.tester.Check):
def __init__(self, expression, decls=None, return_type="void", source=None):
self.expression = expression
... |
from django.conf import settings
from django.core import signals
from django.core.exceptions import ImproperlyConfigured
from django.db.utils import (ConnectionHandler, ConnectionRouter,
load_backend, DEFAULT_DB_ALIAS, DatabaseError, IntegrityError)
__all__ = ('backend', 'connection', 'connections', 'router', 'Dat... |
from selenium import webdriver
import time,os,sys
stepNum = 1
options = webdriver.ChromeOptions()
options.add_experimental_option("excludeSwitches",["ignore-certificate-errors"])
browser = webdriver.Chrome(chrome_options=options)
browser.get("http://www.cnaidai.com/")
print stepNum,": Come in First_Page"
stepNum += 1
... |
import os
import unittest
import threading
import imath
import IECore
import Gaffer
import GafferTest
import GafferImage
import GafferImageTest
class ImageNodeTest( GafferImageTest.ImageTestCase ) :
def testCacheThreadSafety( self ) :
c = GafferImage.Constant()
c["format"].setValue( GafferImage.Format( 200, 2... |
from math import pi, sqrt
import bpy
from mathutils import Quaternion
from ..mu import MuCamera
from .. import properties
def create_camera(mu, muobj, mucamera, name):
camera = bpy.data.cameras.new(name)
#mucamera.clearFlags
camera.type = ['PERSP', 'ORTHO'][mucamera.orthographic]
camera.lens_unit = '... |
"""Tests for SinhArcsinh Bijector."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
# pylint: disable=g-importing-member
from tensorflow.contrib.distributions.python.ops.bijectors.sinh_arcsinh import SinhArcsinh
from tensorflow.python.... |
"""
Tests common to genericpath, macpath, ntpath and posixpath
"""
import unittest
from test import test_support
import os
import genericpath
import sys
def safe_rmdir(dirname):
try:
os.rmdir(dirname)
except OSError:
pass
class GenericTest(unittest.TestCase):
# The path module to be tes... |
from blinker import Namespace
_signals = Namespace()
can_access = _signals.signal('can-access', """
Called when `ProtectionMixin.can_access` is used to determine if a
user can access something or not.
The `sender` is the type of the object that's using the mixin. The
actual instance is passed as `obj`. The `user... |
"""Contains definitions of box sampler."""
# Import libraries
import tensorflow as tf
from official.vision.beta.ops import sampling_ops
@tf.keras.utils.register_keras_serializable(package='Vision')
class BoxSampler(tf.keras.layers.Layer):
"""Creates a BoxSampler to sample positive and negative boxes."""
def __... |
"""Support for interacting with Smappee Comport Plugs."""
import logging
from homeassistant.components.switch import SwitchDevice
from . import DATA_SMAPPEE
_LOGGER = logging.getLogger(__name__)
ICON = "mdi:power-plug"
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Smappee ... |
from __future__ import print_function
import unittest
import numpy as np
from op_test import OpTest
import paddle.fluid.core as core
from paddle import rand
import paddle.fluid as fluid
from paddle.fluid import compiler, Program, program_guard
import paddle
class TestRandOpError(unittest.TestCase):
"""
This... |
"""
File: 1155002613_hw3.py
Author: Me
Email: 0
Github: 0
Description: Compute betweenness centrality and produce the network graph
"""
import os
import pydot
import networkx as nx
with open(os.path.join('.', 'input.csv'), 'r') as f:
lines = [l.rstrip('\n') for l in f.readlines()]
# Process graph
graph = pydot.... |
import unittest
from ctypes import *
class MyInt(c_int):
def __eq__(self, other):
if type(other) != MyInt:
return NotImplementedError
return self.value == other.value
class Test(unittest.TestCase):
def test_compare(self):
self.assertEqual(MyInt(3), MyInt(3))
self.a... |
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
from airflow.hooks.base_hook import BaseHook
class GenericTransfer(BaseOperator):
"""
Moves data from a connection to another, assuming that they both
provide the required methods in their respective hooks. The sou... |
"""
"Safe weakrefs", originally from pyDispatcher.
Provides a way to safely weakref any function, including bound methods (which
aren't handled by the core weakref module).
"""
import traceback
import weakref
def safeRef(target, onDelete = None):
"""Return a *safe* weak reference to a callable target
target... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Jelly Plugin - A minimal plugin framework.
The idea and basis for this code came from:
http://martyalchin.com/2008/jan/10/simple-plugin-framework/
To create a pluginhook define a new class, and set `PluginMount` or
`TaxonomyPluginMount` as its `__metaclass__`.
Every... |
import pickle
import tempfile
import shutil
import os
import numbers
import numpy as np
from sklearn.utils.testing import assert_almost_equal
from sklearn.utils.testing import assert_array_equal
from sklearn.utils.testing import assert_raises
from sklearn.utils.testing import assert_raises_regexp
from sklearn.utils.t... |
#!/usr/bin/python3
from troposphere import cloudfront, ImportValue
class CloudfrontConfigError(Exception):
"""
Error thrown Cloudfront objects are misconfigured
"""
def __init__(self, value):
self.value = value
class CFDistribution(object):
def __init__(self, title, template, cf_origin... |
from operator import itemgetter
import time
from openerp import models, api
from openerp.osv import osv, orm, fields
from openerp.tools.misc import attrgetter
# -------------------------------------------------------------------------
# Properties
# --------------------------------------------------------------------... |
import numpy as np
from tensorlib.decomposition import cp
from tensorlib.decomposition.decomposition import _cp3
from tensorlib.decomposition import tucker
from tensorlib.decomposition.decomposition import _tucker3
from tensorlib.datasets import load_bread
from numpy.testing import assert_almost_equal
from nose.tools i... |
from ..testutil import eq_
from ...const import AccountType
from ..base import TestApp, with_app
# ---
def app_two_txns():
app = TestApp()
app.add_account('one')
app.add_account('two', account_type=AccountType.Liability)
app.add_txn(description='first', from_='one', to='two', amount='42')
app.add_... |
error_codes = (
("OK", 1, ""),
("GENERAL", 2, "$0"),
("CANCELLED", 3, "$0"),
("ANALYSIS_ERROR", 4, "$0"),
("NOT_IMPLEMENTED_ERROR", 5, "$0"),
("RUNTIME_ERROR", 6, "$0"),
("MEM_LIMIT_EXCEEDED", 7, "$0"),
("INTERNAL_ERROR", 8, "$0"),
("RECOVERABLE_ERROR", 9, "$0"),
("PARQUET_MULTIPLE_BLOCKS",... |
from __future__ import unicode_literals, division, absolute_import
from builtins import * # noqa pylint: disable=unused-import, redefined-builtin
import pytest
class TestOnlyTask(object):
"""
Test --task option
"""
config = """
tasks:
test:
mock:
- {t... |
"""
Code for serializing a modulestore XBlock to OLX suitable for import into
Blockstore.
"""
import logging
import os
from collections import namedtuple
from lxml import etree
from . import adapters
log = logging.getLogger(__name__)
# A static file required by an XBlock
StaticFile = namedtuple('StaticFile', ['name... |
"""Helper functions for using the FoLiA format from pynlpl.
"""
from pynlpl.formats import folia
from lxml import etree
import os
def parse_document(file_name):
try:
doc = folia.Document(file=file_name)
except Exception as e:
return None, 'Unable to parse FoLiA XML file.\n{}'.format(str(e))
... |
import math
import pygame
import time
# Initializes the pygame library
pygame.init()
# Color definition
BLACK = (0, 0, 0)
BLACKA = (0, 0, 0, 0.3)
WHITE = (255, 255, 255)
WHITEA = (255, 255, 255, 0.3)
BLUE = (0, 0, 255)
BLUEA = (0, 0, 255, 0.3)
GREEN = (0, 255, 0)
GREENA = (0, 255, 0, 0.3)
RED = (255, 0, 0)
REDA = (25... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
######################## Part3: Journal Record #############################
############### General Journal Record class ###############################
class Jrecord(object):
'''Basic journal record information'''
def __init__(self):
... |
"""
Unit tests for the NetApp 7mode NFS storage driver
"""
import ddt
import mock
from os_brick.remotefs import remotefs as remotefs_brick
from oslo_utils import units
from cinder import test
from cinder.tests.unit.volume.drivers.netapp.dataontap import fakes as fake
from cinder.tests.unit.volume.drivers.netapp impor... |
"""
Logistic Regression With LBFGS Example.
"""
from pyspark import SparkContext
# $example on$
from pyspark.mllib.classification import LogisticRegressionWithLBFGS, LogisticRegressionModel
from pyspark.mllib.regression import LabeledPoint
# $example off$
if __name__ == "__main__":
sc = SparkContext(appName="Pyth... |
# -*- encoding: utf-8 -*-
import pilas
from pilas.actores.globo import Globo
class GloboElegir(Globo):
def __init__(self, texto, opciones, funcion_a_invocar, x=0, y=0, dialogo=None):
self.dialogo = dialogo
self.opciones = opciones
self.funcion_a_invocar = funcion_a_invocar
espa... |
import re
import reportlab
import reportlab.lib.units
units = [
(re.compile('^(-?[0-9\.]+)\s*in$'), reportlab.lib.units.inch),
(re.compile('^(-?[0-9\.]+)\s*cm$'), reportlab.lib.units.cm),
(re.compile('^(-?[0-9\.]+)\s*mm$'), reportlab.lib.units.mm),
(re.compile('^(-?[0-9\.]+)\s*px$'), 0.7),
(re.comp... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: vmware_guest_powerstate
short_description: Manages power sta... |
import os
import random
import tempfile
import shutil
import luigi.util
from target import FileSystem, FileSystemTarget
from luigi.format import FileWrapper
class atomic_file(file):
# Simple class that writes to a temp file and moves it on close()
# Also cleans up the temp file if close is not invoked
def... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
from operator import itemgetter
def main():
module = AnsibleModule(
argument_spec = dict(
state = dict(default=None, choices=['enabled', 'disabled',... |
from __future__ import print_function
import os
# Import the PyQt and QGIS libraries
from builtins import str
from qgis.PyQt.QtCore import (QObject, QVariant)
from qgis.core import (QgsProject, QgsVectorLayer, QgsField, QgsCoordinateReferenceSystem, QgsVectorFileWriter,
QgsDataSourceUri, QgsVec... |
import tensorflow as tf
class Vanilla2DCell(tf.contrib.rnn.RNNCell):
"""Vanilla Recurrent Unit cell."""
def __init__(self, num_units, channels):
self._num_units = num_units
self._channels = channels
@property
def state_size(self):
return self._num_units
@property
def ... |
from django.test import TestCase
from django.test import Client
from app_manage_subscriptions.models import manage_subscriptions
# Create your tests here.
class app_manage_subscriptions_test_case ( TestCase ):
def setUp(self):
manage_subscriptions.objects.all().delete()
def test_contact_form_s... |
"""
"""
import traceback
from .const import *
from .button import Button
from .basic import Label, Image
from .table import Table
class Select(Table):
"""A combo dropdown box widget.
Example:
w = Select(value="goats")
w.add("Cats","cats")
w.add("Goats","goats")
w.add("Dog... |
import discord
from discord.ext import commands
import random
class Roller:
"""Rolling dices, the right way"""
def __init__(self, bot):
self.bot = bot
self.roll_arr = []
# Dice rolling function
def roll_dice(self, count, dice, mod, result):
# extra rolls check
extra_r... |
import platform
import mock
from os_brick.initiator import connector
from nova.compute import arch
from nova.tests.unit.virt.libvirt.volume import test_volume
from nova.virt.libvirt.volume import fibrechannel
class LibvirtFibreChannelVolumeDriverTestCase(
test_volume.LibvirtVolumeBaseTestCase):
def tes... |
from django.core.urlresolvers import reverse
from django import http
from mox import IgnoreArg # noqa
from mox import IsA # noqa
from openstack_dashboard import api
from openstack_dashboard.test import helpers as test
from openstack_dashboard.dashboards.identity.groups import constants
GROUPS_INDEX_URL = reverse... |
from spack import *
class PyWorkloadAutomation(PythonPackage):
"""Workload Automation (WA) is a framework for executing workloads and
collecting measurements on Android and Linux devices."""
homepage = "https://github.com/ARM-software/workload-automation"
url = "https://github.com/ARM-software/w... |
import urllib
from oslo_log import log as logging
from oslo_serialization import jsonutils
import requests
from nova.tests.unit.image import fake
LOG = logging.getLogger(__name__)
class APIResponse(object):
"""Decoded API Response
This provides a decoded version of the Requests response which
include... |
#!/usr/bin/env python
'''
Watershed segmentation
=========
This program demonstrates the watershed segmentation algorithm
in OpenCV: watershed().
Usage
-----
watershed.py [image filename]
Keys
----
1-7 - switch marker color
SPACE - update segmentation
r - reset
a - toggle autoupdate
ESC - exit... |
"""This code example gets all products.
Products are created automatically from product templates.
Tags: ProductService.getProductsByStatement
"""
__author__ = 'Nicholas Chen'
# Import appropriate modules from the client library.
from googleads import dfp
def main(client):
# Initialize appropriate service.
pr... |
import httplib
import os
import socket
import sys
import urllib
import urlparse
import warnings
from cStringIO import StringIO
from TTransport import *
class THttpClient(TTransportBase):
"""Http implementation of TTransport base."""
def __init__(self, uri_or_host, port=None, path=None):
"""THttpClient supp... |
"""
Tests for `attr.validators`.
"""
from __future__ import absolute_import, division, print_function
import pytest
import zope.interface
import attr
from attr import has
from attr import validators as validator_module
from attr._compat import TYPE
from attr.validators import and_, in_, instance_of, optional, provi... |
# -*- coding: utf-8 -*
from __future__ import unicode_literals
from django.test import TestCase
from django.utils.text import slugify
from wagtail.wagtailcore.utils import cautious_slugify
class TestCautiousSlugify(TestCase):
def test_behaves_same_as_slugify_for_latin_chars(self):
test_cases = [
... |
"""Tests for the C++ implementation of the temporal pooler."""
import cPickle as pickle
import unittest2 as unittest
import numpy
from nupic.bindings.math import Random
from nupic.research import fdrutilities as fdrutils
from nupic.research.TP import TP
from nupic.research.TP10X2 import TP10X2
VERBOSITY = 0 # how ... |
"""Call HLA alleles with assembly methods implemented in bwakit.
https://github.com/lh3/bwa/blob/master/README-alt.md#hla-typing
https://github.com/lh3/bwa/tree/master/bwakit
"""
import csv
import glob
import os
import toolz as tz
from bcbio import utils
from bcbio.distributed.transaction import file_transaction
fro... |
"""
An in-memory ICollection implementation.
"""
from copy import deepcopy
from uuid import uuid4
from go_api.queue import PausingDeferredQueue, PausingQueueCloseMarker
from twisted.internet.defer import inlineCallbacks
from zope.interface import implementer
from .interfaces import ICollection
from .errors import (
... |
import ldb, sys
import samba.getopt as options
from samba.auth import system_session
from samba.samdb import SamDB
from samba.netcmd import (
Command,
CommandError,
Option
)
from samba.dbchecker import dbcheck
class cmd_dbcheck(Command):
"""check local AD database for errors"""
synopsis = "%pr... |
"""The tests for the time automation."""
from datetime import timedelta
import unittest
from unittest.mock import patch
from homeassistant.bootstrap import _setup_component
import homeassistant.util.dt as dt_util
import homeassistant.components.automation as automation
from tests.common import fire_time_changed, get_... |
from LogAnalyzer import Test,TestResult
import DataflashLog
from VehicleType import VehicleType
class TestBalanceTwist(Test):
'''test for badly unbalanced copter, including yaw twist'''
def __init__(self):
Test.__init__(self)
self.name = "Motor Balance"
def run(self, logdata, verbose):
... |
# -*- coding: utf-8 -*-
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):
# Adding unique constraint on 'Page', fields ['reverse_id', 'site', 'publisher_is... |
from __future__ import unicode_literals
from django.test import TestCase
from rest_framework.negotiation import DefaultContentNegotiation
from rest_framework.renderers import BaseRenderer
from rest_framework.request import Request
from rest_framework.test import APIRequestFactory
factory = APIRequestFactory()
clas... |
#!/usr/bin/python3
#
# cassandra client test program
#
import os
import sys
import datetime
import json
import cassandra
from cassandra.cluster import Cluster
from cassandra.query import tuple_factory, named_tuple_factory, dict_factory, BatchStatement, PreparedStatement
CASSANDRA_CLUSTER = ['192.168.22.112']
def _ge... |
from django.template.base import Lexer, Parser, tag_re, NodeList, VariableNode, TemplateSyntaxError
from django.utils.encoding import force_text
from django.utils.html import conditional_escape
from django.utils.safestring import SafeData, EscapeData
from django.utils.formats import localize
from django.utils.timezone ... |
# -*- coding: utf-8 -*-
'''
Exodus Add-on
Copyright (C) 2016 Exodus
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any l... |
import os
from distutils.core import Command
from distutils.ccompiler import new_compiler
from numpy.distutils.misc_util import get_cmd
class install_clib(Command):
description = "Command to install installable C libraries"
user_options = []
def initialize_options(self):
self.install_dir = None
... |
import subprocess, os.path, re, warnings, textwrap
import types
######################################################################
# Regular Expression Processing
######################################################################
def convert_regexp_to_nongrouping(pattern):
"""
Convert all grouping par... |
'''
DictAdapter
===========
.. versionadded:: 1.5
.. warning::
This code is still experimental, and its API is subject to change in a
future version.
:class:`~kivy.adapters.dictadapter.DictAdapter` is an adapter around a python
dictionary of records. It extends the list-like capabilities of
:class:`~kivy.ad... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.