content stringlengths 4 20k |
|---|
from __future__ import division
from collections import defaultdict
from functools import partial
import numpy as np
from sklearn.externals.six.moves import zip
from sklearn.utils.testing import assert_equal
from sklearn.utils.testing import assert_array_equal
from sklearn.utils.testing import assert_almost_equal
fr... |
"""
Implementation of the SOCKSv4 protocol.
"""
# python imports
import struct
import string
import socket
import time
# twisted imports
from twisted.internet import reactor, protocol, defer
from twisted.python import log
class SOCKSv4Outgoing(protocol.Protocol):
def __init__(self,socks):
self.socks=so... |
#! /usr/bin/env python
# This file contains a class and a main program that perform three
# related (though complimentary) formatting operations on Python
# programs. When called as "pindent -c", it takes a valid Python
# program as input and outputs a version augmented with block-closing
# comments. When called as ... |
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
# TODO: Disabled the RETURN as it was breaking docs building. Someone needs to
# fix this
try:
import boto.ec2
from boto.exception import BotoServerError
HAS_BOTO = True
except ... |
import odf.opendocument
from odf.table import Table, TableRow, TableCell
from odf.text import P
# http://stackoverflow.com/a/4544699/1846474
class GrowingList(list):
def __setitem__(self, index, value):
if index >= len(self):
self.extend([None]*(index + 1 - len(self)))
list.__setitem__(... |
from argparse import ArgumentParser
from typing import Any, List
from django.contrib.auth.tokens import default_token_generator
from zerver.forms import generate_password_reset_url
from zerver.lib.management import CommandError, ZulipBaseCommand
from zerver.lib.send_email import FromAddress, send_email
from zerver.mo... |
"""Tests for tf.contrib.tensor_forest.ops.finished_nodes_op."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow # pylint: disable=unused-import
from tensorflow.contrib.tensor_forest.python.ops import tensor_forest_ops
from tensorflow.pyt... |
# coding: utf-8
from __future__ import unicode_literals
import random
import re
from .common import InfoExtractor
from ..compat import compat_urllib_parse_unquote_plus
from ..utils import (
int_or_none,
float_or_none,
timeconvert,
update_url_query,
xpath_text,
)
class KUSIIE(InfoExtractor):
... |
"""Authorizes hosts on a specific block volume."""
# :license: MIT, see LICENSE for more details.
import click
import SoftLayer
from SoftLayer.CLI import environment
from SoftLayer.CLI import exceptions
@click.command()
@click.argument('volume_id')
@click.option('--hardware-id', '-h', multiple=True,
he... |
# -*- coding: utf-8 -*-
"""
flask.signals
~~~~~~~~~~~~~
Implements signals based on blinker if available, otherwise
falls silently back to a noop
:copyright: (c) 2011 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
signals_available = False
try:
from blinker import Name... |
from __future__ import (absolute_import, division, print_function)
import math
import warnings
from nose.tools import assert_equal
import numpy as np
import matplotlib.pyplot as plt
import six
import cartopy.crs as ccrs
from cartopy.tests.mpl import ImageTesting
@ImageTesting(['global_contour_wrap'])
def test_glo... |
"""Parses PLA format usig ply."""
from ply import yacc
from ply import lex
import numpy as np
_1 = 1
_0 = 2
_X = 3
_U = 0
NOT = {_0: _1, _1: _0, _X: _U, _U: _U}
class PLA:
def __init__(self):
self.pla_i = []
self.pla_o = []
pla = PLA()
tokens = [
"I",
"O",
"MV",
"ILB",
"OB",
"P",
"L",
"E"... |
from compressor.filters.base import CompilerFilter
from compressor.filters.css_default import CssAbsoluteFilter
from compressor.utils import staticfiles
class CustomCssAbsoluteFilter(CssAbsoluteFilter):
def find(self, basename):
# This is the same as the inherited implementation except for the
# r... |
import time
from openerp.osv import fields, osv
class product_product(osv.osv):
_inherit = "product.product"
def _product_margin(self, cr, uid, ids, field_names, arg, context=None):
res = {}
if context is None:
context = {}
for val in self.browse(cr, uid, ids, context=co... |
'''
This is the gr-vocoder package. This package includes the various
vocoder blocks in GNU Radio.
'''
import os
try:
from vocoder_swig import *
except ImportError:
dirname, filename = os.path.split(os.path.abspath(__file__))
__path__.append(os.path.join(dirname, "..", "..", "swig"))
from vocoder_swig ... |
"""Tests Home Assistant location helpers."""
import unittest
from homeassistant.const import ATTR_LATITUDE, ATTR_LONGITUDE
from homeassistant.core import State
from homeassistant.helpers import location
class TestHelpersLocation(unittest.TestCase):
"""Set up the tests."""
def test_has_location_with_invalid_... |
__all__ = ['ForeignKeyElementWdg']
import re
from pyasm.search import Search, SearchKey
from pyasm.web import DivWdg, WikiUtil
from pyasm.biz import Schema, Project, NamingUtil
from tactic.ui.common import SimpleTableElementWdg
class ForeignKeyElementWdg(SimpleTableElementWdg):
def init(my):
my.parents... |
#!/usr/bin/env python3
from astropy.table import Table
import argparse
import numpy as np
parser = argparse.ArgumentParser()
parser.add_argument('--spall',
type=str,
required=True,
help='Path to spAll file')
parser.add_argument('--qso-catalog',
... |
"""Test previous events page."""
from happening.tests import TestCase
from model_mommy import mommy
from datetime import datetime, timedelta
import pytz
class TestEvents(TestCase):
"""Test previous events page."""
def test_previous_events(self):
"""Test that previous events are listed correctly."""... |
import unittest
from unittest import mock
from airflow.providers.google.cloud.operators.translate import CloudTranslateTextOperator
GCP_CONN_ID = 'google_cloud_default'
IMPERSONATION_CHAIN = ["ACCOUNT_1", "ACCOUNT_2", "ACCOUNT_3"]
class TestCloudTranslate(unittest.TestCase):
@mock.patch('airflow.providers.googl... |
'''
@author: yyk
'''
class IpAddress(object):
'''
Help to save and compare IP Address.
'''
def __init__(self, ip):
self.ip_list = ip.split('.', 3)
self.ips = []
for item in self.ip_list:
if not item.isdigit():
raise Exception('%s is no... |
import math
from functools import partial
from nose.tools import *
import networkx as nx
def _test_func(G, ebunch, expected, predict_func, **kwargs):
result = predict_func(G, ebunch, **kwargs)
exp_dict = dict((tuple(sorted([u, v])), score) for u, v, score in expected)
res_dict = dict((tuple(sorted([u, v... |
#! /usr/bin/env python
# encoding: utf-8
import os,shlex,sys,time
try:import cPickle
except ImportError:import pickle as cPickle
import Environment,Utils,Options,Logs
from Logs import warn
from Constants import*
try:
from urllib import request
except:
from urllib import urlopen
else:
urlopen=request.urlopen
conf_te... |
import unittest
from datetime import date as original_date, datetime as original_datetime
from django.utils.datetime_safe import date, datetime
class DatetimeTests(unittest.TestCase):
def setUp(self):
self.just_safe = (1900, 1, 1)
self.just_unsafe = (1899, 12, 31, 23, 59, 59)
self.really_... |
"""A module for the sync command."""
import os.path
import cr
class SyncCommand(cr.Command):
"""The implementation of the sync command.
This command is a very thin shim over the gclient sync, and should remain so.
The only significant thing it adds is that the environment is set up so that
the run-hooks wi... |
"""
Automated tests for checking transformation algorithms (the models package).
"""
import logging
import unittest
import os
import os.path
import tempfile
import six
import numpy
import scipy.linalg
from gensim.corpora import mmcorpus, Dictionary
from gensim.models import tfidfmodel
from gensim import matutils
m... |
import json
import os
import logging
from collections import OrderedDict
from Bitbucket import BitbucketVCSProvider
from service_buddy.service.loader import walk_service_map, safe_mkdir, ensure_app_directory_exists, \
ensure_service_directory_exists
from service_buddy.service.service import Service
from service_b... |
import unittest
import six
from airflow import AirflowException
from airflow.contrib.operators.gcs_to_gdrive_operator import GcsToGDriveOperator
from tests.compat import mock
MODULE = "airflow.contrib.operators.gcs_to_gdrive_operator"
class TestGcsToGDriveOperator(unittest.TestCase):
@mock.patch(MODULE + ".Go... |
'''
>>> from enum_ext import *
>>> identity(color.red) # in case of duplicated enums it always take the last enum
enum_ext.color.blood
>>> identity(color.green)
enum_ext.color.green
>>> identity(color.blue)
enum_ext.color.blue
>>> identity(color(1)) # in case of duplicated enums it always take the last ... |
# uncompyle6 version 2.9.10
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10)
# [GCC 6.2.0 20161005]
# Embedded file name: __init__.py
import dsz
import dsz.version.checks
import dsz.version.checks.windows
import dsz.version.checks.unix
def _getenvvalue(name, addr):
... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
r_mask_vect.py
--------------
Date : February 2016
Copyright : (C) 2016 by Médéric Ribreux
Email : medspx at medspx dot fr
******************************... |
from twisted.trial import unittest
from twisted.conch.insults import helper, text
A = text.attributes
class Serialization(unittest.TestCase):
def setUp(self):
self.attrs = helper.CharacterAttribute()
def testTrivial(self):
self.assertEqual(
text.flatten(A.normal['Hello, world.'],... |
# This is a sample ISAPI extension written in Python.
# This is like the other 'redirector' samples, but uses asnch IO when writing
# back to the client (it does *not* use asynch io talking to the remote
# server!)
from isapi import isapicon, threaded_extension
import sys
import traceback
import urllib
# sys.isapidl... |
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = 'KMOL'
SITENAME = '2017 協同產品設計實習 設計二甲 張勝雄'
# 不要用文章所在目錄作為類別
USE_FOLDER_AS_CATEGORY = False
#PATH = 'content'
#OUTPUT_PATH = 'output'
TIMEZONE = 'Asia/Taipei'
DEFAULT_LANG = 'en'
# Feed generation is usually not desired... |
from __future__ import unicode_literals
import frappe
from frappe import _, scrub
from frappe.utils import flt
def execute(filters=None):
if not filters: filters = {}
gross_profit_data = GrossProfitGenerator(filters)
data = []
source = gross_profit_data.grouped_data if filters.get("group_by") != "Invoice" else gr... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
try:
from botocore.exceptions import ClientError, BotoCoreError
except ImportError:
... |
"""Implementation of Gaussian mixture model (GMM) clustering.
This goes on top of skflow API.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
import numpy as np
from tensorflow.contrib import framework
from tensorflow.contrib.factorizatio... |
from __future__ import unicode_literals
import frappe
from frappe.utils import cstr, add_days, date_diff
from frappe import _
from frappe.utils.csvutils import UnicodeWriter
from frappe.model.document import Document
class UploadAttendance(Document):
pass
@frappe.whitelist()
def get_template():
if not frappe.has_pe... |
""" Objects and functions related to generating CSV reports """
from decimal import Decimal
import unicodecsv
from django.utils.translation import ugettext as _
from six import text_type
from course_modes.models import CourseMode
from courseware.courses import get_course_by_id
from shoppingcart.models import Certifi... |
from __future__ import print_function
import argparse
import os
import re
import struct
import sys
import hashlib
import binascii
import gen_esp32part as gen
__version__ = '1.0'
quiet = False
def status(msg):
""" Print status message to stderr """
if not quiet:
critical(msg)
def critical(msg):
"... |
import unittest2
from google.appengine.ext import ndb
from google.appengine.ext import testbed
from helpers.match_helper import MatchHelper
from datafeeds.offseason_matches_parser import OffseasonMatchesParser
from models.event import Event
from models.match import Match
class TestMatchCleanup(unittest2.TestCase):
... |
""" run test suites written for nose. """
import sys
import py
import pytest
from _pytest import unittest
def get_skip_exceptions():
skip_classes = set()
for module_name in ('unittest', 'unittest2', 'nose'):
mod = sys.modules.get(module_name)
if hasattr(mod, 'SkipTest'):
skip_cla... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import sys
import six
import astroid
from pylint.interfaces import IAstroidChecker
from pylint.checkers import BaseChecker
from pylint.checkers import utils
from pylint.checkers.utils import check_messages
from pylint.checkers.st... |
import os
import sys
import cocotb
import logging
from cocotb.result import TestFailure
from cocotb.clock import Clock
import time
from array import array as Array
from cocotb.triggers import Timer, FallingEdge, ReadWrite, NextTimeStep
from block_fifo_driver import BlockFIFOWritePath
from block_fifo_driver import Bloc... |
import os
vars = {
'ptr_lib_version': '1.0.11',
'ptr_lib_stable_version': '1.0.11',
'cube_sdk_version': '1.0.44.39-SNAPSHOT'
}
files = [
'README.md',
'README-cn.md',
'ptr-lib/pom.xml',
'ptr-lib/gradle.properties',
'ptr-demo/pom.xml',
'ptr-... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import pytest
import sys
if sys.version_info < (2, 7):
pytestmark = pytest.mark.skip("F5 Ansible modules require Python >= 2.7")
from ansible.module_utils.basic import AnsibleModule
try:
from librar... |
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import forms
from horizon import messages
from openstack_dashboard import api
import logging
LOG = logging.getLogger(__name__)
class DeleteForm(forms.SelfHandlingForm):
... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['stableinterface'],
'supported_by': 'curated'}
try:
import boto
import boto.ec2
import boto.vpc
from boto.exception import BotoServerError
HAS_BOTO=True
except ImportError:
HAS_BOTO=False
def bot... |
#!/usr/bin/env python
# coding: utf8
from __future__ import print_function
from collections import defaultdict
from datetime import datetime
import argparse
import base64
import eviltransform
import json
import logging
import os
import pickle
import time
import urllib2
# Initialize logging.
logging.basicConfig(level=... |
from __future__ import absolute_import
from rest_framework import serializers
from sentry.testutils import TestCase
from sentry.api.serializers.rest_framework import ListField, ActorField
from sentry.models import User, Team
class ChildSerializer(serializers.Serializer):
b_field = serializers.CharField(max_len... |
from nova import db
from nova import exception
from nova import objects
from nova.objects import base as obj_base
from nova.objects import fields
FLOATING_IP_OPTIONAL_ATTRS = ['fixed_ip']
# TODO(berrange): Remove NovaObjectDictCompat
@obj_base.NovaObjectRegistry.register
class FloatingIP(obj_base.NovaPersistentObjec... |
"""Tests for basic_specs."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.compat.v1 as tf
from tunas import basic_specs
class BasicSpecsTest(tf.test.TestCase):
def test_filter_multiplier_ordering(self):
# Verify that instances... |
"""Support for IOTA wallets."""
from datetime import timedelta
from iota import Iota
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.discovery import load_platform
from homeassistant.helpers.entity import Entity
CONF_IRI = "iri"
CONF_TESTNET = "testnet"
CONF_W... |
import json
import collections
# COMMON CODE FOR MIGRATION
import re
from ansible.module_utils.basic import get_exception
from ansible.module_utils.netcfg import NetworkConfig, ConfigLine
from ansible.module_utils.shell import ShellError
try:
from ansible.module_utils.nxos import get_module
except ImportError:
... |
import utils as cu
import libDetection as det
from dataProcessor import processData
import svmClassifier as svm
import latentSVM as lsvm
class Detector():
def __init__(self,models,threshold,maxOverlap):
self.models = models
self.threshold = threshold
self.maxOverlap = maxOverlap
def run(self,img,f... |
# -*- coding: utf-8 -*-
from fabric import api as fabric_api
from fabric.state import env
import os
from solar.core.log import log
from solar.core.handlers.base import TempFileHandler
from solar import errors
# otherwise fabric will sys.exit(1) in case of errors
env.warn_only = True
# if we would have something lik... |
from bibliopixel.animation.matrix import Matrix
from bibliopixel.util import log
from . system_eq import EQ
class BaseSpectrumDraw:
def __init__(self, anim):
self.anim = anim
self.width = anim.width
self.height = anim.height
self.led = anim._led
self.height_map... |
import ConfigParser
import os
import string
from nova.rootwrap import filters
def build_filter(class_name, *args):
"""Returns a filter object of class class_name"""
if not hasattr(filters, class_name):
# TODO(ttx): Log the error (whenever nova-rootwrap has a log file)
return None
filtercl... |
import sys
from solution import Solution
from Interval import Interval
class TestSuite:
def run(self):
self.test000()
self.test001()
self.test002()
self.test003()
# self.test004()
def test000(self):
print 'test 000\n'
... |
from django.test import TestCase
from regressiontests.null_fk.models import *
class NullFkTests(TestCase):
def test_null_fk(self):
d = SystemDetails.objects.create(details='First details')
s = SystemInfo.objects.create(system_name='First forum', system_details=d)
f = Forum.objects.create(... |
# -*- coding: utf8 -*-
import sys, os
sys.path.append(os.path.abspath('.'))
import re
from operator import attrgetter
import difflib
# Pylons model init sequence
import pylons.test
import logging
from quanthistling.config.environment import load_environment
from quanthistling.model.meta import Sessi... |
import re
import tagging.utils
from django import template
from django.contrib.contenttypes.models import ContentType
from django.contrib.comments.models import Comment
from tagging.models import Tag
from post.models import BasicPost, EditorChoice, PostWithImage, PostWithSimpleImage, PostWithSlideshow, PostWithEmbedd... |
# -*- coding: utf-8 -*-
import furl
import json
import urllib
import requests
import httplib as http
from lxml import etree
from website import settings
from framework.auth import User
from framework.auth import authenticate
from framework.flask import redirect
from framework.exceptions import HTTPError
class CasEr... |
# coding: utf-8
"""
3.2 Пользователь может размещать корзины в юнитах
"""
from django.test import TestCase
from django.core.urlresolvers import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from ..models import Basket, BasketSlot, Server, ServerTemplate, Rack
from ..exceptions im... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'network'}
import re
from ansible.module_utils.nxos import get_config, load_config
from ansible.module_utils.nxos import nxos_argument_spec, check_args
from ansible.module_utils.basic import ... |
"""
Course Structure api.py tests
"""
from .api import course_structure
from openedx.core.djangoapps.content.course_structures.signals import listen_for_course_publish
from xmodule.modulestore.django import SignalHandler
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tes... |
"""
Server Configuration flags
This holds persistent server configuration flags.
Config values should usually be set through the
manager's conf() method.
"""
from builtins import object
try:
import cPickle as pickle
except ImportError:
import pickle
from django.db import models
from evennia.utils.idmapper... |
import simplejson
import cgi
class JSONFilter(object):
def __init__(self, app, mime_type='text/x-json'):
self.app = app
self.mime_type = mime_type
def __call__(self, environ, start_response):
# Read JSON POST input to jsonfilter.json if matching mime type
response = {'status': ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
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... |
"""Test cases for traceback module"""
from _testcapi import traceback_print, exception_print
from io import StringIO
import sys
import unittest
import re
from test.support import run_unittest, Error, captured_output
from test.support import TESTFN, unlink
import traceback
class SyntaxTracebackCases(unittest.TestCas... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# pylint: disable=C0103,W0621
"""
Word-context embeddings product model needed for skip-gram training.
"""
__author__ = "GW [http://gw.tnode.com/] <<EMAIL>>"
__license__ = "GPLv3+"
from myhdl import Signal, ConcatSignal, intbv, fixbv, delay, always, always_comb, instance, ... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from collections import defaultdict
import platform
from ansible.module_utils.facts import timeout
class BaseFactCollector:
_fact_ids = set()
_platform = 'Generic'
name = None
def __init__(self, collectors=Non... |
from __future__ import absolute_import, division, print_function, \
with_statement
import os
import json
import sys
import getopt
import logging
from shadowsocks.common import to_bytes, to_str, IPNetwork
from shadowsocks import encrypt
VERBOSE_LEVEL = 5
verbose = 0
def check_python():
info = sys.version_i... |
"""
homeassistant.components.automation.template
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Offers template automation rules.
For more details about this automation rule, please refer to the documentation
at https://home-assistant.io/components/automation/#template-trigger
"""
import logging
from homeassistant... |
{
'name': 'SendGrid',
'version': '8.0.2',
'category': 'Other',
'author': 'Compassion CH',
'website': 'http://www.compassion.ch',
'depends': ['base', 'email_template'],
'data': [
'security/ir.model.access.csv',
'view/sendgrid_email_view.xml',
'view/sendgrid_template_vi... |
from base64 import b64encode as b64e
import unittest
from apiclient.errors import HttpError
from airflow.contrib.hooks.gcp_pubsub_hook import PubSubHook
try:
from unittest import mock
except ImportError:
try:
import mock
except ImportError:
mock = None
BASE_STRING = 'airflow.contrib.hoo... |
# graphicsCrawlerDisplay.py
# -------------------------
# Licensing Information: Please do not distribute or publish solutions to this
# project. You are free to use and extend these projects for educational
# purposes. The Pacman AI projects were developed at UC Berkeley, primarily by
# John DeNero (<EMAIL>) and Dan K... |
"""
The toolbutton module provides the ToolButton class, which is a
Gtk.ToolButton with icon and tooltip styled for Sugar.
Example:
Add a tool button to a window
from gi.repository import Gtk
from sugar3.graphics.toolbutton import ToolButton
def __clicked_cb(button):
print "to... |
# coding: utf-8
"""
pyalysis.utils
~~~~~~~~~~~~~~
:copyright: 2014 by Daniel Neuhäuser and Contributors
:license: BSD, see LICENSE.rst for details
"""
import math
import re
import codecs
import tokenize
from collections import namedtuple
from weakref import WeakKeyDictionary
from contextlib import cont... |
from slicc.symbols.Symbol import Symbol
from slicc.symbols.Type import Type
class Func(Symbol):
def __init__(self, table, ident, location, return_type, param_types,
param_strings, body, pairs):
super(Func, self).__init__(table, ident, location, pairs)
self.return_type = return_type... |
data = (
'[?]', # 0x00
'[?]', # 0x01
'[?]', # 0x02
'[?]', # 0x03
'[?]', # 0x04
'[?]', # 0x05
'[?]', # 0x06
'[?]', # 0x07
'[?]', # 0x08
'[?]', # 0x09
'[?]', # 0x0a
'[?]', # 0x0b
'[?]', # 0x0c
'[?]', # 0x0d
'[?]', # 0x0e
'[?]', # 0x0f
'[?]', # 0x10
'[?]', # 0x11
'[?]'... |
"""
Gradient Boosted Trees Regression Example.
"""
from __future__ import print_function
from pyspark import SparkContext
# $example on$
from pyspark.mllib.tree import GradientBoostedTrees, GradientBoostedTreesModel
from pyspark.mllib.util import MLUtils
# $example off$
if __name__ == "__main__":
sc = SparkContex... |
from neo.io.basefromrawio import BaseFromRaw
from neo.rawio.elanrawio import ElanRawIO
class ElanIO(ElanRawIO, BaseFromRaw):
"""
Class for reading data from Elan.
Elan is software for studying time-frequency maps of EEG data.
Elan is developed in Lyon, France, at INSERM U821
https://elan.lyon.i... |
# -*- coding: utf-8 -*-
from imp import load_module, PY_SOURCE
import os.path
from django.conf import settings
from django.template import loader, TemplateDoesNotExist
from django.test.utils import override_settings
from django.utils.encoding import force_text
from django.utils.translation import ugettext_lazy as _
f... |
from glob import glob
import os
import sys
import tempfile
import logging
import xkit.xutils
import xkit.xorgparser
import Quirks.quirkreader
import Quirks.quirkinfo
class QuirkChecker:
def __init__(self, handler, path='/usr/share/jockey/quirks'):
self._handler = handler
self.quirks_path = path
... |
"""Provide a function to report modification to broadcast settings."""
BAD_OPTIONS_FMT = "\n --%s=%s"
BAD_OPTIONS_TITLE = "ERROR: No broadcast to cancel/clear for these options:"
BAD_OPTIONS_TITLE_SET = ("ERROR: Rejected broadcast: settings are not" +
" compatible with the suite")
CHANGE_FMT... |
import asyncio
import time
import logging
import zmq
import zmq.asyncio
from collections import namedtuple
from gabriel_protocol import gabriel_pb2
from gabriel_server import cognitive_engine
from gabriel_server import network_engine
from gabriel_server.websocket_server import WebsocketServer
FIVE_SECONDS = 5
logge... |
from timeit import default_timer
from functools import wraps
from diary import Diary
import os
import shutil
TEST_DIR = os.path.join(os.path.dirname(__file__), 'performance_test_dir')
TRIAL_COUNT = 1000
def timed(timed_function):
@wraps(timed_function)
def timed_wrapper(trials=TRIAL_COUNT):
start = de... |
"""
Cache middleware. If enabled, each Django-powered page will be cached based on
URL. The canonical way to enable cache middleware is to set
``UpdateCacheMiddleware`` as your first piece of middleware, and
``FetchFromCacheMiddleware`` as the last::
MIDDLEWARE_CLASSES = [
'django.middleware.cache.UpdateCa... |
from base_section import BaseSection
from mtools.util.print_table import print_table
from mtools.util import OrderedDict
class RsStateSection(BaseSection):
""" This section determines if there were any Replica Set state changes in the log file and prints out
the times and information about the restarts fou... |
from m5.params import *
from m5.proxy import *
from Network import RubyNetwork
from BasicRouter import BasicRouter
from ClockedObject import ClockedObject
class GarnetNetwork(RubyNetwork):
type = 'GarnetNetwork'
cxx_header = "mem/ruby/network/garnet2.0/GarnetNetwork.hh"
num_rows = Param.Int(0, "number of r... |
#!/usr/bin/env python
"""
Script which takes one or more file paths and reports on their detected
encodings
Example::
% chardetect somefile someotherfile
somefile: windows-1252 with confidence 0.5
someotherfile: ascii with confidence 1.0
If no paths are provided, it takes its input from stdin.
"""
from... |
"""Test making many calls and immediately cancelling most of them."""
import threading
import unittest
from grpc._cython import cygrpc
from grpc.framework.foundation import logging_pool
from tests.unit.framework.common import test_constants
from tests.unit._cython import test_utilities
_EMPTY_FLAGS = 0
_EMPTY_METADA... |
DEFAULT_AUTH_PIPELINE = (
# Get the information we can about the user and return it in a simple
# format to create the user instance later. On some cases the details are
# already part of the auth response from the provider, but sometimes this
# could hit a provider API.
'social.pipeline.social_auth... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
GridSurfaceCreate.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
-----------------... |
"""
codetransformer.utils.immutable
-------------------------------
Utilities for creating and working with immutable objects.
"""
from collections import ChainMap
from inspect import getfullargspec
from itertools import starmap, repeat
from textwrap import dedent
from weakref import WeakKeyDictionary
class immutab... |
"""Subset of inspect module from upstream python
We use this instead of upstream because upstream inspect is slow to import, and
significanly contributes to numpy import times. Importing this copy has almost
no overhead.
"""
import types
__all__ = ['getargspec', 'formatargspec']
# ----------------------------------... |
#
# To see the output of this macro, click begin_html <a href="gif/fillrandom.gif">here</a>. end_html
#
from ROOT import TCanvas, TPad, TFormula, TF1, TPaveLabel, TH1F, TFile
from ROOT import gROOT, gBenchmark
c1 = TCanvas( 'c1', 'The FillRandom example', 200, 10, 700, 900 )
c1.SetFillColor( 18 )
pad1 = TPad( 'pad... |
import pytest
from cfme import test_requirements
@pytest.mark.manual
@test_requirements.upgrade
@pytest.mark.tier(2)
def test_upgrade_dedicated_db_migration_local():
"""
Test that you can locally migrate a dedicated database after upgrade.
Previously it was missing the database.yml during setup with woul... |
import os
import time
try:
from dopy.manager import DoError, DoManager
HAS_DOPY = True
except ImportError:
HAS_DOPY = False
class TimeoutError(DoError):
def __init__(self, msg, id):
super(TimeoutError, self).__init__(msg)
self.id = id
class JsonfyMixIn(object):
def to_json(self):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.