content string |
|---|
from __future__ import unicode_literals
import frappe
from frappe.utils import flt, cstr
from frappe import msgprint, _
def execute(filters=None):
if not filters: filters = {}
salary_slips = get_salary_slips(filters)
columns, earning_types, ded_types = get_columns(salary_slips)
ss_earning_map = get_ss_earning_ma... |
"""
This module contains the trial distributed runner, the management class
responsible for coordinating all of trial's behavior at the highest level.
@since: 12.3
"""
import os
import sys
from twisted.python.filepath import FilePath
from twisted.python.modules import theSystemPath
from twisted.internet.defer import... |
#!/usr/bin/env python
'''
Tests for fastqutils split
'''
import os
import unittest
import ngsutils.fastq.split
from ngsutils.fastq import FASTQ
class SplitTest(unittest.TestCase):
def testSplit(self):
fname = os.path.join(os.path.dirname(__file__), 'test.fastq')
templ = os.path.join(os.path.dirn... |
"""Tests for MultivariateNormalFullCovariance."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from scipy import stats
from tensorflow.contrib import distributions
from tensorflow.python.ops import array_ops
from tensorflow.python.ops ... |
from openerp.osv import fields,osv
class res_partner(osv.osv):
def _task_count(self, cr, uid, ids, field_name, arg, context=None):
Task = self.pool['project.task']
return {
partner_id: Task.search_count(cr,uid, [('partner_id', '=', partner_id)], context=context)
for partner_... |
from event import Event
class KeyboardEvent(Event):
KEY_DOWN = "keyDown"
KEY_UP = "keyUp"
def __init__(self, etype, bubbles=False, cancelable=False,
charCodeValue=0, keyCodeValue=0, keyLocationValue=0,
ctrlKeyValue=False, altKeyValue=False,
... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
import errno
import json
import os
from subprocess import Popen, PIPE
from ansible.plugins.lookup import LookupBase... |
'''
InfDefineSectionParser
'''
##
# Import Modules
#
import re
from Library import DataType as DT
from Library import GlobalData
from Library.Parsing import MacroParser
from Library.Misc import GetSplitValueList
from Library.ParserValidate import IsValidArch
from Object.Parser.InfCommonObject import InfLi... |
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
__all__ = [
"__title__", "__summary__", "__uri__", "__version__", "__author__",
"__email__", "__license__", "__copyright__",
]
__title__ = "bcrypt"
__summary__ = "Modern password hashing for your sof... |
"""
Solve the unique lowest-cost assignment problem using the
Hungarian algorithm (also known as Munkres algorithm).
"""
# Based on original code by Brain Clapper, adapted to NumPy by Gael Varoquaux.
# Heavily refactored by Lars Buitinck.
# Copyright (c) 2008 Brian M. Clapper <<EMAIL>>, Gael Varoquaux
# LICENSE: BSD
... |
"""Module for experimental sonnet functions and classes.
This file contains functions and classes that are being tested until they're
either removed or promoted into the wider sonnet library.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Dependency ... |
# -*- coding:utf-8 -*-
"""
/***************************************************************************
qgsplugininstallerpluginerrordialog.py
Plugin Installer module
-------------------
Date : June 2013
Copyright... |
"""TestSuite"""
import sys
from . import case
from . import util
__unittest = True
def _call_if_exists(parent, attr):
func = getattr(parent, attr, lambda: None)
func()
class BaseTestSuite(object):
"""A simple test suite that doesn't provide class or module shared fixtures.
"""
def __init__(se... |
from boto.ec2.ec2object import EC2Object
class ReservedInstancesOffering(EC2Object):
def __init__(self, connection=None, id=None, instance_type=None,
availability_zone=None, duration=None, fixed_price=None,
usage_price=None, description=None):
EC2Object.__init__(self,... |
"""Module for downloading files from a pool of mirrors
DESCRIPTION
This module provides support for downloading files from a pool of
mirrors with configurable failover policies. To a large extent, the
failover policy is chosen by using different classes derived from
the main class, MirrorGroup.
Instances ... |
"""
Example of scripts.
These are scripts intended for a particular object - the
red_button object type in contrib/examples. A few variations
on uses of scripts are included.
"""
from evennia import DefaultScript
from evennia.contrib.tutorial_examples import cmdset_red_button as cmdsetexamples
#
# Scripts as state-m... |
import os
import shutil
import time
from lib.util.mysqlBaseTestCase import mysqlBaseTestCase
server_requirements = [[],[]]
servers = []
server_manager = None
test_executor = None
# we explicitly use the --no-timestamp option
# here. We will be using a generic / vanilla backup dir
backup_path = None
class basicTest(... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import re
import sys
from ansible import constants as C
from ansible.inventory.group import Group
from .host import Host
from ansible.plugins.inventory.aggregate import InventoryAggregateParser
from ansible import errors
class Inv... |
"""
Tests for site configuration's django models.
"""
from unittest.mock import patch
import pytest
from django.contrib.sites.models import Site
from django.db import IntegrityError, transaction
from django.test import TestCase
from openedx.core.djangoapps.site_configuration.models import (
SiteConfiguration,
S... |
from __future__ import print_function
import sys
sys.path.insert(1,"../../")
import h2o
import time
from tests import pyunit_utils
#----------------------------------------------------------------------
# This test will parse orc files containing timestamp and date information into
# H2O frame. Next, it will take the ... |
import sys, time, re
use_sub = False
use_popen = False
try:
import subprocess
use_sub = True
except ImportError:
import popen2
use_popen = True
if len(sys.argv) < 2:
print 'syntax: rlMemAvg <command>'
sys.exit(1)
proglist = sys.argv[1:]
if use_sub:
task = subprocess.Popen(proglist)
elif use_popen:
... |
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.azure_rm_common import AzureRMModuleBase
try:
from msrestazure... |
"""
This module tests capablanca.piece
"""
from capablanca import piece
def test_king_positions():
"""Should return proper threat positions when moving a King"""
king = piece.King(3, 3)
assert king.get_threats((1, 1)) == set([
(0, 0), (1, 0), (2, 0), (0, 1), (2, 1), (0, 2), (1, 2), (2, 2)
])
... |
'''
test_kijistats.py is a script to unit test the kijistats.py script to ensure it is
performing the expected computations, such as aggregating based on jobname or function name.
It uses pre-existing files in kiji-mapreduce/src/test/profiling/resources/ that
contain some sample output that was collected from some prof... |
import logging
import random
import select
import socket
import ssl
import time
import cStringIO
from socketpool import Connector
from socketpool.util import is_connected
CHUNK_SIZE = 16 * 1024
MAX_BODY = 1024 * 112
DNS_TIMEOUT = 60
class Connection(Connector):
def __init__(self, host, port, backend_mod=None, ... |
import os
import unittest
import urllib2
import json
import wptserve
from base import TestUsingServer, doc_root
class TestResponseSetCookie(TestUsingServer):
def test_name_value(self):
@wptserve.handlers.handler
def handler(request, response):
response.set_cookie("name", "value")
... |
# -*- coding: utf-8 -*-
from __future__ import with_statement
import copy
from cms.utils.urlutils import admin_reverse
from django.contrib.sites.models import Site
from cms.api import create_page
from cms.models import Page, Placeholder
from cms.utils import get_cms_setting
from cms.test_utils.testcases import CMSTes... |
# coding: utf-8
from __future__ import unicode_literals
import random
from .common import InfoExtractor
from ..compat import compat_urlparse
from ..utils import (
xpath_text,
int_or_none,
ExtractorError,
sanitized_Request,
)
class MioMioIE(InfoExtractor):
IE_NAME = 'miomio.tv'
_VALID_URL = r... |
from django.shortcuts import render, redirect
from django.views.generic import View
from sentiment.models import Tweet, Word
from sentiment.bayes import *
from django.db.models import Avg
from django.http import JsonResponse
class IndexView(View):
template = 'sentiment/index.html'
def get(self, request):
... |
from django.template.defaultfilters import striptags
from django.test import SimpleTestCase
from django.utils.safestring import mark_safe
from ..utils import setup
class StriptagsTests(SimpleTestCase):
@setup({'striptags01': '{{ a|striptags }} {{ b|striptags }}'})
def test_striptags01(self):
output ... |
"""LVNF EMS SET command."""
from uuid import UUID
from empower.core.lvnf import LVNF
from empower.core.module import Module
from empower.lvnf_ems import PT_LVNF_SET_REQUEST
from empower.lvnf_ems import PT_LVNF_SET_RESPONSE
from empower.lvnfp.lvnfpserver import ModuleLVNFPWorker
from empower.main import RUNTIME
cla... |
#!/usr/bin/env python
# encoding: utf-8
"""
print_utils.py
Created by Saverio Porcari on 2009-06-29.
Copyright (c) 2009 __MyCompanyName__. All rights reserved.
"""
from gnr.web.gnrbaseclasses import BaseComponent
class PrintUtils(BaseComponent):
py_requires = 'batch_runner:BatchRunner'
def serverPrint(self,... |
from django.conf.urls import *
from django.contrib.auth.decorators import login_required, permission_required
from signbank.dictionary.models import *
from signbank.dictionary.forms import *
from signbank.dictionary.views import feature_search
from signbank.dictionary.adminviews import GlossListView, GlossDetailView
... |
"""This file contains code for use with "Think Stats",
by Allen B. Downey, available from greenteapress.com
Copyright 2014 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
"""
from __future__ import print_function
import pandas
import numpy as np
import statsmodels.formula.api as smf
import t... |
"""Tests for MultivariateNormal."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from scipy import stats
import tensorflow as tf
distributions = tf.contrib.distributions
class MultivariateNormalShapeTest(tf.test.TestCase):
def _t... |
"""
Unit tests for the `iris.fileformats.grib.message._MessageLocation` class.
"""
from __future__ import (absolute_import, division, print_function)
from six.moves import (filter, input, map, range, zip) # noqa
# Import iris.tests first so that some things can be initialised before
# importing anything else.
impor... |
"""
Views for Instances and Volumes.
"""
from django.utils.translation import ugettext_lazy as _
from horizon import tabs
from openstack_dashboard.dashboards.project.access_and_security \
import tabs as project_tabs
class IndexView(tabs.TabbedTableView):
tab_group_class = project_tabs.AccessAndSecurityTabs... |
class SQLParseError(Exception):
pass
class UnclosedQuoteError(SQLParseError):
pass
# maps a type of identifier to the maximum number of dot levels that are
# allowed to specify that identifier. For example, a database column can be
# specified by up to 4 levels: database.schema.table.column
_PG_IDENTIFIER_... |
import unittest
import shelve
import glob
from test import support
from collections.abc import MutableMapping
from test.test_dbm import dbm_iterator
def L1(s):
return s.decode("latin-1")
class byteskeydict(MutableMapping):
"Mapping that supports bytes keys"
def __init__(self):
self.d = {}
de... |
#!/usr/bin/env python
import copy
import logging
import os
import re
from fuzzywuzzy import fuzz as fw_fuzz
from textblob import TextBlob
from ansibullbot.parsers.botmetadata import BotMetadataParser
from ansibullbot.utils.systemtools import run_command
from ansibullbot.utils.moduletools import ModuleIndexer
import... |
{
'name': 'Belgium - Structured Communication',
'version': '1.2',
'license': 'AGPL-3',
'author': 'Noviat',
'website': 'https://www.odoo.com/page/accounting',
'category' : 'Localization',
'description': """
Belgian localization for in- and outgoing invoices (prereq to account_coda):
====... |
import json
import logging
from functools import partial
from django.contrib.auth.models import User
from django.test import TestCase
from django.test.client import RequestFactory
from django.core.urlresolvers import reverse
from foldit.views import foldit_ops, verify_code
from foldit.models import PuzzleComplete, Sc... |
import types
import inspect
import re
import traceback
from lib.jsonrpclib import config
iter_types = [
types.DictType,
types.ListType,
types.TupleType
]
string_types = [
types.StringType,
types.UnicodeType
]
numeric_types = [
types.IntType,
types.LongType,
types.FloatType
]
value_t... |
import glob
from optparse import OptionParser
import subprocess
import os
import os.path
import shutil
import sys
version = 'build-all.py, version 0.01'
build_dir = '../all-kernels'
make_command = ["vmlinux", "modules"]
make_env = os.environ
make_env.update({
'ARCH': 'arm',
'CROSS_COMPILE': 'arm-none-... |
import os.path
import sys
# Django settings for example_project project.
DEBUG = True
TEMPLATE_DEBUG = True
ADMINS = (
# ('Your Name', '<EMAIL>'),
)
INTERNAL_IPS = ('127.0.0.1',)
MANAGERS = ADMINS
PROJECT_ROOT = os.path.dirname(__file__)
sys.path.insert(0, os.path.abspath(os.path.join(PROJECT_ROOT, '..')))
D... |
"""Add things to old Pythons so I can pretend they are newer."""
# This file does lots of tricky stuff, so disable a bunch of lintisms.
# pylint: disable=F0401,W0611,W0622
# F0401: Unable to import blah
# W0611: Unused import blah
# W0622: Redefining built-in blah
import os, sys
# Python 2.3 doesn't have `set`
try:
... |
import json
import struct
import os
extra_info = [0 for x in range(10000)]
extra_data = open("./extra_data", "r")
for line in extra_data:
line = line.rstrip()
numeroMapa = line.split('=')[0]
data = line.split('=')[1]
extra_info[int(numeroMapa)] = data
def getExtraData (mapa):
return extra_info[mapa]
for fn i... |
from TheCannon import apogee
from TheCannon import dataset
import numpy as np
from TheCannon import model
tr_ID, wl, tr_flux, tr_ivar = apogee.load_spectra("/Users/caojunzhi/Downloads/example_DR10/Data")
tr_label = apogee.load_labels("/Users/caojunzhi/Downloads/example_DR10/reference_labels.csv")
test_ID = tr_ID
te... |
import gensim
import numpy as np
from scipy.stats.stats import spearmanr
# global parameters for word2vec
ALPHA = 0.01 # initial learning rate, drops to min_alpha
MIN_ALPHA = 0.0001
CBOW_MEAN = 1 # http://stackoverflow.com/questions/34249586/the-accuracy-test-of-word2vec-in-gensim
... |
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
"""
Verify basic operation of the SideEffect() method, using a "log
file" as the side effect "target."
"""
import os.path
import string
import TestSCons
test = TestSCons.TestSCons()
test.write('SConstruct', """\
def copy(source, target):
open(target... |
#-*- coding: utf-8 -*-
import usaio
''' добавляет строку в фиксирванный файл '''
def printStrToFile(string, fname):
filename = fname
# Create a file object:
# in "write" mode
FILE = open(filename,"at")
# Write all the lines at once:
FILE.writelines(string)
# Alternatively write them one by one:
FILE.clos... |
''' unit test template for ONTAP Ansible module '''
from __future__ import print_function
import json
import pytest
from units.compat import unittest
from units.compat.mock import patch, Mock
from ansible.module_utils import basic
from ansible.module_utils._text import to_bytes
import ansible.module_utils.netapp as n... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
import fnmatch
import traceback
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ovirt import (
check_sdk,
create_connection,
get_dict_o... |
import webbrowser
from time import sleep
from os import environ
import requests
application_id = environ.get('O365_APP_ID')
secret = environ.get('O365_APP_SECRET')
tenant_id = environ.get('O365_APP_TENANT_ID')
headers = {'Content-type': 'application/json'}
payload = {'grant_type': 'client_credentials',
'... |
""" Backend base class
The class provides the contract for backend modules
implementing the provisioning of dynamic resources.
"""
from ipaqe_provision_hosts.errors import IPAQEProvisionerError
NOT_IMPLEMENTED_MSG = "You need to override this method in a subclass"
class VMsNotCreatedError(IPAQEProvisionerError):
... |
"""Self-test suite for Crypto.Cipher.Blowfish"""
import unittest
from Crypto.Util.py3compat import bchr
from Crypto.Cipher import Blowfish
# This is a list of (plaintext, ciphertext, key) tuples.
test_data = [
# Test vectors from http://www.schneier.com/code/vectors.txt
('0000000000000000', '4ef997456198dd7... |
"""MongoDB event tracker backend."""
from __future__ import absolute_import
import logging
import pymongo
from pymongo import MongoClient
from pymongo.errors import PyMongoError
from track.backends import BaseBackend
log = logging.getLogger(__name__)
class MongoBackend(BaseBackend):
"""Class for a MongoDB e... |
from __future__ import print_function
import binascii
import io
import os
import colorama
import pytest
import sh
from molecule import util
colorama.init(autoreset=True)
def test_print_debug(capsys):
util.print_debug('test_title', 'test_data')
result, _ = capsys.readouterr()
title = [
colorama... |
from vtdb import dbexceptions
# A simple class to trap and re-export only variables referenced from
# the sql statement since bind dictionaries can be *very* noisy. This
# is a by-product of converting the DB-API %(name)s syntax to our
# :name syntax.
class BindVarsProxy(object):
def __init__(self, bind_vars):
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("order", "0008_auto_20151026_0820")]
operations = [
migrations.RenameField(
model_name="order", old_name="total", new_name="to... |
from openerp import api
from openerp.fields import Integer, One2many, Html
from openerp.osv import fields, osv
from openerp.tools.translate import _
import openerp.addons.decimal_precision as dp
class product_template(osv.osv):
_inherit = 'product.template'
_columns = {
'event_ok': fields.boolean('Even... |
from __future__ import absolute_import, division, unicode_literals
from pip._vendor.six import text_type
from . import base
from ..constants import namespaces, voidElements
from ..constants import spaceCharacters
spaceCharacters = "".join(spaceCharacters)
class Filter(base.Filter):
"""Lints the token stream fo... |
# -*- coding: utf-8 -*-
import fcntl
import json
import os
import psutil
import stat
import signal
import sys
import time
import threading
class Monitor:
def __init__(self, app, filename):
self.app = app
self.pid = os.getpid()
self.filename = filename
self.thread = False
se... |
from __future__ import print_function
import os
import numpy as np
from .yambofile import *
class YamboFolder():
"""
Takes as input a folder name that is the folder where yambo saved r-* o-* l-* and netcdf files
"""
def __init__(self,path):
"""
List all the files in the folder and to e... |
import os
import urllib
import docker
from docker.models.containers import Container
from testcontainers.core.utils import inside_container
from testcontainers.core.utils import default_gateway_ip
class DockerClient(object):
def __init__(self):
self.client = docker.from_env()
def run(self, image: str... |
"""Base class for all OpenGLContext event objects."""
class Event(object):
"""Base class for all local event objects.
This is an abstract class from which all local event objects are
derived. It defines the base API for each event type, as understood
by the event dispatch system.
Attributes:
... |
import os
import time
import base64
import hashlib
import datetime
from django.db import models
from django.contrib.auth.models import User
class RequestToken(models.Model):
user = models.ForeignKey(User)
token = models.CharField(max_length=64)
expires = models.DateTimeField()
@classmethod
def ... |
from misago.utils.fixtures import load_settings_fixture, update_settings_fixture
from misago.utils.translation import ugettext_lazy as _
settings_fixture = (
# Register and Sign-In Settings
('accounts', {
'name': _("Users Accounts Settings"),
'description': _("Those settings allow you to increa... |
import os
import tika
from tika import parser
tika.initVM()
def get_metadata_score(metadata):
score = 0
for field in metadata.keys():
field = field.lower()
if "description" in field:
score += 1 / 3
if "title" in field or "name" in field:
score += 1 / 3
... |
from __future__ import absolute_import
from collections import Mapping, MutableMapping
try:
from threading import RLock
except ImportError: # Platform-specific: No threads available
class RLock:
def __enter__(self):
pass
def __exit__(self, exc_type, exc_value, traceback):
... |
#!/usr/bin/env python
#Module to generate a map based on places you're interested in
#from your Firefox History
# mruttley - 2015-04-14
from json import load, dumps
from codecs import open as copen
from re import findall
from collections import defaultdict
from os import listdir, path
from sqlite3 import connect
from... |
# -*- coding: utf-8 -*-
#!/usr/bin/python
"""Test of line navigation output of Firefox on a page with headings
in sections.
"""
from macaroon.playback import *
import utils
sequence = MacroSequence()
########################################################################
# We wait for the focus to be on a blank Fi... |
"""Constants and membership tests for ASCII characters"""
NUL = 0x00 # ^@
SOH = 0x01 # ^A
STX = 0x02 # ^B
ETX = 0x03 # ^C
EOT = 0x04 # ^D
ENQ = 0x05 # ^E
ACK = 0x06 # ^F
BEL = 0x07 # ^G
BS = 0x08 # ^H
TAB = 0x09 # ^I
HT = 0x09 # ^I
LF = 0x0a # ^J
NL =... |
# Description: Shows how to use value transformers
# Category: preprocessing
# Classes: TransformValue, Continuous2Discrete, Discrete2Continuous, MapIntValue
# Uses:
# Referenced:
import orange
print
def printExample(ex):
for val in ex:
print "%16s: %s" % (val.variable.name, val)
data = or... |
# -*- coding: utf-8 -*-
"""
gaefy.db.unique_model
~~~~~~~~~~~~~~~~~~~~~
A Model mixin that validates unique properties.
One limitation is that the entity with unique properties *must have* a
key_name. Example:
class MyModel(UniqueModelMixin, db.Model):
# Define a list of uniqu... |
import SoftLayer
class NodesV1(object):
def on_get(self, req, resp):
client = req.env['sl_client']
hardware = SoftLayer.HardwareManager(client)
nodes = []
hw_items = set([
'id',
'hostname',
'domain',
'hardwareStatus',
'gl... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Bunch is a subclass of dict with attribute-style access.
>>> b = Bunch()
>>> b.hello = 'world'
>>> b.hello
'world'
>>> b['hello'] += "!"
>>> b.hello
'world!'
>>> b.foo = Bunch(lol=True)
>>> b.foo.lol
True
>>> b.foo is b['... |
import hashlib, os
from .main import read, translate
from .jvm.optimization import options
# Hash outputs of all tests in order to easily detect changes between versions
fullhash = b''
for i in range(1, 7):
name = 'test{}'.format(i)
print(name)
dir = os.path.join('tests', name)
rawdex = read(os.path.... |
from setuptools import setup, find_packages
import os
import cms
CLASSIFIERS = [
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independ... |
"""Tests for the lms module itself."""
import mimetypes
from mock import patch
from django.test import TestCase
from django.core.urlresolvers import reverse
from edxmako import add_lookup, LOOKUP
from lms import startup
from xmodule.modulestore.tests.factories import CourseFactory
from xmodule.modulestore.tests.djan... |
from openerp.osv import osv, fields, orm
from datetime import datetime, date, timedelta
from openerp.tools.translate import _
class school_school(osv.osv):
_name = 'school.school'
school_school()
class school_teacher(osv.osv):
_name = "school.teacher"
_inherits = {'res.users' : 'user_id',}
_columns =... |
from test import support
import types
import unittest
def global_function():
def inner_function():
class LocalClass:
pass
global inner_global_function
def inner_global_function():
def inner_function2():
pass
return inner_function2
... |
#!/usr/bin/python
# coding=utf-8
from test import CollectorTestCase
from test import get_collector_config
from mock import patch
import os
from diamond.collector import Collector
from gridengine import GridEngineCollector
class TestGridEngineCollector(CollectorTestCase):
"""Set up the fixtures for the test
... |
class MergeDict(object):
"""
A simple class for creating new "virtual" dictionaries that actually look
up values in more than one dictionary, passed in the constructor.
If a key appears in more than one of the given dictionaries, only the
first occurrence will be used.
"""
def __init__(self... |
"""define Hdfs as subclass of Service"""
# -*- python -*-
import os
from service import *
from hodlib.Hod.nodePool import *
from hodlib.Common.desc import CommandDesc
from hodlib.Common.util import get_exception_string, parseEquals
class HdfsExternal(MasterSlave):
"""dummy proxy to external HDFS instance"""
de... |
"""Vector Student's t distribution classes."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.distributions.python.ops import bijectors
from tensorflow.contrib.distributions.python.ops import distribution_util
from tensorflow.contri... |
"""
The I{sudsobject} module provides a collection of suds objects
that are primarily used for the highly dynamic interactions with
wsdl/xsd defined types.
"""
from suds import *
from logging import getLogger
log = getLogger(__name__)
def items(sobject):
"""
Extract the I{items} from a suds object much like... |
import Framework
import github
import datetime
class AuthenticatedUser(Framework.TestCase):
def setUp(self):
Framework.TestCase.setUp(self)
self.user = self.g.get_user()
def testAttributes(self):
self.assertEqual(self.user.avatar_url, "https://secure.gravatar.com/avatar/b68de5ae38616... |
import cherrypy
from cherrypy.lib import httpauth
def check_auth(users, encrypt=None, realm=None):
"""If an authorization header contains credentials, return True, else False."""
request = cherrypy.serving.request
if 'authorization' in request.headers:
# make sure the provided credentials are corr... |
from __future__ import unicode_literals
from django.forms import MultipleChoiceField, ValidationError
from django.test import SimpleTestCase
class MultipleChoiceFieldTest(SimpleTestCase):
def test_multiplechoicefield_1(self):
f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two')])
with sel... |
from .fish import Fish
class Salmon(Fish):
"""Salmon.
:param species:
:type species: str
:param length:
:type length: float
:param siblings:
:type siblings: list of :class:`Fish
<fixtures.acceptancetestsbodycomplex.models.Fish>`
:param fishtype: Polymorphic Discriminator
:typ... |
# coding: utf-8
from __future__ import unicode_literals
import re
import os.path
from .common import InfoExtractor
from ..compat import (
compat_urllib_parse,
compat_urllib_request,
)
from ..utils import (
ExtractorError,
)
class PlayedIE(InfoExtractor):
IE_NAME = 'played.to'
_VALID_URL = r'http... |
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
try:
import json
except ImportError:
try:
import simplejson as json
except ImportError:
# Let snippet from module_utils/basic.py return a proper error in this ca... |
"""
Sphinx plugins for Django documentation.
"""
import json
import os
import re
from sphinx import addnodes, __version__ as sphinx_ver
from sphinx.builders.html import StandaloneHTMLBuilder
from sphinx.writers.html import SmartyPantsHTMLTranslator
from sphinx.util.console import bold
from sphinx.util.compat import Di... |
"""Use the HTMLParser library to parse HTML files that aren't too bad."""
__all__ = [
'HTMLParserTreeBuilder',
]
from HTMLParser import (
HTMLParser,
HTMLParseError,
)
import sys
import warnings
# Starting in Python 3.2, the HTMLParser constructor takes a 'strict'
# argument, which we'd like to s... |
from . import docx, conversion, options, images, transforms, underline
from .raw_text import extract_raw_text_from_element
from .docx.style_map import write_style_map, read_style_map
__all__ = ["convert_to_html", "extract_raw_text", "images", "transforms", "underline"]
_undefined = object()
def convert_to_html(*ar... |
import rope.base.codeanalyze
import rope.base.evaluate
import rope.base.pyobjects
from rope.base import taskhandle, exceptions, worder
from rope.contrib import fixsyntax
from rope.refactor import occurrences
def find_occurrences(project, resource, offset, unsure=False, resources=None,
in_hierarch... |
from test.test_support import verbose, run_unittest, import_module
#Skip these tests if either fcntl or termios is not available
fcntl = import_module('fcntl')
import_module('termios')
import errno
import pty
import os
import sys
import select
import signal
import socket
import unittest
TEST_STRING_1 = "I wish to bu... |
# Reading old ASAP files (version 1.X NetCDF files).
"""Asap.IO.ReadOldFiles reads NetCDF files from ASAP version 1.X.
The following functions are defined:
`Reader(filename)`:
An object for reading old-style (ASAP 1.x) NetCDF files.
`Reader.Read(frame = None)`:
Read a given frame into an ASAP ListOfAtoms object. T... |
# -*- coding: utf-8 -*-
import uuid
from datetime import datetime
from django.conf import settings
from django.contrib import auth, messages
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth.models import User
from django.core.mail import send_mail
from django.sho... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.