content stringlengths 4 20k |
|---|
from __future__ import print_function
from frappe.utils.selenium_testdriver import TestDriver
import unittest
import time, os
class TestToDo(unittest.TestCase):
def setUp(self):
self.driver = TestDriver()
def test_todo(self):
self.driver.login()
# list view
self.driver.set_route('List', 'ToDo')
time.sle... |
# -*- encoding: utf-8 -*-
import urllib2
import csv
from util import *
BGCOLOR_1 = '#ffffff'
BGCOLOR_2 = '#eafcf2'
def macro_ListEquipsInCategory(macro, _trailing_args=[]):
request = macro.request
formatter = macro.formatter
parser = macro.parser
requested_cat = _trailing_args[0] if len(_trailing_a... |
import errno
import os
import tempfile
from django.conf import settings
from django.contrib.sessions.backends.base import SessionBase, CreateError
from django.core.exceptions import SuspiciousOperation, ImproperlyConfigured
class SessionStore(SessionBase):
"""
Implements a file based session store.
"""
... |
"""Tests for the distance matrix module."""
import googlemaps
import responses
import test as _test
class DistanceMatrixTest(_test.TestCase):
def setUp(self):
self.key = 'AIzaasdf'
self.client = googlemaps.Client(self.key)
@responses.activate
def test_basic_params(self):
response... |
"""Production settings and globals."""
from __future__ import absolute_import
from os import environ
from .base import *
# Normally you should not import ANYTHING from Django directly
# into your settings, but ImproperlyConfigured is an exception.
from django.core.exceptions import ImproperlyConfigured
DEBUG=True
... |
import tempfile
from django.conf import settings
from django.core.files.uploadedfile import InMemoryUploadedFile # noqa
from django.core.urlresolvers import reverse
from django.forms.widgets import HiddenInput # noqa
from django import http
from django.test.utils import override_settings
from mox3.mox import IsA #... |
import os, sys, time
from pprint import pformat
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir, 'common')))
import workload_runner, rdb_unittest, scenario_common, utils, vcoptparse
from utils import print_with_time
op = vcoptparse.OptParser()
workload_runner.prepare_option_pars... |
"""Tests for ast_util module."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import ast
import collections
import textwrap
from tensorflow.contrib.autograph.pyct import anno
from tensorflow.contrib.autograph.pyct import ast_util
from tensorflow.contrib... |
import netrc, os, unittest, sys, textwrap
from test import test_support
temp_filename = test_support.TESTFN
class NetrcTestCase(unittest.TestCase):
def tearDown(self):
os.unlink(temp_filename)
def make_nrc(self, test_data):
test_data = textwrap.dedent(test_data)
mode = 'w'
if... |
from array import array
from collections import Mapping
from operator import itemgetter
import numpy as np
import scipy.sparse as sp
from ..base import BaseEstimator, TransformerMixin
from ..externals import six
from ..externals.six.moves import xrange
from ..utils import check_array, tosequence
from ..utils.fixes im... |
""" Handlers for OpenID Connect provider. """
from django.conf import settings
from django.core.cache import cache
from xmodule.modulestore.django import modulestore
from courseware.access import has_access
from openedx.core.djangoapps.user_api.models import UserPreference
from student.models import anonymous_id_for_... |
import copy
from bashlex import ast, flags, tokenizer, errors
def _recursiveparse(parserobj, base, sindex, tokenizerargs=None):
# TODO: fix this hack that prevents mutual import
from bashlex import parser
tok = parserobj.tok
if tokenizerargs is None:
tokenizerargs = {'parserstate' : copy.cop... |
#!/usr/bin/env python
import pytest
import pdb
import pprint
pp = pprint.PrettyPrinter(indent=4).pprint
def contains_only_unique_chars(chars, max_count=1):
"""Check a string for unique charachters
Arguments:
chars: the string to be checked
max_count: the number of allowed duplicates
... |
"""This code example gets all active creative wrappers.
To create creative wrappers, run create_creative_wrappers.py.
The LoadFromStorage method is pulling credentials and properties from a
"googleads.yaml" file. By default, it looks for this file in your home
directory. For more information, see the "Caching authent... |
from __future__ import division, absolute_import, unicode_literals
from functools import partial
import errno
import os
from os.path import join
import subprocess
import threading
from . import core
from .compat import int_types
from .compat import ustr
from .compat import WIN32
from .decorators import memoize
from .i... |
__all__ = [ 'DbResourceWdg']
import types
import os
from pyasm.common import Container, Environment
from pyasm.biz import Project
from pyasm.search import Sql, Search, SearchType, DbResource, DbContainer
from pyasm.web import WebContainer, Widget, HtmlElement, DivWdg, Table
from pyasm.widget import IconWdg, RadioWdg,... |
"""
COMMAND-LINE SPECIFIC STUFF
=============================================================================
"""
import markdown
import sys
import optparse
import logging
from logging import DEBUG, INFO, CRITICAL
logger = logging.getLogger('MARKDOWN')
def parse_options():
"""
Define and parse `optparse` ... |
import os
import tempfile
import shutil
import unittest
import pkg_resources
from setuptools.command import egg_info
ENTRIES_V10 = pkg_resources.resource_string(__name__, 'entries-v10')
"An entries file generated with svn 1.6.17 against the legacy Setuptools repo"
class TestEggInfo(unittest.TestCase):
def setUp... |
{
'name': 'Office Automation (CRM setup)',
'version': '1.0',
'category': 'Tools',
'description': """This module create a new Menu with all your meetings, scheduled calls, assigned leads and opportunities.""",
'author': 'Elico Corp',
'website': 'http://www.openerp.net.cn/',
'depends': ['crm', ... |
"""Unit tests for RenderedTaskInstanceFields."""
import os
import unittest
from datetime import date, timedelta
from unittest import mock
from parameterized import parameterized
from airflow import settings
from airflow.models import Variable
from airflow.models.dag import DAG
from airflow.models.renderedtifields im... |
# -*- coding: utf-8 -*-
"""
The Pygments reStructuredText directive
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This fragment is a Docutils_ 0.5 directive that renders source code
(to HTML only, currently) via Pygments.
To use it, adjust the options below and copy the code into a module
that you i... |
from case5_19 import *
class Case5_20(Case5_19):
DESCRIPTION = """Same as Case 5.19, but send all frames with SYNC = True.
Note, this does not change the octets sent in any way, only how the stream
is chopped up on the wire."""
EXPECTATION = """Same as Case 5.19. Implementations must be agnostic ... |
import inspect
import typing as tp
from inspect import Parameter
def extract_type_signature_from(fun: tp.Callable) -> tp.Tuple[type, ...]:
sign = []
params = inspect.signature(fun).parameters
for parameter in params.values():
if parameter.kind in (Parameter.POSITIONAL_ONLY, Parameter.POSITIONAL_OR... |
from __future__ import unicode_literals
import datetime
import os
import subprocess
from django.utils.lru_cache import lru_cache
def get_version(version=None):
"Returns a PEP 386-compliant version number from VERSION."
version = get_complete_version(version)
# Now build the two parts of the version num... |
input = """
% Simplified version of a program by Michael Fink, which segfaults
% with the Jun 11 2001 Release.
object(o1,4).
object(o2,5).
object(o3,17).
bid(1,14).
bid(2,34).
bid(3,14).
contains(1,o1,2).
contains(1,o2,4).
contains(1,o3,2).
contains(2,o3,10).
contains(3,o2,5).
%#maxint=62.
selec... |
__author__ = 'luogangyi'
#
# Copyright 2011-2014 Red Hat, Inc.
#
# This program 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 later version.
#
# Thi... |
# errorSemantics.py
# Test the Python error handling semantics. Specifically:
#
# * When a Python COM object is called via IDispatch, the nominated
# scode is placed in the exception tuple, and the HRESULT is
# DISP_E_EXCEPTION
# * When the same interface is called via IWhatever, the
# nominated scode is retur... |
"""
Tests for views/tools.py.
"""
import datetime
import mock
import json
import unittest
from django.utils.timezone import utc
from django.test.utils import override_settings
from nose.plugins.attrib import attr
from courseware.field_overrides import OverrideFieldData
from lms.djangoapps.ccx.tests.test_overrides im... |
# We register a custom Python signal handler here for the following reasons.
#
# 1. We are running R and Python together within the same process.
# Interrupts should be handled by whichever process appears to
# be at the foreground.
#
# 2. To facilitate this, we need to register a SIGINT handler at
# the ... |
from django.utils.datastructures import SortedDict
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import tabs
from openstack_dashboard import api
from openstack_dashboard.dashboards.project.volumes.backups \
import tables as backups_tables
from openstack_dashb... |
"""
Example
Description:
Create a Maya Mesh using OpenMaya
in Maya's python editor :
import example_createMesh
reload(example_createMesh)
example_createMesh.readPolyFile('/host/devel/rtc3/trees/dev/amber/bin/pbr2/script')
"""
from maya import OpenMaya as om
from itertools import chain
import m... |
import re
class Reindeer(object):
def __init__(self, name, speed, flight_time, rest_time):
self.name = name
self.speed = int(speed)
self.flight_time = int(flight_time)
self.rest_time = int(rest_time)
def dist(self, time):
cycle_time = self.flight_time + self.rest_time... |
#!/usr/bin/env python
"""
Determines the contribution of different subcomponents of a file to its file size, serialization time,
and deserialization time.
"""
from __future__ import print_function
import sys
from pylearn2.utils import serial
try:
import cPickle
except ImportError:
import pickle as cPickle
impo... |
import ConfigParser
from contextlib import closing
import json
from pprint import pprint
import MySQLdb
from MySQLdb.cursors import DictCursor
def safe_db_call(f):
def wrapper(self, *args, **kwargs):
try:
return f(self, *args, **kwargs)
finally:
self.disconnect()
retur... |
import moose
import pylab
import rdesigneur as rd
rdes = rd.rdesigneur(
elecDt = 50e-6,
chemDt = 0.002,
chemPlotDt = 0.002,
# cellProto syntax: ['somaProto', 'name', dia, length]
cellProto = [['somaProto', 'soma', 12e-6, 12e-6]],
chemProto = [['./chem/chanPhosphByCaMKII.g', 'chem']],
chanPro... |
import itertools
import json
import os.path
import re
import sys
from json_parse import OrderedDict
# This file is a peer to json_schema.py. Each of these files understands a
# certain format describing APIs (either JSON or IDL), reads files written
# in that format into memory, and emits them as a Python array of ob... |
import os.path
import sickbeard
from sickbeard import helpers, logger, exceptions
from sickbeard import encodingKludge as ek
from sickbeard.metadata.generic import GenericMetadata
from lib.hachoir_parser import createParser
from lib.hachoir_metadata import extractMetadata
class ImageCache:
def __init__(self):... |
from packetbeat import BaseTest
"""
Tests for the mysql's send_request and send_response
options.
"""
class Test(BaseTest):
def test_default_settings(self):
"""
Should not include request and response by
default.
"""
self.render_config_template(
mysql_ports=[3... |
"""Sanity test for documentation of sanity tests."""
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
from ..sanity import (
SanityVersionNeutral,
SanityMessage,
SanityFailure,
SanitySuccess,
sanity_get_tests,
)
from ..config import (
SanityCon... |
"""
Renumbers atom serials in the PDB file starting from a given value (default 1).
Usage:
python pdb_reatom.py -<number> <pdb file>
Example:
python pdb_reatom.py -10 1CTF.pdb # renumbers from 10
python pdb_reatom.py --1 1CTF.pdb # renumbers from -1
This program is part of the `pdb-tools` suite of util... |
"""
Utility functions for batch-processing sentences: parsing and
extraction of the semantic representation of the root node of the the
syntax tree, followed by evaluation of the semantic representation in
a first-order model.
"""
import evaluate
import re
############################################################... |
import sys
import subprocess
try:
import json
except ImportError:
import simplejson as json
import killableprocess
class GitError(Exception):
pass
def git(command, *args):
command_line = ["git", command] + list(args)
sys.stderr.write("Running command %s\n"%" ".join(command_line))
proc = killa... |
{
'name': 'Portal Stock',
'version': '0.1',
'category': 'Tools',
'complexity': 'easy',
'description': """
This module adds access rules to your portal if stock and portal are installed.
==========================================================================================
""",
'author': ... |
import os
from zope.interface import implements, Interface, Attribute
from twisted.internet import defer
from twisted.python import failure, log
from twisted.cred import error, credentials
class ICredentialsChecker(Interface):
"""
An object that can check sub-interfaces of ICredentials.
"""
creden... |
#!/bin/bash
import socket
import subprocess
import ipaddress
import nmap
import pexpect
from core.flowcontrol import WriteFileFunction
# Function to parse raw NMAP results into readable format
def reportscan(argument, IP):
output = " "
nm = nmap.PortScanner()
nm.scan(hosts=IP, arguments=argument)
output += (nm.com... |
import re
import pep8
"""
Guidelines for writing new hacking checks
- Use only for Glance-specific tests. OpenStack general tests
should be submitted to the common 'hacking' module.
- Pick numbers in the range G3xx. Find the current test with
the highest allocated number and then pick the next value.
If n... |
# -*- coding: utf-8 -*-
import unittest
from mongoengine import Document, connect
from mongoengine.connection import get_db
from mongoengine.fields import StringField
__all__ = ('TurnOffInheritanceTest', )
class TurnOffInheritanceTest(unittest.TestCase):
def setUp(self):
connect(db='mongoenginetest')
... |
from warnings import catch_warnings
import numpy as np
import pytest
from pandas.core.dtypes import generic as gt
import pandas as pd
import pandas._testing as tm
class TestABCClasses:
tuples = [[1, 2, 2], ["red", "blue", "red"]]
multi_index = pd.MultiIndex.from_arrays(tuples, names=("number", "color"))
... |
from sklearn.model_selection import train_test_split
from sklearn.metrics import f1_score
import data_parser
class BaseModel:
def __init__(self, model):
self.model = model
def train(self):
return self.model.fit(self.x_train, self.y_train)
class SupervisedBinaryClassificationModel(BaseModel)... |
#!/usr/bin/env python
#
# Wrapper script for Java Conda packages that ensures that the java runtime
# is invoked with the right options. Adapted from the bash script (http://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-stored-in/246128#246128).
#
# Program Parameters
#
import os
import s... |
from django.conf import settings
from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.generic.simple import direct_to_template
# Enable the django admin
admin.autodiscover()
urlpatterns = pat... |
import sqlalchemy as sa
from sqlalchemy import orm
from neutron.api.v2 import attributes as attr
from neutron.db import db_base_plugin_v2
from neutron.db import model_base
from neutron.db import models_v2
from neutron.extensions import allowedaddresspairs as addr_pair
class AllowedAddressPair(model_base.BASEV2):
... |
from weboob.capabilities.video import BaseVideo
class NolifeTVVideo(BaseVideo):
def __init__(self, *args, **kwargs):
BaseVideo.__init__(self, *args, **kwargs)
self.ext = u'mp4'
@classmethod
def id2url(cls, _id):
return u'http://mobile.nolife-tv.com/online/emission-%s/' % _id |
import sys
import logging
LOG_NOTSET = 'notset'
LOG_DEBUG = 'debug'
LOG_TEST = 'test'
LOG_INFO = 'info'
LOG_WARNING = 'warn'
LOG_ERROR = 'error'
LOG_CRITICAL = 'critical'
logging.TEST = logging.INFO - 5
logging.addLevelName(logging.TEST, 'TEST')
_logger = logging.getLogger(__name__)
class Logger(object):
def __... |
# Code for loading and accessing binwalk settings (extraction rules, signature files, etc).
import os
import binwalk.core.common as common
from binwalk.core.compat import *
class Settings:
'''
Binwalk settings class, used for accessing user and system file paths and general configuration settings.
Af... |
from __future__ import absolute_import, division, print_function
import abc
import six
from cryptography import utils
@six.add_metaclass(abc.ABCMeta)
class EllipticCurve(object):
@abc.abstractproperty
def name(self):
"""
The name of the curve. e.g. secp256r1.
"""
@abc.abstractp... |
# -*- coding: utf-8 -*-
"""
kaftools.utils.shortcuts
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This module provides utility functions that are used within
kaftools that can be useful for external scripts.
"""
import time
import re
import numpy as np
import matplotlib.pyplot as plt
def plot_series(data, prediction, **kwargs... |
__all__ = [
'HTML5TreeBuilder',
]
import warnings
from bs4.builder import (
PERMISSIVE,
HTML,
HTML_5,
HTMLTreeBuilder,
)
from bs4.element import NamespacedAttribute
import html5lib
from html5lib.constants import namespaces
from bs4.element import (
Comment,
Doctype,
NavigableStr... |
import os
import unittest
import random
from test import support
thread = support.import_module('_thread')
import time
import sys
import weakref
from test import lock_tests
NUMTASKS = 10
NUMTRIPS = 3
_print_mutex = thread.allocate_lock()
def verbose_print(arg):
"""Helper function for printing out debugging outp... |
from django.dispatch import Signal
post_vc_update = Signal(providing_args=["oldstats", "remotestats", "newstats"])
post_vc_commit = Signal(providing_args=["store", "stats", "user", "success"])
post_template_update = Signal(providing_args=["oldstats", "newstats"])
post_file_upload = Signal(providing_args=["user", "olds... |
import sys, itertools
import _ast
def to_tuple(t):
if t is None or isinstance(t, (basestring, int, long, complex)):
return t
elif isinstance(t, list):
return [to_tuple(e) for e in t]
result = [t.__class__.__name__]
if hasattr(t, 'lineno') and hasattr(t, 'col_offset'):
result.app... |
"""cryptomath module
This module has basic math/crypto code."""
import os
import math
import base64
import binascii
# The sha module is deprecated in Python 2.6
try:
import sha
except ImportError:
from hashlib import sha1 as sha
# The md5 module is deprecated in Python 2.6
try:
import md5
except Import... |
ERROR_FIRST = 1000
HASHCHK = 1000
NISAMCHK = 1001
NO = 1002
YES = 1003
CANT_CREATE_FILE = 1004
CANT_CREATE_TABLE = 1005
CANT_CREATE_DB = 1006
DB_CREATE_EXISTS = 1007
DB_DROP_EXISTS = 1008
DB_DROP_DELETE = 1009
DB_DROP_RMDIR = 1010
CANT_DELETE_FILE = 1011
CANT_FIND_SYSTEM_REC = 1012
CANT_GET_STAT = 1013
CANT_GET_WD = 10... |
#
# Tools for the SIM method.
# pyplagia, Pierre-Antoine BRAMERET (C) 2014
import tokenize
import token
import keyword
import builtins
import io
from itertools import permutations
#-------------------------------------------------------------------------------
# This one is used by sim and ilar.
# ... |
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response
from nssrc.com.citrix.netscaler.nitro.service.options import options
from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_... |
import pydot
from keras.layers.core import Merge
from keras.models import Model
from collections import Counter
class Grapher(object):
def __init__(self):
self.names = {}
self.class_counts = Counter()
def get_name(self, model):
"""
returns the name of the model instance. If mo... |
""" Output file objects for generator. """
import difflib
import os
import time
import sys
from idl_log import ErrOut, InfoOut, WarnOut
from idl_option import GetOption, Option, ParseOptions
from stat import *
Option('diff', 'Generate a DIFF when saving the file.')
#
# IDLOutFile
#
# IDLOutFile provides a temporar... |
# pylint: skip-file
import sys
sys.path.append('../../python/')
import mxnet as mx
import logging
def ConvFactory(data, num_filter, kernel, stride=(1,1), pad=(0, 0), name=None, suffix=''):
conv = mx.symbol.Convolution(data=data, num_filter=num_filter, kernel=kernel, stride=stride, pad=pad, name='conv_%s%s' %(name,... |
#!/usr/bin/python -tt
__requires__='TurboGears >= 1.0.4'
import os
import re
import glob
import subprocess
import shutil
from distutils.command.build import build as _build
from distutils.command.install_data import install_data as _install_data
from distutils.dep_util import newer
from setuptools import setup, find_... |
"""
Waf tool for external builds with cmake. This tool defines the feature
'cmake_build', for building through the cmake interface.
You can use CMAKE_MIN_VERSION environment variable before loading this tool in
the configuration to set a minimum version required for cmake. Example::
def configure(cfg):
cf... |
"""A cache for operation filtering."""
import collections
from typing import Callable, Dict, Iterable, List, Optional
from tf_coder.value_search import value
class FilteredValuesCache(object):
"""A cache for operation filtering."""
def __init__(self) -> None:
# A map from filter functions and weights to as... |
text="""
#define FUNC$numR(m_r,m_func,$argt)\\
virtual m_r m_func($argtp) { \\
if (Thread::get_caller_ID()!=server_thread) {\\
m_r ret;\\
command_queue.push_and_ret( visual_server, &VisualServer::m_func,$argp,&ret);\\
return ret;\\
} else {\\
return visual_server->m_func($argp);\\
}\\
}
#define FUN... |
#!/usr/bin/python
import os
import mongo
class Subnets(mongo.Mongo):
@mongo.Format()
def subnetList(self, projection = { 'hosts': 0 }, format=False):
return self.searchDoc('subnets', {}, projection)
@mongo.Format()
def subnetAdd(self, subnet, description='', discovery=True, discoveryhost='lo... |
import os, sys, thread, time
sys.path.append(os.environ['PERF_EXEC_PATH'] + \
'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')
from perf_trace_context import *
from Core import *
from Util import *
usage = "perf trace -s sctop.py [comm] [interval]\n";
for_comm = None
default_interval = 3
interval = default_interv... |
'''Package with the specs for all supported APIs.''' |
'''*****************************************************************************
AToMPM - A Tool for Multi-Paradigm Modelling
Copyright (c) 2011 Raphael Mannadiar (<EMAIL>)
This file is part of AToMPM.
AToMPM is free software: you can redistribute it and/or modify it under the
terms of the GNU Lesser General Public ... |
"""Tests for the Bernoulli distribution."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib import distributions
from tensorflow.contrib.distributions.python.kernel_tests import distribution_test
from tensorflow.python.framework impo... |
from __future__ import with_statement
import os, sys
import py
needsdup = py.test.mark.skipif("not hasattr(os, 'dup')")
from py.builtin import print_
if sys.version_info >= (3,0):
def tobytes(obj):
if isinstance(obj, str):
obj = obj.encode('UTF-8')
assert isinstance(obj, bytes)
... |
from __future__ import absolute_import
from PyQt4.QtGui import QVBoxLayout
from PyQt4.QtGui import QHBoxLayout
from PyQt4.QtGui import QPushButton
from PyQt4.QtGui import QTreeWidget
from PyQt4.QtGui import QTreeWidgetItem
from PyQt4.QtGui import QDialog
from PyQt4.QtGui import QWidget
from PyQt4.QtGui import QLabel
f... |
def test():
a = 1
b = 2
c = 3
d = 4
i = 0
while i < 1e6:
# 100
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b
a = a; a = b; a = c; a = d; b = a... |
from __future__ import unicode_literals
from webnotes.model.doc import make_autoname
from webnotes.utils import cstr, cint, get_site_path,now
import datetime
"""
record of files
naming for same name files: file.gif, file-1.gif, file-2.gif etc
"""
import webnotes, webnotes.utils, os
from webnotes import conf
class Do... |
from . import ProgressiveTest, skip
from progressivis.storage.base import StorageEngine, Group, Dataset #, Attribute
from progressivis.table.table import Table
import numpy as np
@skip
class TestStorageEngine(ProgressiveTest):
def test_storage_engine(self):
e = StorageEngine.default
self.assertIs... |
from distutils.core import setup
import py2exe
manifest_template = '''
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity
version="5.0.0.0"
processorArchitecture="x86"
name="%(prog)s"
type="win32"... |
from openerp.osv import osv, fields
from openerp.tools.translate import _
from openerp import workflow
class sale_order_line_make_invoice(osv.osv_memory):
_name = "sale.order.line.make.invoice"
_description = "Sale OrderLine Make_invoice"
def _prepare_invoice(self, cr, uid, order, lines, context=None):
... |
import logging
from oslo_utils import timeutils
import six.moves.urllib.parse as urlparse
import swiftclient
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon.utils.memoized import memoized # noqa
from openstack_dashboard.api import... |
from mock import patch
from path import path
from path import Path
import pytest
import subprocess
import sys
# Add the hooks directory to the python path.
hooks_dir = Path('__file__').parent.abspath() / 'hooks'
sys.path.insert(0, hooks_dir.abspath())
# Import the module to be tested.
import kubernetes_installer
def... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from datetime import datetime
from ansible.plugins.callback import CallbackBase
class CallbackModule(CallbackBase):
"""
This callback module tells you how long your plays ran for.
"""
CALLBACK_VERSION = 2.0
C... |
#!/usr/bin/env python
"""
blogtool.py
The entry module for the blogtool command line utility.
Program initialization, option and file processing are all started from
here.
"""
from __version__ import __version__
from options import OptionProcessor
from headerparse import Header
import sys
import u... |
"""Create links in the HDF5 file.
This module implements containers for soft and external links. Hard
links doesn't need a container as such as they are the same as regular
nodes (groups or leaves).
Classes:
SoftLink
ExternalLink
Functions:
Misc variables:
"""
import os
import tables
from tables import ... |
"""Utill functions for distillation loss.
The distillation loss_fn will be called with the following:
Args:
dnn_logits: Tensor of logits from the dnn, treated as the "target". This will
be the output of a call to tf.stop_gradient().
tree_logits: Tensor of logits from the tree, treated as the "predictions".
... |
#!/usr/bin/env python
"""Populate template tracker with information based on cfme_data"""
import sys
import traceback
from collections import defaultdict
from threading import Lock, Thread
from slumber.exceptions import SlumberHttpBaseException
from cfme.utils import trackerbot, net
from cfme.utils.conf import cfme_d... |
"""Option type for true/false Variables.
Usage example::
opts = Variables()
opts.Add(BoolVariable('embedded', 'build for an embedded system', 0))
...
if env['embedded'] == 1:
...
"""
__all__ = ['BoolVariable',]
import SCons.Errors
__true_strings = ('y', 'yes', 'true', 't', '1', 'on' , 'all' )
... |
# -*- coding: utf-8 -*-
import time
import unittest2
import xmlrpclib
import openerp.tests.common
DB = openerp.tests.common.DB
class test_xmlrpc(openerp.tests.common.HttpCase):
def test_01_xmlrpc_login(self):
""" Try to login on the common service. """
uid = self.xmlrpc_common.login(DB, 'admin',... |
from sqlalchemy import *
from migrate import *
from migrate.changeset import schema
pre_meta = MetaData()
post_meta = MetaData()
config = Table('config', post_meta,
Column('id', Integer, primary_key=True, nullable=False),
Column('site_title', Text, nullable=False),
Column('site_display_name', Text, nullab... |
#!/usr/bin/env python
"""
Created on Sun Feb 21 14:45:34 2016
@author: Gus Segura
"""
# imports
import time
import random
import base64
import os
import sys
import math
import json
from collections import OrderedDict
# from kafka import SimpleProducer, KafkaClient
# kafka server info
# kafka = KafkaClient("localhost"... |
"""Test node responses to invalid locators.
"""
from test_framework.messages import msg_getheaders, msg_getblocks, MAX_LOCATOR_SZ
from test_framework.mininode import P2PInterface
from test_framework.test_framework import MachinecoinTestFramework
class InvalidLocatorTest(MachinecoinTestFramework):
def set_test_pa... |
"""
This module houses ctypes interfaces for GDAL objects. The following GDAL
objects are supported:
CoordTransform: Used for coordinate transformations from one spatial
reference system to another.
Driver: Wraps an OGR data source driver.
DataSource: Wrapper for the OGR data source object, supports
OGR-su... |
from django.db import models
from django.utils.translation import gettext_lazy as _
class Site(models.Model):
domain = models.CharField(max_length=100)
def __str__(self):
return self.domain
class Article(models.Model):
"""
A simple Article model for testing
"""
site = models.Foreign... |
import ConfigParser
import json
import os
import pprint
import requests
import sys
from akamai.edgegrid import EdgeGridAuth
def main(args):
if len(args) != 3:
print("usage: python purge.py [env] [url]")
print(
"example : python purge.py [prod|test] http://blog.mysite.com/")
sy... |
# -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsFilterLineEdit
.. note:: This program 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 later version.
"""
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.