content string |
|---|
'''
Gesture recognition
===================
This class allows you to easily create new
gestures and compare them::
from kivy.gesture import Gesture, GestureDatabase
# Create a gesture
g = Gesture()
g.add_stroke(point_list=[(1,1), (3,4), (2,1)])
g.normalize()
# Add it to the database
gdb ... |
class User(object):
def __init__(self, parent=None, id='', display_name=''):
if parent:
parent.owner = self
self.type = None
self.id = id
self.display_name = display_name
def startElement(self, name, attrs, connection):
return None
def endElement(self, n... |
""" @file run_swarm.py
This script is the command-line interface for running swarms in nupic."""
import sys
import os
import optparse
from nupic.swarming import permutations_runner
from nupic.swarming.permutations_runner import DEFAULT_OPTIONS
def runPermutations(args):
"""
The main function of the RunPermutati... |
KEY_LENGTH = 16
SREG2AX = { # from http://www.axschema.org/types/#sreg
'nickname': 'http://axschema.org/namePerson/friendly',
'email': 'http://axschema.org/contact/email',
'fullname': 'http://axschema.org/namePerson',
'dob': 'http://axschema.org/birthDate',
'gender': 'http://axschema.org/person... |
from sqlalchemy import Column
from sqlalchemy import MetaData
from sqlalchemy import Table
from sqlalchemy import Text
BASE_TABLE_NAME = 'instance_extra'
NEW_COLUMN_NAME = 'migration_context'
def upgrade(migrate_engine):
meta = MetaData()
meta.bind = migrate_engine
for prefix in ('', 'shadow_'):
... |
from __future__ import division, unicode_literals
import os
import re
import sys
import time
from ..compat import compat_str
from ..utils import (
encodeFilename,
decodeArgument,
format_bytes,
timeconvert,
)
class FileDownloader(object):
"""File Downloader class.
File downloader objects are... |
import os
# toolchains options
ARCH ='risc-v'
CPU ='k210'
CROSS_TOOL ='gcc'
if os.getenv('RTT_ROOT'):
RTT_ROOT = os.getenv('RTT_ROOT')
else:
RTT_ROOT = r'../..'
if os.getenv('RTT_CC'):
CROSS_TOOL = os.getenv('RTT_CC')
if CROSS_TOOL == 'gcc':
PLATFORM = 'gcc'
EXEC_PATH = r'/... |
import sys
import time
from django.conf import settings
from django.db.backends.creation import BaseDatabaseCreation
from django.utils.six.moves import input
TEST_DATABASE_PREFIX = 'test_'
PASSWORD = 'Im_a_lumberjack'
class DatabaseCreation(BaseDatabaseCreation):
# This dictionary maps Field objects to their ass... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import re
import time
import glob
from ansible.plugins.action.iosxr import ActionModule as _ActionModule
from ansible.module_utils._text import to_text
from ansible.module_utils.six.moves.urllib.parse import urlsplit
fro... |
"""Platform to retrieve Jewish calendar information for Home Assistant."""
import logging
import hdate
from homeassistant.components.sensor import SensorEntity
from homeassistant.const import DEVICE_CLASS_TIMESTAMP, SUN_EVENT_SUNSET
from homeassistant.helpers.sun import get_astral_event_date
import homeassistant.util... |
from __future__ import unicode_literals
from sickbeard import db
# Add new migrations at the bottom of the list; subclass the previous migration.
class InitialSchema(db.SchemaUpgrade):
def test(self):
return self.hasTable("db_version")
def execute(self):
queries = [
("CREATE TABL... |
# encoding: 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 'Distrito'
db.create_table('core_distrito', (
('id', self.gf('django.db.models.... |
# This is a good example of how the sk.c stuff can be integrated into
# the raid stuff to be able to verify the image without unpacking the
# whole thing.
import mapper
import optparse,sys
import sk
if __name__ == '__main__':
parser = optparse.OptionParser()
parser.add_option('-p','--period',default=6, type=... |
from ansible.errors import AnsibleError
from ansible.plugins.action import ActionBase
from ansible.template import Templar
from ansible.utils.boolean import boolean
class ActionModule(ActionBase):
TRANSFERS_FILES = False
def run(self, tmp=None, task_vars=dict()):
templar = Templar(loader=self._loader... |
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function)
import numpy as np
from scipy.io import loadmat
# This module is an excerpt from the one in python-gsw.
# Based on Robert Kern's Bunch; taken from
# http://currents.soest.hawaii.edu/hgstage/pycurrents/
# pycurrents/system/uti... |
#Name: Tony Ranieri
#Modified: August 2015
import numpy as np
import pylab as py
import matplotlib.pyplot as plt
def roots(f,df,a,b,niter,epsilon):
# Input
# f: the function that we need to find roots for
# df: derivative of the function f
# a: initial left bracket x-coord
# b: initial right b... |
class TestMod:
def __init__(self, config):
self.value = 0
def get_status(self):
actions = [{"id": "inc", "label": "Increment"}, {"id": "dec", "label": "Decrement"}]
return {"caption": "Test module", "status": str(self.value), "actions": actions }
def exec_command(self, command):
if command == "inc":
s... |
"""
Two players (numbered 1 and 2) are playing a game with n stones. Player 1
always plays first, and the two players move in alternating turns. The game's
rules are as follows:
In a single move, a player can remove 2, 3, or 5 stones from the game board.
If a player is unable to make a move, that player loses the ga... |
#!/usr/bin/env python
from __future__ import division, print_function, absolute_import
import datetime
import os
import sys
from os.path import join as pjoin
if sys.version_info[0] >= 3:
from io import StringIO
else:
from cStringIO import StringIO
import numpy as np
from numpy.testing import (TestCase, asse... |
from beritest_tools import BaseBERITestCase
from nose.plugins.attrib import attr
class test_cp2_ctoptr_tag(BaseBERITestCase):
@attr('capabilities')
def test_cp2_ctoptr_tag_1(self):
'''Check that ctoptr of a capability with the tag bit unset returns 0'''
self.assertRegisterEqual(self.MIPS.a0, 0... |
"""
test_images
--------------
Tests for `dox.images` module.
"""
import fixtures
import testscenarios
from dox import images
from dox.tests import base
def get_fake_image(value):
if value is not None:
def fake_value(self):
return value
else:
def fake_value(self):
re... |
import unittest
from unittest import mock
from test.support import captured_stderr
import idlelib.run as idlerun
class RunTest(unittest.TestCase):
def test_print_exception_unhashable(self):
class UnhashableException(Exception):
def __eq__(self, other):
return True
ex1... |
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
import os
from tempfile import mkdtemp
from shutil import rmtree
import numpy as np
import nibabel as nb
from nipype.testing import (assert_equal, assert_not_equal,
assert_rai... |
from django.conf.urls.defaults import *
urlpatterns = patterns('pootle_project.views',
(r'^$|^index.html$', 'projects_index'),
(r'^(?P<project_code>[^/]*)/admin.html$', 'project_admin'),
(r'^(?P<project_code>[^/]*)/permissions.html$', 'project_admin_permissions'),
(r'^(?P<project_code>[^/]*)(/|/index.h... |
"""Unit tests for side inputs."""
import logging
import unittest
from nose.plugins.attrib import attr
import apache_beam as beam
from apache_beam.testing.test_pipeline import TestPipeline
from apache_beam.testing.util import assert_that, equal_to
from apache_beam.transforms import window
class SideInputsTest(unitt... |
import re
from unicodedata import normalize
from datetime import date, time, datetime, timedelta
def chunk(li, n):
"""Yield succesive n-size chunks from l."""
for i in xrange(0, len(li), n):
yield li[i:i+n]
def date_and_times(meta):
date_part = None
time_part = None
if 'date' in meta:
... |
from .namespaces import DRAWNS, STYLENS, PRESENTATIONNS
from .element import Element
def StyleRefElement(stylename=None, classnames=None, **args):
qattrs = {}
if stylename is not None:
f = stylename.getAttrNS(STYLENS, 'family')
if f == 'graphic':
qattrs[(DRAWNS, u'style-name')] = s... |
"""Implements ThreadPoolExecutor."""
__author__ = 'Brian Quinlan (<EMAIL>)'
import atexit
from concurrent.futures import _base
import queue
import threading
import weakref
# Workers are created as daemon threads. This is done to allow the interpreter
# to exit when there are still idle threads in a ThreadPoolExecuto... |
#!/usr/bin/python
"""
Read a pair of fastq files and filter out reads which IDs not found in both files
"""
import sys
fq1 = open(sys.argv[1])
fq2 = open(sys.argv[2])
out1 = open(sys.argv[3], "w")
out2 = open(sys.argv[4], "w")
stack1 = dict()
stack2 = dict()
counter = 0
same = False
while True:
read1 = fq1.rea... |
'''
Copyright (c) 2014 Pivotal Software, Inc. All Rights Reserved.
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 ... |
"""Tests for nbformat validation"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
import io
import os
import nose.tools as nt
from nbformat.validator import validate, ValidationError
from ..nbjson import reads
from ..nbbase import (
nbformat,
new_code_c... |
"""
A nearly direct translation of Andrej's code
https://github.com/karpathy/char-rnn
"""
from __future__ import division
import cgt
from cgt import nn, utils, profiler
import numpy as np, numpy.random as nr
import os.path as osp
import argparse
from time import time
from StringIO import StringIO
from param_collection... |
from charsetgroupprober import CharSetGroupProber
from utf8prober import UTF8Prober
from sjisprober import SJISProber
from eucjpprober import EUCJPProber
from gb2312prober import GB2312Prober
from euckrprober import EUCKRProber
from big5prober import Big5Prober
from euctwprober import EUCTWProber
class MBCSGroupProber... |
"""build_ext tests
"""
import sys, os, shutil, tempfile, unittest, site, zipfile
from setuptools.command.upload_docs import upload_docs
from setuptools.dist import Distribution
SETUP_PY = """\
from setuptools import setup
setup(name='foo')
"""
class TestUploadDocsTest(unittest.TestCase):
def setUp(self):
... |
import unittest
from Crypto.SelfTest.loader import load_tests
from Crypto.SelfTest.st_common import list_test_cases
from Crypto.Util.py3compat import tobytes, b, unhexlify
from Crypto.Cipher import AES, DES3, DES
from Crypto.Hash import SHAKE128
def get_tag_random(tag, length):
return SHAKE128.new(data=tobytes(ta... |
import os
import pkgutil
import abc
from functools import wraps
class PluginMeta(abc.ABCMeta):
def __new__(meta, name, bases, dct):
cls = super(PluginMeta, meta).__new__(meta, name, bases, dct)
cls.handlers = []
for name, obj in cls.__dict__.iteritems():
if hasattr(obj, "__ca... |
from __future__ import with_statement
import errno
import os
import random
import select
import signal
import sys
import time
import traceback
from gunicorn.errors import HaltServer, AppImportError
from gunicorn.pidfile import Pidfile
from gunicorn.sock import create_sockets
from gunicorn import util
from gunicorn i... |
from oslo_log import log as logging
from cinder.api import common
LOG = logging.getLogger(__name__)
class ViewBuilder(common.ViewBuilder):
"""Model cgsnapshot API responses as a python dictionary."""
_collection_name = "cgsnapshots"
def __init__(self):
"""Initialize view builder."""
s... |
import warnings
from openid import message as message_module
class Extension(object):
"""An interface for OpenID extensions.
@ivar ns_uri: The namespace to which to add the arguments for this
extension
"""
ns_uri = None
ns_alias = None
def getExtensionArgs(self):
"""Get the ... |
# -*- coding: utf-8 -*-
"""
tmdbsimple.search
~~~~~~~~~~~~~~~~~
This module implements the Search functionality of tmdbsimple.
Created by Celia Oakley on 2013-10-31.
:copyright: (c) 2013-2014 by Celia Oakley
:license: GPLv3, see LICENSE for more details
"""
from .base import TMDB
class Search(TMDB):
"""
Se... |
# -*- coding: utf-8 -*-
'''
ADC, Add with Carry Test
This is an arithmetic instruction of the 6502.
'''
import unittest
from pynes.tests import MetaInstructionCase
class AdcImmTest(unittest.TestCase):
'''
Test the arithmetic operation ADC between decimal 16
and the content of the accumulator.
'''
... |
from gnuradio import gr, gr_unittest, blocks
import pmt
import numpy
def make_tag(key, value, offset, srcid=None):
tag = gr.tag_t()
tag.key = pmt.string_to_symbol(key)
tag.value = pmt.to_pmt(value)
tag.offset = offset
if srcid is not None:
tag.srcid = pmt.to_pmt(srcid)
return tag
cla... |
"""
Classes for writing XTB input files
"""
import logging
import os
from typing import Dict, Optional, Union, List
from monty.json import MSONable
from pymatgen.core import Molecule
__author__ = "Alex Epstein"
__copyright__ = "Copyright 2020, The Materials Project"
__version__ = "0.1"
__maintainer__ = "Alex Epstein"... |
"""Base classes for machine types. Do not use directly."""
import serial
import threading
from plover.exception import SerialPortException
import collections
STATE_STOPPED = 'closed'
STATE_INITIALIZING = 'initializing'
STATE_RUNNING = 'connected'
STATE_ERROR = 'disconnected'
class StenotypeBase(object):
"""The b... |
#
# Test script for the curses module
#
# This script doesn't actually display anything very coherent. but it
# does call every method and function.
#
# Functions not tested: {def,reset}_{shell,prog}_mode, getch(), getstr(),
# init_color()
# Only called, not tested: getmouse(), ungetmouse()
#
import curses, sys, tempf... |
from __future__ import absolute_import
from __future__ import division
import itertools
import sys
from signal import signal, SIGINT, default_int_handler
import time
import contextlib
import logging
from pip.compat import WINDOWS
from pip.utils import format_size
from pip.utils.logging import get_indentation
from pip... |
#!/usr/bin/env python
from __future__ import division
__author__ = "Jai Ram Rideout"
__copyright__ = "Copyright 2012, The QIIME project"
__credits__ = ["Jai Ram Rideout"]
__license__ = "GPL"
__version__ = "1.8.0-dev"
__maintainer__ = "Jai Ram Rideout"
__email__ = "<EMAIL>"
"""Contains functionality to interact with r... |
from django.db import models
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.utils.timezone import now, utc
import calendar, datetime, string, random
# Create your models here.
class Thing(models.Model):
name = models.CharField(max_length=255)
location = models.C... |
from __future__ import absolute_import, division, unicode_literals
from gettext import gettext
_ = gettext
from . import _base
from ..constants import cdataElements, rcdataElements, voidElements
from ..constants import spaceCharacters
spaceCharacters = "".join(spaceCharacters)
class LintError(Exception):
pass
... |
from __future__ import unicode_literals
import sys
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from wstore.models import Context
from wstore.store_commons.utils.url import is_valid_url
from wstore.ordering.inventory_client import InventoryClient
from wstore.rss_adaptor.rs... |
"""Support for functionality to have conversations with Home Assistant."""
import logging
import re
import voluptuous as vol
from homeassistant import core
from homeassistant.components import http
from homeassistant.components.cover import (
INTENT_CLOSE_COVER, INTENT_OPEN_COVER)
from homeassistant.components.ht... |
class ModuleDocFragment(object):
# Docker doc fragment
DOCUMENTATION = r'''
options:
docker_host:
description:
- The URL or Unix socket path used to connect to the Docker API. To connect to a remote host, provide the
TCP connection string. For example, C(tcp://192.0.2.23:... |
from __future__ import unicode_literals
import frappe
from frappe import _, throw
from frappe.utils import flt, cint, add_days, cstr
import json
from erpnext.accounts.doctype.pricing_rule.pricing_rule import get_pricing_rule_for_item
from erpnext.setup.utils import get_exchange_rate
from frappe.model.meta import get_fi... |
data = (
'', # 0x00
'', # 0x01
'', # 0x02
'', # 0x03
'', # 0x04
'', # 0x05
'', # 0x06
'', # 0x07
'', # 0x08
'', # 0x09
'', # 0x0a
'', # 0x0b
'', # 0x0c
'', # 0x0d
'', # 0x0e
'', # 0x0f
'', # 0x10
'', # 0x11
'', # 0x12
'', # 0x13
'[?]', # 0x14
'[?]', # 0x... |
import struct
from pymod.constants import *
from pymod.module import *
from pymod.tables import *
from pymod.util import *
MOD_TYPES = (
('M.K.', 'Amiga-NewTracker', 4),
('M!K!', 'Amiga-ProTracker', 4),
('M&K!', 'Amiga-NoiseTracker', 4),
('N.T.', 'Amiga-NoiseTracker?', 4), # ???, mentioned in libMod... |
#!/usr/bin/env python
from __future__ import print_function
import gtk
from os import path
if gtk.pygtk_version < (2, 3, 90):
print("Please upgrade your pygtk")
raise SystemExit
def filechooser(pathname):
dialog = gtk.FileChooserDialog("Open ...", None,
gtk.FILE_CHOO... |
"""
I define support for hookable instance methods.
These are methods which you can register pre-call and post-call external
functions to augment their functionality. People familiar with more esoteric
languages may think of these as \"method combinations\".
This could be used to add optional preconditions, user-ext... |
class TransformerMixin(object):
"""Mixin class for all transformers in scikit-learn"""
def fit_transform(self, X, y=None, **fit_params):
"""Fit to data, then transform it
Fits transformer to X and y with optional parameters fit_params
and returns a transformed version of X.
Pa... |
"""
Lighting Controls
~~~~~~~~~~~~~~~~~
Control aspects of the rendered mesh's lighting such as Ambient, Diffuse,
and Specular. These options only work if the ``lighting`` argument to
``add_mesh`` is ``True`` (it's true by default).
You can turn off all lighting by passing ``lighting=False`` to ``add_mesh``.
"""
# sp... |
from selenium.common.exceptions import NoSuchElementException
from results_page import ResultsPage
from page_loader import require_loaded
class GoogleOneBox(object):
"""This class models a page that has a google search bar."""
def __init__(self, driver, url):
self._driver = driver
self._url... |
import urllib
import re
import generic
from sickbeard import logger
from sickbeard import tvcache
class BinSearchProvider(generic.NZBProvider):
def __init__(self):
generic.NZBProvider.__init__(self, "BinSearch")
self.enabled = False
self.public = True
self.cache = BinSearchCache(... |
"""Tests and benchmarks for interacting with the `tf.Session`."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
import numpy as np
from tensorflow.python.client import session
from tensorflow.python.framework import dtypes
from tensorflow.py... |
from __future__ import print_function
from LogAnalyzer import Test,TestResult
import DataflashLog
# import scipy
# import pylab #### TEMP!!! only for dev
# from scipy import signal
class TestDualGyroDrift(Test):
'''test for gyro drift between dual IMU data'''
def __init__(self):
Test.__init__(self)
self.n... |
from setuptools import setup, find_packages
setup(
name='django-postman',
version=__import__('postman').__version__,
description='User-to-User messaging system for Django, with gateway to AnonymousUser,' \
' moderation and thread management, user & exchange filters, inbox/sent/archives/trash folder... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
import re
from ansible.module_utils.basic import AnsibleModule
class Icinga2FeatureHelper:
def __init__(self, m... |
"""Faux ``threading`` version using ``dummy_thread`` instead of ``thread``.
The module ``_dummy_threading`` is added to ``sys.modules`` in order
to not have ``threading`` considered imported. Had ``threading`` been
directly imported it would have made all subsequent imports succeed
regardless of whether ``thread`` wa... |
from datetime import datetime
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import metrics
from webapp import config
def weighted_f1(scores):
f1_0 = scores["f1"][0] * scores["support"][0]
f1_1 = scores["f1"][1] * scores["support"][1]
return (f1_0 + f1_1) / (scores[... |
from collections import defaultdict
from openerp.tools import mute_logger
from openerp.tests import common
UID = common.ADMIN_USER_ID
DB = common.DB
class TestORM(common.TransactionCase):
""" test special behaviors of ORM CRUD functions
TODO: use real Exceptions types instead of Exception """
d... |
import logging
import os
import unittest
from telemetry import test
from telemetry.core import bitmap
from telemetry.core import util
from telemetry.core.platform import android_platform_backend
from telemetry.unittest import system_stub
class MockAdbCommands(object):
def __init__(self, mock_content, system_proper... |
"""
Summarizes the output of an online learning experiment.
"""
try:
from include import *
except:
pass
import argparse
import gzip
import yaml
from numpy import cumsum, mean, std, zeros
# parse arguments
parser = argparse.ArgumentParser(
prog="python summarize-learning-experiment.py",
description="S... |
# -*- coding: utf-8 -*-
# This is a hack of the builtin todo extension, to make the todo_list
# more user friendly.
from sphinx.ext.todo import *
import re
def _(s):
return s
def process_todo_nodes(app, doctree, fromdocname):
if not app.config['todo_include_todos']:
for node in doctree.traverse(tod... |
"""
"""
import TestGyp
test = TestGyp.TestGyp()
test.run_gyp('build/all.gyp', chdir='src')
test.build('build/all.gyp', test.ALL, chdir='src')
chdir = 'src/build'
# The top-level Makefile is in the directory where gyp was run.
# TODO(mmoss) Should the Makefile go in the directory of the passed in .gyp
# file? What... |
from __future__ import unicode_literals
import frappe, erpnext
from frappe.model.document import Document
from frappe.model.mapper import get_mapped_doc
from frappe.utils import money_in_words
from frappe.utils import cint, flt, cstr
from frappe.utils.background_jobs import enqueue
from frappe import _
class FeeSched... |
"""
>>> from pyspark.conf import SparkConf
>>> from pyspark.context import SparkContext
>>> conf = SparkConf()
>>> conf.setMaster("local").setAppName("My app")
<pyspark.conf.SparkConf object at ...>
>>> conf.get("spark.master")
u'local'
>>> conf.get("spark.app.name")
u'My app'
>>> sc = SparkContext(conf=conf)
>>> sc.ma... |
"""Recursive feature elimination for feature ranking"""
import warnings
import numpy as np
from ..utils import check_X_y, safe_sqr
from ..utils.metaestimators import if_delegate_has_method
from ..base import BaseEstimator
from ..base import MetaEstimatorMixin
from ..base import clone
from ..base import is_classifier
f... |
from django.db import models
from guardian.conf import settings
from guardian.exceptions import WrongAppError
from guardian.core import ObjectPermissionChecker
from guardian.models import User
class ObjectPermissionBackend(object):
supports_object_permissions = True
supports_anonymous_user = True
supports... |
from rx import Observable
from rx.internal import extensionmethod
@extensionmethod(Observable)
def group_by(self, key_selector, element_selector=None,
key_serializer=None):
"""Groups the elements of an observable sequence according to a
specified key selector function and comparer and selects the... |
import json
import os
import time
import uuid
from google.appengine.api import urlfetch
from models import Profile
def getUserId(user, id_type="email"):
if id_type == "email":
return user.email()
if id_type == "oauth":
"""A workaround implementation for getting userid."""
auth = os.ge... |
import unittest2 as unittest
from webkitpy.layout_tests.reftests import extract_reference_link
class ExtractLinkMatchTest(unittest.TestCase):
def test_getExtractMatch(self):
html_1 = """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xm... |
"""Test debug logging."""
import os
from test_framework.test_framework import BitcoinTestFramework
class LoggingTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 1
self.setup_clean_chain = True
def run_test(self):
# test default log file name
assert os.p... |
import uuid
from msrest.pipeline import ClientRawResponse
from msrestazure.azure_exceptions import CloudError
from .. import models
class LoadBalancerBackendAddressPoolsOperations(object):
"""LoadBalancerBackendAddressPoolsOperations operations.
:param client: Client for service requests.
:param config:... |
import account_coda_import
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
import unittest
from warnings import catch_warnings
from unittest.test.testmock.support import is_instance
from unittest.mock import MagicMock, Mock, patch, sentinel, mock_open, call
something = sentinel.Something
something_else = sentinel.SomethingElse
class WithTest(unittest.TestCase):
def test_with_sta... |
def sample_cubic(x):
return x**3 - 2*x - 1
def Dsample_cubic(x):
return 3*x**2 - 2
def sign(x):
if x<0:
return -1
else:
return 1
def bisection(f,a,b,fa,fb):
"""given a function, f, and an interval [a,b] in which f changes sign
return a new interval [x,y] in which f changes si... |
import io
import os
import re
import operator
import sys
import base64
import time
from IOST_Prepare import IOST_Prepare
from IOST_Config import *
import gtk
import gtk.glade
class IOST_AboutDialog():
def __init__(self, glade_filename, window_name, object_name ,main_builder):
"This is a function get of ... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core
from caffe2.python.modeling import initializers
from caffe2.python.modeling.parameter_info import ParameterTags
def _ConvBase(
model,
... |
from django.core.management.base import BaseCommand, CommandError
from optparse import make_option
import os
import sys
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--noreload', action='store_false', dest='use_reloader', default=True,
help='Tells Django to ... |
"""Model ops python wrappers."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.boosted_trees.python.ops import gen_model_ops
from tensorflow.contrib.boosted_trees.python.ops.gen_model_ops import tree_ensemble_deserialize
from tensor... |
import pandas as pd
from bokeh.layouts import row, widgetbox
from bokeh.models import Select
from bokeh.palettes import Spectral5
from bokeh.plotting import curdoc, figure
from bokeh.sampledata.autompg import autompg_clean as df
df = df.copy()
SIZES = list(range(6, 22, 3))
COLORS = Spectral5
N_SIZES = len(SIZES)
N_C... |
"""Archives a set of files to a server."""
import binascii
import cStringIO
import hashlib
import itertools
import logging
import optparse
import os
import sys
import time
import urllib
import zlib
import run_isolated
import run_test_cases
# The minimum size of files to upload directly to the blobstore.
MIN_SIZE_FO... |
import json
from django.test import TestCase
from django.core.urlresolvers import reverse
from apiv1.tests import data
class ResourcesV1Tests(TestCase):
base_kwargs = {'api_name': 'v1'}
def setUp(self):
data.load()
def test_01_category(self):
kwargs = {'resource_name': 'category'}
... |
"""
This module holds the actual pattern implementations.
End users should not normally have to deal with it, except for constructing
patterns programatically without making use of the pattern syntax parser.
"""
import re
try:
# python 2.x base string
_basestring = basestring
except NameError:
# python ... |
# -*- coding: utf-8 -*-
from openerp import fields, models, api, _
from openerp.exceptions import Warning
from openerp import tools
class prices_update_wizard(models.TransientModel):
_name = 'product.prices_update_wizard'
price_type = fields.Selection(
[('list_price', 'Sale Price'), ('standard_price'... |
import gobject
from gettext import gettext as _
import dbus
import dbus.service
import dbus.mainloop.glib
from dbus.exceptions import DBusException
import logging
import struct
import sys
import os
from optparse import OptionParser
from peephole.peepholed import PEEPHOLE_WELL_KNOWN_NAME
from peephole.dbus_settings imp... |
import numpy as np
import datetime as dt
from os import listdir, path
def gather_mats(
split_mat, avg_5_mat, avg_25_mat, avg_50_mat, dates_mat, min_year
):
"""
Collects chosen columns from split and avg matrices and adds dates_mat
indicator data for each row (each day).
:param split_mat: origi... |
import weakref
from django.dispatch import saferef
WEAKREF_TYPES = (weakref.ReferenceType, saferef.BoundMethodWeakref)
def _make_id(target):
if hasattr(target, 'im_func'):
return (id(target.im_self), id(target.im_func))
return id(target)
class Signal(object):
"""
Base class for all signals
... |
import unittest
import datamuse
from datamuse import Datamuse
class DatamuseTestCase(unittest.TestCase):
def setUp(self):
self.api = Datamuse()
self.max = 5
# words endpoint
def test_sounds_like(self):
args = {'sl': 'orange', 'max': self.max}
data = self.api.words(**args)
... |
data = (
'pyuk', # 0x00
'pyut', # 0x01
'pyup', # 0x02
'pyuh', # 0x03
'peu', # 0x04
'peug', # 0x05
'peugg', # 0x06
'peugs', # 0x07
'peun', # 0x08
'peunj', # 0x09
'peunh', # 0x0a
'peud', # 0x0b
'peul', # 0x0c
'peulg', # 0x0d
'peulm', # 0x0e
'peulb', # 0x0f
'peuls', # 0x1... |
# -*- coding: utf-8 -*-
"""
Client HTTPS Setup
~~~~~~~~~~~~~~~~~~
This example code fragment demonstrates how to set up a HTTP/2 client that
negotiates HTTP/2 using NPN and ALPN. For the sake of maximum explanatory value
this code uses the synchronous, low-level sockets API: however, if you're not
using sockets direct... |
from __future__ import print_function, division
from sympy import Basic, Symbol, symbols, lambdify
from util import interpolate, rinterpolate, create_bounds, update_bounds
from sympy.core.compatibility import range
class ColorGradient(object):
colors = [0.4, 0.4, 0.4], [0.9, 0.9, 0.9]
intervals = 0.0, 1.0
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.