content stringlengths 4 20k |
|---|
#!/usr/bin/env python
import argparse
import collections
import nltk.corpus
from nltk.corpus.util import LazyCorpusLoader
from nltk_trainer import basestring, load_corpus_reader, simplify_wsj_tag
########################################
## command options & argument parsing ##
########################################
... |
def get_links_from_url(url):
"Return all the href links found on the web location"
import urllib, sgmllib
class LinksParser(sgmllib.SGMLParser):
def parse(self, s):
"Parse the given string 's'."
self.feed(s)
self.close()
def __init__(self, verbo... |
import isdhic
import numpy as np
from isdhic import utils
from isdhic.core import take_time
from scipy import optimize
class HamiltonianMonteCarlo(isdhic.HamiltonianMonteCarlo):
stepsizes = []
@property
def stepsize(self):
return self.leapfrog.stepsize
@stepsize.setter
def stepsize(sel... |
"""
If you execute force_repeatability() then the following things are changed in the runtime:
1. random.random() and its sibling functions, and random.Random.seed() in the random module are seeded with a known seed so that they will return the same sequence on each run.
2. os.urandom() is replaced by a fake urandom... |
# -*- coding: utf-8 -*-
import os
import httplib as http
from flask import request
from framework.flask import redirect # VOL-aware redirect
from framework.exceptions import HTTPError
from framework.auth.decorators import collect_auth
from framework.auth.decorators import must_be_logged_in
from website import mode... |
import web
import os
from collector.webapi.class_partial import class_with_partial_init
from configman import Namespace, RequiredConfig
#==============================================================================
class WebServerBase(RequiredConfig):
required_config = Namespace()
#-----------------------... |
"""
Support for reading data from a serial port.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.serial/
"""
import logging
import json
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.components.se... |
"""Test idlelib.ParenMatch."""
# This must currently be a gui test because ParenMatch methods use
# several text methods not defined on idlelib.idle_test.mock_tk.Text.
import unittest
from unittest.mock import Mock
from test.support import requires
from tkinter import Tk, Text
from idlelib.ParenMatch import ParenMatch... |
import logging
import yaml
import click
from barn import open_collection
from docpipe.exc import DocpipeException
from docpipe.pipeline import Pipeline
log = logging.getLogger(__name__)
def execute_pipeline(ctx, fh, operation):
try:
config = yaml.load(fh.read())
fh.close()
except Exception... |
import numpy as np
import scipy.sparse as sp
from sklearn.utils.testing import assert_less
from sklearn.utils.testing import assert_greater
from sklearn.utils.testing import assert_array_almost_equal, assert_array_equal
from sklearn.utils.testing import assert_raises
from sklearn.base import ClassifierMixin
from skle... |
"""
SleekXMPP: The Sleek XMPP Library
Copyright (C) 2010 Nathanael C. Fritz, Lance J.T. Stout
This file is part of SleekXMPP.
See the file LICENSE for copying permission.
"""
import logging
import sleekxmpp
from sleekxmpp.plugins.xep_0030 import StaticDisco
log = logging.getLogger(__name__)
class... |
from test_framework import BitcoinTestFramework
from util import assert_equal
class GetChainTipsTest (BitcoinTestFramework):
def run_test (self):
BitcoinTestFramework.run_test (self)
tips = self.nodes[0].getchaintips ()
assert_equal (len (tips), 1)
assert_equal (tips[0]['branchlen... |
# encoding: UTF-8
# 内置模块
import sys
from time import sleep
# 测试模块
from vnltsmd import *
#----------------------------------------------------------------------
def print_dict(d):
"""按照键值打印一个字典"""
for key,value in d.items():
print key + ':' + str(value)
#-----------------------------... |
def printTextfile(fdist, fileName):
"""This function will print the given frequency distribution to
text file with the given filename"""
#Create the file with the given filename.
file = open(fileName, "w+")
#Write each bigram with its frequency into the file.
for k,v in fdist.items():
fi... |
"""Test utilities.
.. warning:: This module is not part of the public API.
"""
import os
import pkg_resources
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
import OpenSSL
from acme import jose
def vector_path(*names):
"""Path to a test vector... |
"""Sphinx related paver tasks.
Methods
-------
apidoc
Derive reStructuredText API doc files from python source code.
This task is essentially a wrapper around the `sphinx-apidoc`_ script.
The following settings can be set on the options object:
* ``apidoc_excludes`` -- (*str or list of str*) A direct... |
#! /usr/bin/env python
from MDAnalysis import *
#from MDAnalysis.analysis.align import *
import numpy
import math
u = Universe("init.pdb","temp.pos.pdb")
v = Universe("init.pdb")
# residues
a1 = u.selectAtoms("segid A and resid 46")
b1 = u.selectAtoms("segid B and resid 90")
a2 = u.selectAtoms("segid A and resid 69"... |
from django.contrib import admin
from django.contrib.admin import helpers
from django.contrib.admin.utils import model_ngettext, get_deleted_objects
from django.db import router
from django.core.exceptions import PermissionDenied
from django.template.response import TemplateResponse
from django.utils.encoding import fo... |
import re
component_re = re.compile(r'(\d+ | [a-z]+ | \.| -)', re.VERBOSE)
replace = {'pre':'c', 'preview':'c','-':'final-','_':'final-','rc':'c','dev':'@','saas':'','~':''}.get
def _parse_version_parts(s):
for part in component_re.split(s):
part = replace(part,part)
if not part or part=='.':
... |
import os
import sys
import urllib
import urllib2
import re
import xbmc
import xbmcgui
import xbmcaddon
import xbmcplugin
import plugintools
from __main__ import *
addonName = xbmcaddon.Addon().getAddonInfo("name")
addonVersion = xbmcaddon.Addon().getAddonInfo("version")
addonId = xbmca... |
import BoostBuild
t = BoostBuild.Tester()
t.write("jamroot.jam", """
import rcc ;
""")
t.write("rcc.jam", """
import type ;
import generators ;
import print ;
# Use 'RCC' to avoid conflicts with definitions in the standard rc.jam and
# msvc.jam
type.register RCC : rcc ;
rule resource-compile ( targets * : sourc... |
# -*- coding: utf-8 -*-
r"""
>>> floatformat(7.7)
u'7.7'
>>> floatformat(7.0)
u'7'
>>> floatformat(0.7)
u'0.7'
>>> floatformat(0.07)
u'0.1'
>>> floatformat(0.007)
u'0.0'
>>> floatformat(0.0)
u'0'
>>> floatformat(7.7,3)
u'7.700'
>>> floatformat(6.000000,3)
u'6.000'
>>> floatformat(6.200000, 3)
u'6.200'
>>> floatformat(... |
# -*- coding: utf-8 -*-
"""
werkzeug.contrib.lint
~~~~~~~~~~~~~~~~~~~~~
.. versionadded:: 0.5
This module provides a middleware that performs sanity checks of the WSGI
application. It checks that :pep:`333` is properly implemented and warns
on some common HTTP errors such as non-empty respons... |
# -*- coding: utf-8 -*-
"""Test suite for the deepreload module."""
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
import os
import nose.tools as nt
from IPython.testing import decorators as dec
... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
dlg_field_properties.py
---------------------
Date : April 2012
Copyright : (C) 2012 by Giuseppe Sucameli
Email : brush dot tyler at gmail dot com
******... |
import json
from django.contrib.postgres import forms, lookups
from django.contrib.postgres.fields.array import ArrayField
from django.core import exceptions
from django.db.models import Field, TextField, Transform
from django.utils import six
from django.utils.encoding import force_text
from django.utils.translation ... |
import errno
import os
import platform
import subprocess
from subprocess import PIPE
import time
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.common import utils
try:
from subprocess import DEVNULL
_HAS_NATIVE_DEVNULL = True
except ImportError:
DEVNULL = -3
_HAS_NAT... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import csv
import os
import drules_struct_pb2
from webcolors.webcolors import hex_to_color_name
from operator import *
from copy import *
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
DATADIR = "../../../data"
files = {
"mapcss_mapping": os.path.join(DATADIR... |
# the order of these calls is important...
import sys
import os
import re
import getopt
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as pyplot
import scipy.ndimage
import scipy.misc
from scipy import stats
import numpy
import math
import string
import random
from subprocess import call
import shutil... |
from spack import *
class PacbioDamasker(MakefilePackage):
"""Damasker: The Dazzler Repeat Masking Suite. This is a special fork
required for some pacbio utilities."""
homepage = "https://github.com/PacificBiosciences/DAMASKER"
url = "https://github.com/PacificBiosciences/DAMASKER"
versi... |
# -*- coding: utf-8 -*-
from south.v2 import DataMigration
try:
from django.contrib.auth import get_user_model
except ImportError: # django < 1.5
from django.contrib.auth.models import User
else:
User = get_user_model()
user_orm_label = '%s.%s' % (User._meta.app_label, User._meta.object_name)
user_model_... |
#!/usr/bin/python -u
import sys
import libxml2
# Memory debug specific
libxml2.debugMemory(1)
log = ""
class callback:
def startDocument(self):
global log
log = log + "startDocument:"
def endDocument(self):
global log
log = log + "endDocument:"
def startElement(self, tag... |
import json
import requests
import pynder
# class User(object):
# """docstring for User"""
# def __init__(self, bio, name, photo, age, gender, birth_date, jobs, schools, distance_km, common_connections, common_interests):
# super(User, self).__init__()
# self.bio = bio
# self.name = n... |
from google.appengine.ext import db
from model.queuepropertymixin import QueuePropertyMixin
class WorkItems(db.Model, QueuePropertyMixin):
queue_name = db.StringProperty()
item_ids = db.ListProperty(int)
date = db.DateTimeProperty(auto_now_add=True)
@classmethod
def key_for_queue(cls, queue_name... |
"""
Copyright (c) 2012-2014 RockStor, Inc. <http://rockstor.com>
This file is part of RockStor.
RockStor 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 2 of the License,
or (at your option) any la... |
"""
Tests for the PCG_XSH_RS_V0 generator.
"""
import pkgutil
import unittest
from pcgrandom.pcg_xsh_rs_v0 import PCG_XSH_RS_V0
from pcgrandom.test.test_pcg_common import TestPCGCommon
class Test_PCG_XSH_RS_V0(TestPCGCommon, unittest.TestCase):
gen_class = PCG_XSH_RS_V0
def setUp(self):
self.gen = s... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.netv... |
import numpy as np
import pickle
from sklearn.isotonic import (check_increasing, isotonic_regression,
IsotonicRegression)
from sklearn.utils.testing import (assert_raises, assert_array_equal,
assert_true, assert_false, assert_equal,
... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
import traceback
try:
import ovirtsdk4.types as otypes
except ImportError:
pass
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ovirt impo... |
import pygit2
from gitmodel import fields
from gitmodel import models
class Person(models.GitModel):
slug = fields.SlugField()
first_name = fields.CharField()
last_name = fields.CharField()
email = fields.EmailField()
age = fields.IntegerField(required=False)
account_balance = fields.DecimalF... |
from django.conf import settings
from rest_framework.decorators import APIView
from rest_framework.exceptions import NotAcceptable
from rest_framework.response import Response
from rest_framework.test import APIRequestFactory
class RequestVersionView(APIView):
def get(self, request, *args, **kwargs):
retu... |
"""Abstract base class for clustering algorithm."""
import abc
import six
import tensorflow as tf
from tensorflow_model_optimization.python.core.clustering.keras.cluster_config import GradientAggregation
@six.add_metaclass(abc.ABCMeta)
class ClusteringAlgorithm(object):
"""Class to implement highly efficient ve... |
from copy import copy
import sqlalchemy as sa
from sqlalchemy_continuum import version_class
from sqlalchemy_continuum.plugins import PropertyModTrackerPlugin
from sqlalchemy_continuum.schema import update_property_mod_flags
from tests import TestCase
class TestSchemaTools(TestCase):
versioning_strategy = 'valid... |
"""
Custom Django fields.
"""
from django.db import models
class CharNullField(models.CharField):
"""
CharField that stores NULL but returns ''
"""
description = "CharField that stores NULL but returns ''"
def to_python(self, value):
"""Converts the value into the correct Python object.... |
#!/usr/bin/env python
'''
@author: Carlos Hernandez
@organization: ASLab
@summary: module that realises perception up to the sensory processing, on rosnodes
@status: second version - basic functionality but working
'''
#import sys
#import os
#import xmlrpclib
import roslib; roslib.load_manifest('OMRosDrivers_py')
im... |
"""This module is deprecated. Please use `airflow.providers.mysql.operators.mysql`."""
import warnings
# pylint: disable=unused-import
from airflow.providers.mysql.operators.mysql import MySqlOperator # noqa
warnings.warn(
"This module is deprecated. Please use `airflow.providers.mysql.operators.mysql`.",
D... |
"""A helper library which provides support for (windows) chrome installation.
The library provides methods to check if Chrome is installed and the ability to
install/uninstall it. Currently, there is no cleanup of previously downloaded
installers and their associated folders.
"""
import cStringIO
import csv
import ... |
# -*- coding: utf-8 -*-
"""
requests.api
~~~~~~~~~~~~
This module implements the Requests API.
:copyright: (c) 2012 by Kenneth Reitz.
:license: ISC, see LICENSE for more details.
"""
from . import sessions
from .safe_mode import catch_exceptions_if_in_safe_mode
@catch_exceptions_if_in_safe_mode
def request(metho... |
"""Tests for the experimental input pipeline ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.contrib.data.python.ops import dataset_ops
from tensorflow.python.framework import constant_op
from tensorflow.python.fra... |
"""
Notes:
This code contains one method that explains how to build a
logistic regression classifier for the MNIST dataset using
the yann toolbox.
For a more interactive tutorial refer the notebook at
yann/pantry/tutorials/notebooks/Logistic Regression.ipynb
"""
from yann.network import network
... |
from collections import Counter
def TFIDF(TF, complaints, term):
if TF >= 1:
n = len(complaints)
x = sum([1 for complaint in complaints if term in complaint['body']])
return log(TF + 1) * log(n / x)
else:
return 0
def DF(vocab, complaints):
term_DF = dict()
for term in ... |
from __future__ import unicode_literals
from ._discounts import get_discount_modules
from ._module import get_pricing_module
def get_price_info(context, product, quantity=1):
"""
Get price info of product for given quantity.
Returned `PriceInfo` object contains calculated `price` and
`base_price`. ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.utils.encoding import python_2_unicode_compatible
import uuid
from django.db import models
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
class BaseProfile(models.Model):
user = models.OneToOneFie... |
"""
Support for Verisure Smartplugs.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.verisure/
"""
import logging
from homeassistant.components.verisure import HUB as hub
from homeassistant.components.verisure import CONF_SMARTPLUGS
from homeassis... |
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:
... |
"""Tests for the Google Hangouts config flow."""
from unittest.mock import patch
from homeassistant import data_entry_flow
from homeassistant.components.hangouts import config_flow
async def test_flow_works(hass, aioclient_mock):
"""Test config flow without 2fa."""
flow = config_flow.HangoutsFlowHandler()
... |
"""Allows custom commands to be run when an event is emitted by beets"""
from __future__ import division, absolute_import, print_function
import string
import subprocess
import six
from beets.plugins import BeetsPlugin
from beets.util import shlex_split, arg_encoding
class CodingFormatter(string.Formatter):
"""... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from scipy import special
from scipy import stats
from tensorflow.contrib.distributions.python.ops import beta as beta_lib
from tensorflow.contrib.distributions.python.ops import kullback_lei... |
"""Useful utility decorators. """
from __future__ import print_function, division
import sys
import types
import inspect
from sympy.core.decorators import wraps
from sympy.core.compatibility import class_types, get_function_globals, get_function_name, iterable
def threaded_factory(func, use_add):
"""A factory f... |
import unittest
import ryu.ofproto.ofproto_v1_3_parser as ofpp
class Test_FlowSpec(unittest.TestCase):
def test_flowspec_src_0_dst_0(self):
user = ofpp.NXFlowSpecMatch(src=('in_port', 0),
dst=('in_port', 0),
n_bits=16)
on_wir... |
import sys
from types import ModuleType
import unittest
from lazyload import make_lazy, _LazyModuleMarker
class LazyLoadTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.modname = 'abc'
def tearDown(self):
sys.modules.pop(self.modname, None) # remove from the modules.
... |
"""**Numerical tools**
"""
import numpy
from utilities import verify
def ensure_numeric(A, typecode=None):
"""Ensure that sequence is a numeric array.
Args:
* A: Sequence. If A is already a numeric array it will be returned
unaltered
If not, an attempt i... |
{
"P_COUNT": {
"columns": (("ID", FastSerializer.VOLTTYPE_INTEGER),
("POINTS", FastSerializer.VOLTTYPE_INTEGER)),
"partitions": ("ID",),
"indexes": ("POINTS",)
},
"R_COUNT": {
"columns": (("ID", FastSerializer.VOLTTYPE_INTEGER),
("POINT... |
"""This module holds the ``Process``es for NER."""
from copy import deepcopy
from dataclasses import dataclass
from typing import Any, List
from boltons.cacheutils import cachedproperty
from cltk.core.data_types import Doc, Process
from cltk.ner.ner import tag_ner
@dataclass
class NERProcess(Process):
"""To be... |
import sys,math,os.path
import StringIO
from amlogparser import AMLog
from getopt import getopt
class ColourManager(object):
def __init__(self):
# text-printable colours
self.colours = [
'#E4F5FC', '#62C2A2', '#E2F2D8', '#A9DDB4', '#E2F6E1', '#D8DAD7', '#BBBDBA', '#FEE6CE', '#FFCF9F',
'#FDAE69', '#FDE4DD', '#... |
"""
CorpusReader for reviews corpora (syntax based on Customer Review Corpus).
- Customer Review Corpus information -
Annotated by: Minqing Hu and Bing Liu, 2004.
Department of Computer Sicence
University of Illinois at Chicago
Contact: Bing Liu, <EMAIL>
http://www.cs.uic.edu/~liub
Distrib... |
from __future__ import print_function
import sys
if __name__ == '__main__':
import matplotlib
matplotlib.use('Agg')
import pylab as plt
import numpy as np
from astrometry.util.file import trymakedirs
from tractor import *
from tractor.psfex import *
from legacypipe.survey import *
def main():
plt.figur... |
# 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 'Helptext'
db.create_table('okhelptexts_helptext', (
('id', self.gf('django.db.... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import sys
from units.mock.procenv import ModuleTestCase
from ansible.compat.tests import unittest
from ansible.compat.tests.mock import patch, MagicMock
from ansible.module_utils.six.moves import builtins
realimport = builtins.__... |
class ATNDeserializationOptions(object):
defaultOptions = None
def __init__(self, copyFrom = None):
self.readOnly = False
self.verifyATN = True if copyFrom is None else copyFrom.verifyATN
self.generateRuleBypassTransitions = False if copyFrom is None else copyFrom.generateRuleBypassTra... |
# -*- coding: utf-8 -*-
"""
sockjs.tornado.periodic
~~~~~~~~~~~~~~~~~~~~~~~
This module implements customized PeriodicCallback from tornado with
support of the sliding window.
"""
import time
import logging
LOG = logging.getLogger("tornado.general")
class Callback(object):
"""Custom implementati... |
"""
Support for status output of APCUPSd via its Network Information Server (NIS).
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/apcupsd/
"""
import logging
from datetime import timedelta
import voluptuous as vol
from homeassistant.const import (CONF... |
"""Functional tests for 3d convolutional operations."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import itertools
import numpy as np
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.... |
import paddle.v2.dataset.cifar
import unittest
class TestCIFAR(unittest.TestCase):
def check_reader(self, reader):
sum = 0
label = 0
for l in reader():
self.assertEqual(l[0].size, 3072)
if l[1] > label:
label = l[1]
sum += 1
retur... |
"""Test Home Assistant volume utility functions."""
import pytest
from homeassistant.const import (
VOLUME_FLUID_OUNCE,
VOLUME_GALLONS,
VOLUME_LITERS,
VOLUME_MILLILITERS,
)
import homeassistant.util.volume as volume_util
INVALID_SYMBOL = "bob"
VALID_SYMBOL = VOLUME_LITERS
def test_convert_same_unit... |
"""The tests for local file sensor platform."""
import pytest
from homeassistant.const import STATE_UNKNOWN
from homeassistant.setup import async_setup_component
from tests.async_mock import Mock, mock_open, patch
from tests.common import mock_registry
@pytest.fixture
def entity_reg(hass):
"""Return an empty, l... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import re
from ansible.module_utils._text import to_bytes
from ansible.plugins.become import BecomeBase
class BecomeModule(BecomeBase):
name = 'doas'
# messages for detecting prompted password issues
fail = ('Permi... |
import pickle
import sys
import traceback
sys.path[0:0] = [""]
from pymongo.errors import (BulkWriteError,
EncryptionError,
NotPrimaryError,
NotMasterError,
OperationFailure)
from test import (PyMongoTestCa... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from rest_framework import serializers
from rest_framework_recursive.fields import RecursiveField
class NodeAttributeSerializer(serializers.Serializer):
"""
Serializes ``NavigationNode.attr``
"""
auth_required = seriali... |
import time
from odoo import tools
from odoo.modules.module import get_resource_path
from odoo.tests import Form, common, tagged
ISR1 = "703192500010549027000209403"
ISR2 = "120000000000234478943216899"
@tagged("post_install", "-at_install")
class PaymentISR(common.TransactionCase):
"""Test grouping of payment ... |
# -*- coding: utf-8 -*-
from functools import partial
from django.db import IntegrityError
from django.contrib.auth.models import User
from django.test import TestCase
from django.test.utils import override_settings
from organizations.models import (Organization, OrganizationUser,
OrganizationOwner)
from org... |
from oslo_config import cfg
from nova.tests.functional.v3 import api_sample_base
CONF = cfg.CONF
CONF.import_opt('osapi_compute_extension',
'nova.api.openstack.compute.extensions')
class FlavorAccessSampleJsonTests(api_sample_base.ApiSampleTestBaseV3):
ADMIN_API = True
extension_name = 'flav... |
# The views used below are normally mapped in django.contrib.admin.urls.py
# This URLs file is used to provide a reliable view deployment for test purposes.
# It is also provided as a convenience to those who want to deploy these URLs
# elsewhere.
from django.conf.urls import patterns, url
urlpatterns = patterns('',
... |
import sys,socket,os,time,re
port=None
host=None
if os.environ.has_key("SHELLPORT"):
try:
port=int(os.environ.get("SHELLPORT"))
except:
print("error: parsing SHELLPORT")
if os.environ.has_key("SHELLSERVER"):
host=os.environ.get("SHELLSERVER")
if len(sys.argv)>1 and re.search('^--shellserve... |
"""An estimator is a rule for calculating an estimate of a given quantity.
# Estimators
* **Estimators** are used to train and evaluate TensorFlow models.
They support regression and classification problems.
* **Classifiers** are functions that have discrete outcomes.
* **Regressors** are functions that predict conti... |
#
# simple Tokenizer for Matlab / Octave code
#
import re
class Token(object):
NAME = 1
OP = 2
COMMENT = 3
NL = 4
WHITESPACE = 5
def __init__(self, content, type):
self.content = content
self.type = type
def __str__(self):
return '"%s" [%s]' % (self.content, self.... |
#!/usr/bin/env python
"""Simple script to concatenate coverage reports.
"""
import os
import sys
import argparse
import fnmatch
def main(arguments):
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_arg... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import control, core, test_util, workspace
import logging
logger = logging.getLogger(__name__)
class TestControl(test_util.TestCase):
def setUp(... |
"""Test the timestamp processing functions."""
import logging
from src import basetest
from src.csvmatchreplace import timestamp
class TestTimestamp(basetest.TestCase):
def testConvertFmtToRe(self):
lookup = {'a': 'apple', 'b': 'bat', 'c': 'cat'}
tests = (
('', ''),
('%a', 'apple'),
... |
"""
Formtools Preview application.
"""
import cPickle as pickle
from django.conf import settings
from django.http import Http404
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from django.utils.hashcompat import md5_constructor
from django.utils.crypto import consta... |
from cStringIO import StringIO
from weboob.capabilities.radio import CapRadio, Radio
from weboob.capabilities.audiostream import BaseAudioStream
from weboob.tools.capabilities.streaminfo import StreamInfo
from weboob.capabilities.collection import CapCollection
from weboob.tools.backend import Module
from weboob.depre... |
"""Self documenting XML-RPC Server.
This module can be used to create XML-RPC servers that
serve pydoc-style documentation in response to HTTP
GET requests. This documentation is dynamically generated
based on the functions and methods registered with the
server.
This module is built upon the pydoc and SimpleXMLRPCSe... |
from __future__ import unicode_literals
import frappe
import os
from frappe.utils import get_files_path
from frappe.utils.file_manager import get_content_hash
def execute():
files_path = get_files_path()
# get files that don't have attached_to_name but exist
unlinked_files = get_unlinked_files(files_path)
if not ... |
"""liusblog URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-base... |
#!/usr/bin/env python
import logging
import sys
import unittest
from os.path import dirname, join
sys.path.insert(0, dirname(dirname(dirname(__file__))))
from dedupe import block, sim, linkcsv
def classify(comparisons):
"""Returns match pairs and non-match pairs.
:type comparisons: {(R, R):[float, ...]}
... |
from openradar import config
from openradar import loghelper
import logging
import ftplib
import os
import io
def ftp_transfer(source, target, name):
""" Transfer ftp file from source ftp to target ftp. """
data = io.BytesIO()
source.retrbinary('RETR ' + name, data.write)
data.seek(0)
target.stor... |
"""Unit tests for code in urllib.response."""
import socket
import tempfile
import urllib.response
import unittest
class TestResponse(unittest.TestCase):
def setUp(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.fp = self.sock.makefile('rb')
self.test_headers = {... |
"""
Test the interaction between trial and errors logged during test run.
"""
from __future__ import division
import time
from twisted.internet import reactor, task
from twisted.python import failure, log
from twisted.trial import unittest, reporter
def makeFailure():
"""
Return a new, realistic failure.
... |
"""
"""
import TestGyp
test = TestGyp.TestGyp()
test.run_gyp('build/all.gyp', chdir='src')
test.relocate('src', 'relocate/src')
test.build('build/all.gyp', test.ALL, chdir='relocate/src')
chdir = 'relocate/src/build'
# The top-level Makefile is in the directory where gyp was run.
# TODO(mmoss) Should the Makefil... |
from django.core.exceptions import FieldError
from django.db.models import F
from django.test import TestCase
from models import Company, Employee
class ExpressionsTests(TestCase):
def test_filter(self):
Company.objects.create(
name="Example Inc.", num_employees=2300, num_chairs=5,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.