content stringlengths 4 20k |
|---|
""" Standard "encodings" Package
Standard Python encoding modules are stored in this package
directory.
Codec modules must have names corresponding to normalized encoding
names as defined in the normalize_encoding() function below, e.g.
'utf-8' must be implemented by the module 'utf_8.py'.
Ea... |
"""Generic retry wrapper for Git operations.
This is largely DEPRECATED in favor of the Infra Git wrapper:
https://chromium.googlesource.com/infra/infra/+/master/go/src/infra/tools/git
"""
import logging
import optparse
import os
import subprocess
import sys
import threading
import time
from git_common import GIT_E... |
data = (
'Ci ', # 0x00
'Xiang ', # 0x01
'She ', # 0x02
'Luo ', # 0x03
'Qin ', # 0x04
'Ying ', # 0x05
'Chai ', # 0x06
'Li ', # 0x07
'Ze ', # 0x08
'Xuan ', # 0x09
'Lian ', # 0x0a
'Zhu ', # 0x0b
'Ze ', # 0x0c
'Xie ', # 0x0d
'Mang ', # 0x0e
'Xie ', # 0x0f
'Qi ', # 0x10
'Ro... |
"""
===========
Convex Hull
===========
The convex hull of a binary image is the set of pixels included in the
smallest convex polygon that surround all white pixels in the input.
In this example, we show how the input pixels (white) get filled in by the
convex hull (white and grey).
A good overview of the algorithm... |
import os
from dotgit.__main__ import main
from dotgit.git import Git
class TestMain:
def setup_repo(self, tmp_path, flist):
home = tmp_path / 'home'
repo = tmp_path / 'repo'
os.makedirs(home)
os.makedirs(repo)
main(args=['init'], cwd=str(repo))
with open(repo / 'fi... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
ConfigDialog.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
**************************... |
import sys
import os
import os.path as op
import tempfile
import shutil
from subprocess import Popen
from datetime import datetime
from . import globalvars
from .base import CodeTemplate, GeneratedItem, owner, NSApp, const, defaults
from .types import Action, NLSTR
from .control import ControlSize, TextAlignment
from ... |
import ast
import numpy as np
import mxnet as mx
class BinaryRBM(mx.operator.CustomOp):
def __init__(self, k):
self.k = k # Persistent contrastive divergence k
def forward(self, is_train, req, in_data, out_data, aux):
visible_layer_data = in_data[0] # (num_batch, num_visible)
visible_... |
"""Gets preferences from Firnberg et al amino-acid "fitnesses".
Uses the reported fitnesses except:
* Fitness of wildtype at each site is always set to one.
* If no fitness is provided, uses the average fitness of all amino acids
with reported fitnesses plus wildtype at that site.
Written by Jesse Bloom, 2014."""... |
import imp
import inspect
import os.path
import sys
# Disable lint check for finding modules:
# pylint: disable=F0401
def _GetDirAbove(dirname):
"""Returns the directory "above" this file containing |dirname| (which must
also be "above" this file)."""
path = os.path.abspath(__file__)
while True:
path, tai... |
"""Tests for WALSMatrixFactorization."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import itertools
import json
import numpy as np
from tensorflow.contrib.factorization.python.ops import factorization_ops_test_utils
from tensorflow.contrib.factorizat... |
from django.conf.urls import include, url
from django.core import urlresolvers
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import Permission
from wagtail.wagtailcore import hooks
from wagtail.wagtailadmin.menu import MenuItem
from wagtail.wagtailsites import urls
@hooks.r... |
"""
Twitter fetcher
In order to schedule fetching tweets you can type at the command line:
$ sudo -u www-data /opt/invenio/bin/bibtasklet -T bst_twitter_fetcher -uadmin -s5m -a "query=YOURQUERY"
"""
## Here we import the Twitter APIs
import twitter
import re
import os
import sys
import tempfile
import time
import s... |
"""\
Management tool for the Spacewalk Proxy.
This script performs various management operations on the Spacewalk Proxy:
- Creates the local directory structure needed to store local packages
- Uploads packages from a given directory to the RHN servers
- Optionally, once the packages are uploaded, they can be linked t... |
from __future__ import absolute_import, unicode_literals
from django.db import models
from django.utils.html import format_html
from django.utils.translation import ugettext_lazy as _
from django.utils import version
from error_report.settings import ERROR_DETAIL_SETTINGS
if version.get_complete_version() < (1, 10)... |
from __future__ import print_function
import base64
import json
import os
import subprocess
import tempfile
import threading
import traceback
import uuid
from six import ensure_str
from mozprocess import ProcessHandler
from tools.serve.serve import make_hosts_file
from .base import (ConnectionlessProtocol,
... |
"""Basic XML utilities based on minidom - the built in Document Object Model
"""
import sys
from xml.dom import minidom, Node
from safe.common.utilities import verify
def print_tree(n, indent=0):
while n:
#print 'nodeType', n.nodeType, Node.ELEMENT_NODE
#if n.nodeType != Node.ELEMENT_NODE:
... |
"""
Management utility to create superusers.
"""
import getpass
import os
import re
import sys
from optparse import make_option
from django.contrib.auth.models import User
from django.core import exceptions
from django.core.management.base import BaseCommand, CommandError
from django.utils.translation import ugettext ... |
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.maxDiff = None
filename = 'comment06.xlsx'
... |
class MakeProperties(type):
def __init__(cls, name, bases, dct):
def _wrap_set(names, name):
def fun(self, value):
for field in names:
self.__dict__[field] = (name == field) and value
return fun
def _wrap_get(name):
def fun(sel... |
import os
import re
import asyncio
import functools
import logging
from ..config import config
from ..utils import remove_stop_words
log = logging.getLogger('stagehand.searchers')
class SearcherError(Exception):
pass
class SearcherBase:
# Values must be supplied by subclasses.
# The internal name of t... |
from collections import defaultdict
from nose.tools import *
from nose import SkipTest
import networkx as nx
from networkx.algorithms.centrality.communicability_alg import *
class TestCommunicability:
@classmethod
def setupClass(cls):
global numpy
global scipy
try:
import nu... |
import os
import pytest
INSIDE_VPCSC_ENVVAR = "GOOGLE_CLOUD_TESTS_IN_VPCSC"
PROJECT_INSIDE_ENVVAR = "PROJECT_ID"
PROJECT_OUTSIDE_ENVVAR = "GOOGLE_CLOUD_TESTS_VPCSC_OUTSIDE_PERIMETER_PROJECT"
BUCKET_OUTSIDE_ENVVAR = "GOOGLE_CLOUD_TESTS_VPCSC_OUTSIDE_PERIMETER_BUCKET"
class VPCSCTestConfig(object):
"""System tes... |
suite = {
"mxversion" : "5.282.0",
"name" : "fastr",
"versionConflictResolution" : "latest",
"imports" : {
"suites" : [
{
"name" : "truffle",
"subdir" : True,
# The version must be the same as the version of Sulong
# TRUFFLE REVISION (n... |
"""
Wrapper for wtsapi32.dll in ctypes.
"""
__revision__ = "$Id$"
from winappdbg.win32.defines import *
from winappdbg.win32.advapi32 import *
#==============================================================================
# This is used later on to calculate the list of exported symbols.
_all = None
_all = set(vars... |
import cv2
import os
import serial
from image_processing import mask_by_pixel_value, dark_mask, masked_merge
class BlendModes:
MASK, OVERLAY = range(2)
class FractalsDirectory(object):
"""
Keep a sequence of images and provide a method to merge the current image
into another one.
"""
def _... |
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import sys
import unittest
import SCons.Errors
import SCons.Tool
class ToolTestCase(unittest.TestCase):
def test_Tool(self):
"""Test the Tool() function"""
class Environment:
def __init__(self):
self.dict = ... |
from __future__ import print_function
import abc
import os
import numpy as np
class Output(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def output(self, config, results):
"""Return the test data: training data and labels"""
return None
class ScreenOutput(Output):
... |
"""
Check that all of the certs on all service endpoints validate.
"""
from tests.integration import ServiceCertVerificationTest
from tests.compat import unittest
import boto.ec2.elb
class ELBCertVerificationTest(unittest.TestCase, ServiceCertVerificationTest):
elb = True
regions = boto.ec2.elb.regions()
... |
import datetime
from dateutil.relativedelta import relativedelta
from django.conf import settings
from django.db.models import get_model
from django.utils import timezone
from timepiece.defaults import TimepieceDefaults
class ActiveEntryError(Exception):
"""A user should have no more than one active entry at a ... |
"""Zwave util methods."""
import asyncio
import logging
import homeassistant.util.dt as dt_util
from . import const
_LOGGER = logging.getLogger(__name__)
def check_node_schema(node, schema):
"""Check if node matches the passed node schema."""
if const.DISC_NODE_ID in schema and node.node_id not in schema[c... |
from django import forms
from django.conf.urls import url
from django.contrib import messages
from django.contrib.messages.views import SuccessMessageMixin
from django.http import HttpResponse, HttpResponseRedirect
from django.template import engines
from django.template.response import TemplateResponse
from django.url... |
# This program is public domain
"""
Format values and uncertainties nicely for printing.
:func:`format_uncertainty_pm` produces the expanded format v +/- err.
:func:`format_uncertainty_compact` produces the compact format v(##),
where the number in parenthesis is the uncertainty in the last two digits of v.
:func:`f... |
import os
import subprocess
from bzrlib.plugin import load_plugins
from bzrlib.branch import Branch
from git import Git
def autodetect_vcs(url):
if 'bitbucket' in url:
return 'hg'
if 'launchpad' in url:
return 'bzr'
if 'github' in url:
return 'git'
def clone_git_repo(url, local_... |
"""Model code for `IHasTranslationImports."""
__metaclass__ = type
__all__ = [
'HasTranslationImportsMixin',
]
from zope.component import getUtility
from lp.translations.interfaces.translationimportqueue import (
ITranslationImportQueue,
)
class HasTranslationImportsMixin:
"""Helper class for i... |
import re
from telemetry.page import page as page_module
from telemetry.page import page_set as page_set_module
def _CreateXpathFunction(xpath):
return ('document.evaluate("%s",'
'document,'
'null,'
'XPathResult.FIRST_ORDERED_NO... |
import sale_analytic_plans
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
#!/usr/bin/env python
# Standard packages
import os
import sys
import argparse
# Third-party packages
from toil.job import Job
# Package methods
from ddb import configuration
from ddb_ngsflow import pipeline
from ddb_ngsflow.rna import hisat
from ddb_ngsflow.rna import stringtie
if __name__ == "__main__":
pars... |
"""
Customized Mixin2to3 support:
- adds support for converting doctests
This module raises an ImportError on Python 2.
"""
from distutils.util import Mixin2to3 as _Mixin2to3
from distutils import log
from lib2to3.refactor import RefactoringTool, get_fixers_from_package
import setuptools
class DistutilsRefactor... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('twitterclone', '0010_auto_20150331_1958')... |
import os
import sys
import re
import tarfile
import tempfile
import unittest
from sdktools_test import SdkToolsTestCase
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
BUILD_TOOLS_DIR = os.path.dirname(SCRIPT_DIR)
TOOLS_DIR = os.path.join(os.path.dirname(BUILD_TOOLS_DIR), 'tools')
sys.path.extend([BUILD_TOOL... |
from sqlalchemy import MetaData, Table, Enum, Column, Integer
from migrate.changeset.constraint import UniqueConstraint
meta = MetaData()
ACTIONS = ['CREATE', 'DELETE', 'UPDATE', 'NONE']
def upgrade(migrate_engine):
meta.bind = migrate_engine
RESOURCE_STATUSES = ['ACTIVE', 'PENDING', 'DELETED', 'ERROR']
... |
import unittest
import pysal
import numpy as np
import random
class Test_Maxp(unittest.TestCase):
def setUp(self):
random.seed(100)
np.random.seed(100)
def test_Maxp(self):
w = pysal.lat2W(10, 10)
z = np.random.random_sample((w.n, 2))
p = np.ones((w.n, 1), float)
... |
from robot.libraries.BuiltIn import BuiltIn
# from selenium.webdriver.common.action_chains import ActionChains
class _FlashControllerKeywords:
''' The Locator:
`name:testText*rea/name:U*TextField*`
`window.document.getElementById('loginApp').fp_type({name:'password_field', text:'mode'});`
'''
def _... |
"""
Base classes for the Key Manager tests.
"""
import distutils.spawn
import os.path
from twisted.internet.defer import gatherResults
from twisted.trial import unittest
from leap.common.testing.basetest import BaseLeapTest
from leap.bitmask.keymanager import KeyManager
from leap.soledad.client import Soledad
PATH =... |
from transitions import Transition
from transitions.extensions.markup import MarkupMachine
from transitions.core import listify
import logging
from functools import partial
import copy
_LOGGER = logging.getLogger(__name__)
_LOGGER.addHandler(logging.NullHandler())
# this is a workaround for dill issues when partials... |
# coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import (
ExtractorError,
remove_end,
)
from .rudo import RudoIE
class BioBioChileTVIE(InfoExtractor):
_VALID_URL = r'https?://(?:tv|www)\.biobiochile\.cl/(?:notas|noticias)/(?:[^/]+/)+(?P<id>[^/]+)\.sht... |
from django.core.management.base import BaseCommand
def module_to_dict(module, omittable=lambda k: k.startswith('_')):
"""Convert a module namespace to a Python dictionary."""
return {k: repr(v) for k, v in module.__dict__.items() if not omittable(k)}
class Command(BaseCommand):
help = """Displays diffe... |
import warnings
_short_name = __name__.split(".")[-1]
warnings.warn(
"Importing %(full_name)s is deprecated. "
"Use from openupgradelib import %(short_name)s" % {
'full_name': __name__,
'short_name': _short_name,
}, DeprecationWarning, stacklevel=2)
_new_name = "openupgradelib.%s" % _short... |
import ldif
import os
import sys
import shutil
import random
import traceback
from ipaplatform.paths import paths
from ipaplatform import services
from ipapython.ipa_log_manager import *
from ipapython import ipaldap
from ipaserver.install import installutils
from ipaserver.install import schemaupdate
from ipaserver.i... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.db.models.deletion
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('api', '0132_auto_20160607_1748'),
]
operations = [
migrati... |
from __future__ import print_function
#!/usr/bin/env python
#########################################################################
# Reinforcement Learning with SPE on the ShipSteering Environment
#
# Requirements:
# pybrain (tested on rev. 1195, ship env rev. 1202)
# Synopsis:
# shipbenchm.py [<True|False> [lo... |
from pymatgen.util.testing import PymatgenTest
from pymatgen.core.xcfunc import XcFunc
class LibxcFuncTest(PymatgenTest):
def test_xcfunc_api(self):
"""Testing XcFunc API."""
# Aliases should be unique
assert len(XcFunc.aliases()) == len(set(XcFunc.aliases()))
# LDA-Teter
... |
from matplotlib.offsetbox import AnchoredOffsetbox
#from matplotlib.transforms import IdentityTransform
import matplotlib.transforms as mtrans
#from matplotlib.axes import Axes
from mpl_axes import Axes
from matplotlib.transforms import Bbox, TransformedBbox, IdentityTransform
from matplotlib.patches import Patch
fr... |
from lib.common import helpers
class Module:
def __init__(self, mainMenu, params=[]):
self.info = {
'Name': 'Invoke-WMI',
'Author': ['@harmj0y'],
'Description': ('Executes a stager on remote hosts using WMI.'),
'Background' : False,
'OutputE... |
"""
==============
Array indexing
==============
Array indexing refers to any use of the square brackets ([]) to index
array values. There are many options to indexing, which give numpy
indexing great power, but with power comes some complexity and the
potential for confusion. This section is just an overview of the
v... |
from __future__ import absolute_import
import collections
import functools
import logging
from ._collections import RecentlyUsedContainer
from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool
from .connectionpool import port_by_scheme
from .exceptions import LocationValueError, MaxRetryError, ProxyScheme... |
'''
Created on July 26, 2013
Example service created for a weather sensor. An Arduino POSTs simple JSON value-only updates to the
REST endpoints defined by the Observable Property created for each sensor output. An example graph is
created to demonstrate how endpoints can be discovered by reading the graph meta data
... |
"""A generic class to build line-oriented command interpreters.
Interpreters constructed with this class obey the following conventions:
1. End of file on input is processed as the command 'EOF'.
2. A command is parsed out of each line by collecting the prefix composed
of characters in the identchars member.
3. A ... |
import flask
from flask import redirect
from werkzeug.exceptions import Forbidden, NotFound, MethodNotAllowed
from inginious.frontend.lti_request_validator import LTIValidator
from inginious.frontend.pages.utils import INGIniousPage, INGIniousAuthPage
from itsdangerous import want_bytes
from inginious.common import ex... |
import subprocess
import tempfile
import luigi
from helpers import with_config, unittest
from luigi.contrib.pig import PigJobError, PigJobTask
from mock import patch
class SimpleTestJob(PigJobTask):
def output(self):
return luigi.LocalTarget('simple-output')
def pig_script_path(self):
return... |
"""
Very simple and basic mathematical expressions used often throughout the library.
"""
__authors__ = "Ian Goodfellow and Razvan Pascanu"
__copyright__ = "Copyright 2013, Universite de Montreal"
__credits__ = ["Ian Goodfellow and Razvan Pascanu"]
__license__ = "3-clause BSD"
__maintainer__ = "LISA Lab"
__email__ = "p... |
"""Signs and zipaligns APK.
"""
import optparse
import os
import shutil
import sys
import tempfile
from util import build_utils
def SignApk(keystore_path, unsigned_path, signed_path):
shutil.copy(unsigned_path, signed_path)
sign_cmd = [
'jarsigner',
'-sigalg', 'MD5withRSA',
'-digestalg', 'SHA1... |
"""Self-test suite for Crypto.Cipher.DES"""
__revision__ = "$Id$"
from common import dict # For compatibility with Python 2.1 and 2.2
from Crypto.Util.py3compat import *
import unittest
# This is a list of (plaintext, ciphertext, key, description) tuples.
SP800_17_B1_KEY = '01' * 8
SP800_17_B2_PT = '00' * 8
test... |
"""
Youtube Tag
---------
This implements a Liquid-style youtube tag for Pelican,
based on the jekyll / octopress youtube tag [1]_
Syntax
------
{% youtube id [width height] %}
Example
-------
{% youtube dQw4w9WgXcQ 640 480 %}
Output
------
<iframe
width="640" height="480" src="https://www.youtube.com/embed/dQw4... |
'''
Created on Dec 15, 2014
@author: bvukobratovic
'''
from sydpy import *
from examples.crc32.crc32 import Crc32
import zlib
from sydpy.procs.clk import Clocking
eth_usr_pkt = Struct(
('dest', Vector(6, bit8)),
('src', Vector(6, bit8)),
('len_type', bi... |
#!/usr/bin/env python
"""
Example Azure Handler script for Linux IaaS
Diable example
"""
import os
import imp
import time
import json
waagent=imp.load_source('waagent','/usr/sbin/waagent')
from waagent import LoggerInit
hutil=imp.load_source('HandlerUtil','./resources/HandlerUtil.py')
LoggerInit('/var/log/waagent.l... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
import traceback
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ec2 import boto3_conn, ec2_argument_spec, get_aws_connection_info
from ansible.modu... |
from django.utils.translation import ugettext_lazy as _
import horizon
from openstack_dashboard.api import glance
from openstack_dashboard.dashboards.admin import dashboard
class MetadataDefinitions(horizon.Panel):
name = _("Metadata Definitions")
slug = 'metadata_defs'
permissions = ('openstack.roles.a... |
"""
Annotations.
invenio.modules.annotations
---------------------------
**FIXME: Outdated documentation.**
To enable the module, make sure to remove it from ``PACKAGES_EXCLUDE``,
where it is placed by default.
To enable Web page annotations, add the following to your templates:
.. code-block:: jinja
{%- from... |
'''
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use... |
import os
import sys
import tempfile
import re
import platform
import imp
import socket
protocol=imp.load_source('protocol','../protocol.py')
"""
Ubuntu/Debian: /etc/network/interfaces:dns-nameservers 8.8.8.8 8.8.4.4
REDHAT/CENTOS: /etc/resolv.conf
nameserver 192.168.1.254
nameserver 8.8.8.8
SLES: /etc/... |
"""
Utility class for moving averages.
It is used in the status panel widget for displaying up and down
download rates.
"""
from leap.bitmask.util import first
class RateMovingAverage(object):
"""
Moving window average for calculating
upload and download rates.
"""
SAMPLE_SIZE = 5
def __init... |
from __future__ import unicode_literals
from flask import flash, redirect, request
from werkzeug.exceptions import NotFound
from indico.core.db.sqlalchemy.protection import ProtectionMode, render_acl
from indico.modules.events.management.controllers.base import RHManageEventBase
from indico.modules.events.management.... |
"""
Zen Chatbot talks in gems of Zen wisdom.
This is a sample conversation with Zen Chatbot:
ZC: Welcome, my child.
me: Good afternoon.
ZC: Ask the question you have come to ask.
me: How can I achieve enlightenment?
ZC: How do you suppose?
me: Through meditation.
ZC: Form is emptiness, and emptine... |
from __future__ import unicode_literals
import datetime
from django.contrib.admin.templatetags.admin_static import static
from django.contrib.admin.templatetags.admin_urls import add_preserved_filters
from django.contrib.admin.utils import (
display_for_field, display_for_value, label_for_field, lookup_field,
)
f... |
"""helpful functions to analyses pytrak data"""
__author__ = "Oliver Lindemann"
from scipy import signal
import numpy as np
def inch2cm(data):
"""converts numpy data in inch to cm"""
return data * 2.54
def velocity(data, timestamps):
"""calculates velocity of data for all sensors
data in cm, timest... |
# -*- 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):
# Changing field 'Benefit.type'
db.alter_column('offer_benefit', 'type', self.gf('django.db.models.fields.C... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'network'}
import re
import time
from copy import deepcopy
from ansible.module_utils.basic import Ansib... |
from datetime import datetime
from django import forms
from django.utils.translation import ugettext_lazy as _
from pinax.apps.photos.models import Image
class PhotoUploadForm(forms.ModelForm):
class Meta:
model = Image
exclude = ["member", "photoset", "title_slug", "effect", "crop_from"]
... |
from openerp import models, fields, api, exceptions, _
from openerp.addons import decimal_precision as dp
class MrpRepair(models.Model):
_inherit = 'mrp.repair'
analytic_account = fields.Many2one(
'account.analytic.account', domain=[('type', '!=', 'view')],
string='Analytic Account')
@ap... |
"""
Module to set up run time parameters for Clawpack -- AMRClaw code.
The values set in the function setrun are then written out to data files
that will be read in by the Fortran code.
"""
import os
import numpy as np
#------------------------------
def setrun(claw_pkg='geoclaw'):
#-------------------------... |
from nose.tools import assert_raises, assert_true, assert_false
import numpy as np
from scipy import sparse
from numpy.testing import (assert_array_almost_equal, assert_array_equal,
assert_equal)
from sklearn import datasets, svm, linear_model, base
from sklearn.datasets import make_classif... |
import github.GithubObject
import github.HookResponse
class Hook(github.GithubObject.CompletableGithubObject):
"""
This class represents Hooks as returned for example by http://developer.github.com/v3/repos/hooks
"""
@property
def active(self):
"""
:type: bool
"""
... |
import threading
import traceback
from gi.repository import Gdk
from gi.repository import GLib
import libvirt
import virtinst.progress
from .baseclass import vmmGObjectUI
class _vmmMeter(virtinst.progress.Meter):
def __init__(self, pbar_pulse, pbar_fraction, pbar_done):
virtinst.progress.Meter.__init_... |
import redis
import msgpack
import json
import pytest
from webob import Request
from dsq.store import QueueStore, ResultStore
from dsq.manager import Manager
from dsq.http import Application
from dsq.compat import bytestr
@pytest.fixture
def app(request):
cl = redis.StrictRedis()
cl.flushdb()
return Appl... |
from m5.params import *
from MemObject import MemObject
# The communication monitor will most typically be used in combination
# with periodic dumping and resetting of stats using schedStatEvent
class CommMonitor(MemObject):
type = 'CommMonitor'
# one port in each direction
master = MasterPort("Master por... |
"""Drop-in replacement for the thread module.
Meant to be used as a brain-dead substitute so that threaded code does
not need to be rewritten for when the thread module is not present.
Suggested usage is::
try:
import thread
except ImportError:
import dummy_thread as thread
"""
__author__ = ... |
'''
Created on 26/10/2011
@author: Luis Ariel Vega Soliz (<EMAIL>)
@contact: Uremix Team (http://uremix.org)
'''
from setuptools import setup, find_packages
setup(name='uremix-app-developer-helper',
version='0.3.1',
description='Un conjunto de procedimientos de ayuda para el desarrollo de aplicacion... |
import datetime, time
"""
module for logical calculation stuff needed by gui implementations
"""
def parseStartTime(startTime):
"""
creates a datetime object from a string, generated by time.asctime
@param startTime string: time string in format: %a %b %d %H:%M:%S %Y
"""
currentDay=datetime.da... |
"""Tests for 'site'.
Tests assume the initial paths in sys.path once the interpreter has begun
executing have not been removed.
"""
import unittest
from test.test_support import run_unittest, TESTFN, EnvironmentVarGuard
from test.test_support import captured_output, is_jython
import __builtin__
import os
import sys
i... |
""" Test for assert_deallocated context manager and gc utilities
"""
import gc
from scipy._lib._gcutils import (set_gc_state, gc_state, assert_deallocated,
ReferenceError, IS_PYPY)
from numpy.testing import assert_equal
import pytest
def test_set_gc_state():
gc_status = gc.isen... |
import json
import re
import sys
import threading
import urllib
# URL regular expression
url_re = re.compile('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', re.IGNORECASE)
# UniProt sequence page expression
uniprot_sequence_re = re.compile('http://(www|ebi[0-9]).uniprot.org/uniprot/[... |
import FreeCAD,FreeCADGui
FreeCAD.open(FreeCAD.getResourceDir()+"examples/FemCalculixCantilever3D.FCStd")
FreeCADGui.activeDocument().sendMsgToViews("ViewFit") |
"""
ZFS Storage Appliance REST API Client Programmatic Interface
"""
import httplib
import json
import StringIO
import time
import urllib2
from oslo_log import log
from cinder.i18n import _LE, _LI
LOG = log.getLogger(__name__)
class Status(object):
"""Result HTTP Status"""
def __init__(self):
pas... |
from __future__ import unicode_literals
import datetime
import decimal
from collections import defaultdict
from django.contrib.auth import get_permission_codename
from django.core.exceptions import FieldDoesNotExist
from django.core.urlresolvers import NoReverseMatch, reverse
from django.db import models
from django.... |
#Contains functions used to classify a proposed trade consisting of two HistoricData
#objects at a specific time as either successful (reverted to mean) or unsuccessful.
from singleseriesfns import *
from twoseriesfns import *
def bounded_roi(hd1, hd2, n=20, offset=20):
"""
Calculates the average, bounded ROI ... |
#! /usr/bin/python
#
# See README for usage instructions.
import sys
import os
import subprocess
# We must use setuptools, not distutils, because we need to use the
# namespace_packages option for the "google" package.
try:
from setuptools import setup, Extension
except ImportError:
try:
from ez_setup import u... |
import memcache
# connect to local server
mc = memcache.Client(['127.0.0.1:11211'], debug=0)
# Add couple of keys
mc.set("http://127.0.0.1:80/", "http://127.0.0.1:8080");
mc.set("http://localhost:80/", "http://localhost:8080");
# Print the keys that are saved
print "response-1 is '%s'" %(mc.get("http://127.0.0.1:80/... |
import itertools
from typing import Iterable, Tuple, Dict, Any
import networkx as nx
import cirq
from cirq._compat import deprecated
@deprecated(deadline="v0.12", fix="use gridqubits_to_graph_device(device.qubits) instead")
def xmon_device_to_graph(device: Any) -> nx.Graph:
"""Gets the graph of an XmonDevice.""... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.