content stringlengths 4 20k |
|---|
import os
import unittest2 as unittest
from webkitpy.common.system.outputcapture import OutputCapture
from webkitpy.tool.bot.irc_command import *
from webkitpy.tool.mocktool import MockTool
from webkitpy.common.net.web_mock import MockWeb
from webkitpy.common.system.executive_mock import MockExecutive
from webkitpy.co... |
#!/usr/bin/env python
# -*- coding: utf8 -*-
# *****************************************************************
# ** PTS -- Python Toolkit for working with SKIRT **
# ** © Astronomical Observatory, Ghent University **
# *****************************************************************
##... |
from tempest_lib import exceptions as lib_exc
from tempest.api.compute import base
from tempest.common.utils import data_utils
from tempest import test
class FlavorsExtraSpecsNegativeTestJSON(base.BaseV2ComputeAdminTest):
"""
Negative Tests Flavor Extra Spec API extension.
SET, UNSET, UPDATE Flavor Extr... |
#!/usr/bin/env python3
import sys
import signal
import gi
gi.require_version('Playerctl', '2.0')
from gi.repository import Playerctl, GLib
manager = Playerctl.PlayerManager()
loop = GLib.MainLoop()
def on_play(player, status, manager):
on_metadata(player, player.props.metadata, manager)
def on_metadata(player,... |
from ray.util.iter import ParallelIterator, from_iterators
class Dataset():
"""A simple Dataset abstraction for RaySGD.
This dataset is designed to work with RaySGD trainers (currently just
Torch) to provide support for streaming large external datasets, and built
in sharding.
.. code-block:: py... |
# coding: utf-8
#--------------//////////----------------------
#Projeto Criado por: Lário Diniz
#Contatos: <EMAIL>
#Data: 06/08/2015
#--------------//////////----------------------
from django.test import TestCase
from grimorio.core.models import Userc
class AboutTest(TestCase):
def setUp(self):
self... |
"""
Login page for Studio.
"""
from bok_choy.page_object import PageObject
from bok_choy.promise import EmptyPromise
from common.test.acceptance.pages.studio import BASE_URL
from common.test.acceptance.pages.studio.course_page import CoursePage
from common.test.acceptance.pages.studio.utils import HelpMixin
class Lo... |
"""
Find the number connected component in the undirected graph. Each node in the graph contains a label and a list of its
neighbors. (a connected component (or just component) of an undirected graph is a subgraph in which any two vertices are
connected to each other by paths, and which is connected to no additional ve... |
from __future__ import print_function
import subprocess # Needs Python 2.4
from indexed_search import DB
import psycopg2 as db2
CLUSTER_NAME = "base"
DATA_DIR = "/scratch2/postgres/data/%s" % CLUSTER_NAME
#DATA_DIR = "/var/lib/pgsql/data/%s" % CLUSTER_NAME
DSN = "dbname=%s port=%s"
CREATE_DB = "createdb %s"
DROP_DB =... |
import re
import sys
def negate(condition):
"""
Returns a CPP conditional that is the opposite of the conditional passed in.
"""
if condition.startswith('!'):
return condition[1:]
return "!" + condition
class Monitor:
"""
A simple C preprocessor that scans C source and computes, li... |
from hcsvlab_robochef.rdf.namespaces import *
NAMEMAP = {
'ambig-paragraph': ICEA.ambigparagraph,
'bold': ICEA.bold,
'byline': ICEA.byline,
'changed': ICEA.changed,
'corpus': ICEA.corpus,
'correction': ARTA.correction,
'deleted... |
# -*- coding: utf-8 -*-
"""
flask.sessions
~~~~~~~~~~~~~~
Implements cookie based sessions based on itsdangerous.
:copyright: (c) 2015 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
import uuid
import hashlib
import warnings
from base64 import b64encode, b64decode
from dateti... |
from spack import *
import os
class Molcas(CMakePackage):
"""Molcas is an ab initio quantum chemistry software package
developed by scientists to be used by scientists.
Please set the path to licence file with the following command
export MOLCAS_LICENSE=/path/to/molcas/license/"""
homepa... |
import sys
from pip.basecommand import Command
BASE_COMPLETION = """
# pip %(shell)s completion start%(script)s# pip %(shell)s completion end
"""
COMPLETION_SCRIPTS = {
'bash': """
_pip_completion()
{
COMPREPLY=( $( COMP_WORDS="${COMP_WORDS[*]}" \\
COMP_CWORD=$COMP_CWORD \\
... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
import json
import logging
import sys
import traceback
from ansible.module_utils.api impor... |
import os
import zipfile
import contextlib
import pytest
from setuptools.command.upload_docs import upload_docs
from setuptools.dist import Distribution
from .textwrap import DALS
from . import contexts
SETUP_PY = DALS(
"""
from setuptools import setup
setup(name='foo')
""")
@pytest.fixture
def ... |
"""Helper functions for tracker file functionality."""
import errno
import hashlib
import os
import re
from boto import config
from gslib.exception import CommandException
from gslib.util import CreateDirIfNeeded
from gslib.util import GetGsutilStateDir
from gslib.util import ResumableThreshold
from gslib.util import... |
RAID_CONFIG_OKAY = '''
{
"logical_disks": [
{
"raid_level": "1",
"size_gb": 100,
"volume_name": "my-volume",
"is_root_volume": true,
"share_physical_disks": false,
"disk_type": "ssd",
"interface_type": "sas",
"number_of_physical_disks": 2,
"controll... |
import datetime
import StringIO
from nova import context
from nova import exception
from nova import test
import nova.tests.image.fake
class FakeImageServiceTestCase(test.NoDBTestCase):
def setUp(self):
super(FakeImageServiceTestCase, self).setUp()
self.image_service = nova.tests.image.fake.FakeI... |
from collections import Counter
import nltk
from nltk.corpus import stopwords
from nltk.util import ngrams
from numpy.random import choice
import plot
s = set(stopwords.words('english'))
#from nltk.model import NgramModel
# figure out encoding
# separate messages by special character instead of newline
class Lan... |
from ansible.cache.base import BaseCacheModule
class CacheModule(BaseCacheModule):
def __init__(self, *args, **kwargs):
self._cache = {}
def get(self, key):
return self._cache.get(key)
def set(self, key, value):
self._cache[key] = value
def keys(self):
return self._c... |
from gi.repository import Gtk, Gdk, GLib, Pango, GObject, WebKit2
from eolie.label_indicator import LabelIndicator
from eolie.define import El, ArtSize
from eolie.utils import remove_www
class PageChildRow(Gtk.ListBoxRow):
"""
Label for a view
"""
def __init__(self, view, window):
"""
... |
''' This manages remote shared Ansible objects, mainly roles'''
import os
from ansible.errors import AnsibleError
from ansible.utils.display import Display
# default_readme_template
# default_meta_template
class Galaxy(object):
''' Keeps global galaxy info '''
def __init__(self, options, display... |
import mock
from oslo_config import cfg
from nova.tests.functional.v3 import test_servers
CONF = cfg.CONF
CONF.import_opt('osapi_compute_extension',
'nova.api.openstack.compute.extensions')
class ServerPasswordSampleJsonTests(test_servers.ServersSampleBase):
extension_name = "os-server-password"... |
"""GDB commands for working with pretty-printers."""
import copy
import gdb
import re
def parse_printer_regexps(arg):
"""Internal utility to parse a pretty-printer command argv.
Arguments:
arg: The arguments to the command. The format is:
[object-regexp [name-regexp]].
Ind... |
#!/usr/bin/python
"""
Copyright 2014 Google Inc.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
Utilities for working with URLs.
TODO(epoger): move this into tools/utils for broader use?
"""
# System-level imports
import contextlib
import os
import shutil
import u... |
""" Look through skia-autogen, searching for all checksums which should have
corresponding files in Google Storage, and verify that those files exist. """
import json
import posixpath
import re
import subprocess
import sys
# TODO(borenet): Replace some/all of these with constants from gm/gm_json.py
AUTOGEN_URL = 'h... |
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
unified_strdate,
)
class KhanAcademyIE(InfoExtractor):
_VALID_URL = r'^https?://(?:(?:www|api)\.)?khanacademy\.org/(?P<key>[^/]+)/(?:[^/]+/){,2}(?P<id>[^?#/]+)(?:$|[?#])'
IE_NAME = 'KhanAcademy'
... |
"""Support for mounting virtual image files."""
import os
import time
from oslo_log import log as logging
from oslo_service import loopingcall
from oslo_utils import importutils
from nova import exception
from nova.i18n import _
import nova.privsep.fs
from nova.virt.image import model as imgmodel
LOG = logging.getL... |
"""
String Substitution for a Mad Lib
Adapted from code by Kirby Urner
This version loops through the cue choices.
"""
storyFormat = """
Once upon a time, deep in an ancient jungle,
there lived a {animal}. This {animal}
liked to... |
from sqlalchemy.orm import validates
from sqlalchemy import UniqueConstraint
from eachday import app, db, bcrypt
from datetime import datetime, date, timedelta
import jwt
import marshmallow
from marshmallow import Schema, fields, validate, ValidationError
class User(db.Model):
__tablename__ = 'user'
TOKEN_EXP... |
''' Provide a set of named FontAwesome icons that can be uses in Bokeh documents
'''
__icons__ = [
"adjust", "adn", "align-center", "align-justify", "align-left", "align-right", "ambulance",
"anchor", "android", "angellist", "angle-double-down", "angle-double-left", "angle-double-right",
"angle-double-up"... |
from distutils.command.bdist_wininst import bdist_wininst as _bdist_wininst
import os, sys
class bdist_wininst(_bdist_wininst):
def create_exe(self, arcname, fullname, bitmap=None):
_bdist_wininst.create_exe(self, arcname, fullname, bitmap)
dist_files = getattr(self.distribution, 'dist_files', [])... |
__all__ = ['Mark', 'YAMLError', 'MarkedYAMLError']
class Mark(object):
def __init__(self, name, index, line, column, buffer, pointer):
self.name = name
self.index = index
self.line = line
self.column = column
self.buffer = buffer
self.pointer = pointer
def get_... |
#!/usr/bin/env python
# It will connect to DataStoreClient
from sciwonc.dataflow.DataStoreClient import DataStoreClient
import ConfigDB_MedianMemory_0
# connector and config
client = DataStoreClient("postgres", ConfigDB_MedianMemory_0)
data = client.getData()
output = []
if(data):
#docs = []
n = 0
# p... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
import re
from ansible.module_utils.nxos import get_config, load_config, run_commands
from ansible.module_utils.nxos import nxos_argument_spec, check_args
from ansible.module_util... |
# -*- coding: utf-8 -*-
"""
jinja2.runtime
~~~~~~~~~~~~~~
Runtime helpers.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD.
"""
from itertools import chain
from jinja2.nodes import EvalContext, _context_function_types
from jinja2.utils import Markup, soft_unicode, escape, missing, concat, \
... |
import os
import re
from MenuList import MenuList
from Components.Harddisk import harddiskmanager
from Tools.Directories import SCOPE_ACTIVE_SKIN, resolveFilename, fileExists, pathExists
from enigma import RT_HALIGN_LEFT, eListboxPythonMultiContent, \
eServiceReference, eServiceCenter, gFont
from Tools.LoadPixmap impo... |
from urllib.parse import quote_plus
import requests
import requests.exceptions
from cloudbot import hook
from cloudbot.util import formatting
api_url = "http://api.fishbans.com/stats/{}/"
@hook.command("bans", "fishbans")
def fishbans(text, bot):
"""<user> - gets information on <user>'s minecraft bans from fis... |
from .main import Plex
def start():
return Plex()
config = [{
'name': 'plex',
'groups': [
{
'tab': 'notifications',
'list': 'notification_providers',
'name': 'plex',
'options': [
{
'name': 'enabled',
... |
from __future__ import absolute_import
from collections import namedtuple
import requests
from xbmcswift2 import xbmc
GameState = namedtuple(u'GameState',
[u'inning_num',
u'inning_half',
u'runners_on',
u'outs',
u'away_score',
u'home_score',
u'away_team',
u'home_team',
u'new_... |
#!/usr/bin/env python
# coding=utf-8
###############################################################################
from test import CollectorTestCase
from test import get_collector_config
from test import unittest
from mock import Mock
from mock import patch
try:
from cStringIO import StringIO
except ImportErro... |
from extensions.rich_text_components import base
class Math(base.BaseRichTextComponent):
"""A rich-text component representing a LaTeX math formula."""
name = 'Math'
category = 'Basic Input'
description = 'A math formula.'
frontend_name = 'math'
tooltip = 'Insert mathematical formula'
_c... |
from __future__ import absolute_import
import logging
import os
from pip._vendor.six.moves.urllib import parse as urllib_parse
from pip._internal.download import path_to_url
from pip._internal.utils.misc import display_path, rmtree
from pip._internal.utils.temp_dir import TempDirectory
from pip._internal.vcs import ... |
"""
This script updates website files with the new release information.
(How to run)
python update_website <reef_home> <reef_version> <sha512> <release_notes_link>
You can also see how to run the script with "python update_website.py -h"
(Example)
python update_website ~/reef 0.14.0 8f542ae...c4fed7 https://issues.a... |
"""
==============================================
Feature agglomeration vs. univariate selection
==============================================
This example compares 2 dimensionality reduction strategies:
- univariate feature selection with Anova
- feature agglomeration with Ward hierarchical clustering
Both metho... |
from migrate import ForeignKeyConstraint
from sqlalchemy import MetaData, select, Table
from nova.openstack.common import log as logging
LOG = logging.getLogger(__name__)
def upgrade(migrate_engine):
"""Convert volume and snapshot id columns from int to varchar."""
meta = MetaData()
meta.bind = migrate... |
"""For reading and writing TFRecords files."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python import pywrap_tensorflow
from tensorflow.python.framework import errors
from tensorflow.python.util import compat
class TFRecordCompressi... |
import os
import pytest
import datetime
from excavator import env_iso8601
try:
import iso8601 # NOQA
iso8601_available = True
except ImportError:
iso8601_available = False
def assert_datetimes_almost_equal(w1, w2, delta=datetime.timedelta(microseconds=1)):
assert abs(w1.replace(tzinfo=None) - w2.r... |
from django.core.urlresolvers import reverse
from django import http
from mox3.mox import IsA # noqa
from openstack_dashboard import api
from openstack_dashboard.api import cinder
from openstack_dashboard.test import helpers as test
from openstack_dashboard.usage import quotas
INDEX_URL = reverse('horizon:project:v... |
import sys
import readParams_moreoptions as rdp1
import matplotlib.pyplot as plt
from mom_plot import m6plot
import numpy as np
from netCDF4 import MFDataset as mfdset, Dataset as dset
import time
def extract_twamomy_terms(geofil,vgeofil,fil,xstart,xend,ystart,yend,zs,ze,meanax,
alreadysaved=False,xyasindices=Fa... |
import collections
import unittest
from unittest import mock
from pyrser import parsing
class TestCapture(unittest.TestCase):
def test_it_returns_clause_result(self):
res = mock.Mock()
# if __len__ == 0, bool(res) is False
# overrides with __bool__
res.__len__ = lambda x: 0
... |
def euclidiano(n1,n2):
number1 = 0
number2 = 0
quociente = 0
resto = 0
savedX = 0
x1 = 1
x2 = 0
y1 = 0
y2 = 1
number1 = n1
number2 = n2
originalNumber = number2
while(number2 != 0):
if(originalNumber == number2):
temp = y2
temp -= y1 * quociente
y2 = y1
y1 = temp
resto ... |
"""
AU audio file parser
Author: Victor Stinner
Creation: 12 july 2006
"""
from hachoir_parser import Parser
from hachoir_core.field import UInt32, Enum, String, RawBytes
from hachoir_core.endian import BIG_ENDIAN
from hachoir_core.text_handler import displayHandler, filesizeHandler
from hachoir_core.tools import cre... |
from __future__ import absolute_import
# we use the following in code examples, so it must be part of
# out public API
from autobahn.util import utcnow, utcstr
__version__ = u"0.11.1"
"""
AutobahnPython library version.
"""
__all__ = (
'utcnow',
'utcstr',
) |
"""Minimalist standard library Asynchronous JSON Client
"""
import sys
import uuid
import socket
import logging
import traceback
try:
import sublime
except:
pass
try:
import ujson as json
except ImportError:
import json
from .callback import Callback
from .ioloop import EventHandler
from .typing imp... |
"""
Author: Dr. John T. Hwang <<EMAIL>>
This package is distributed under New BSD license.
Nonuniformly spaced sampling.
"""
from __future__ import division
import numpy as np
import scipy.interpolate
from six.moves import range
from smt.sampling_methods.sampling_method import SamplingMethod
from smt.sampling_method... |
"""
Two TestCase classes for writing tests be run using Django's test
runner (i.e. `manage.py test`).
"""
from __future__ import print_function
import logging
logger = logging.getLogger(__name__)
from django.conf import settings
from django.test import TestCase as DjangoTestCase
from django.test import Client
from d... |
from pythonforandroid.toolchain import Bootstrap, current_directory, info, info_main, shprint
from pythonforandroid.util import ensure_dir
from os.path import join
import sh
class WebViewBootstrap(Bootstrap):
name = 'webview'
recipe_depends = list(
set(Bootstrap.recipe_depends).union({'genericndkbuil... |
"""
tests for the models
"""
import json
from datetime import datetime, timedelta
import ddt
from nose.plugins.attrib import attr
from pytz import utc
from student.roles import CourseCcxCoachRole
from student.tests.factories import AdminFactory
from xmodule.modulestore.tests.django_utils import TEST_DATA_SPLIT_MODULE... |
"""A parser for HTML and XHTML."""
# This file is based on sgmllib.py, but the API is slightly different.
# XXX There should be a way to distinguish between PCDATA (parsed
# character data -- the normal case), RCDATA (replaceable character
# data -- only char and entity references and end tags are special)
# and CDAT... |
#!/usr/bin/env python
import os
import sys
import shutil
from colorama import Fore
import argparse
import zipTest
import unzipTest
parser = argparse.ArgumentParser(description='Process command-line arguments')
parser.add_argument('--file', '-f', metavar='path/to/file', type=str, nargs='?', help='Path to file to use f... |
from X import NoSymbol
def string_to_keysym(keysym):
'''Return the (16 bit) numeric code of keysym.
Given the name of a keysym as a string, return its numeric code.
Don't include the 'XK_' prefix, just use the base, i.e. 'Delete'
instead of 'XK_Delete'.'''
return globals().get('XK_' + keysym, NoSy... |
# coding: utf8
{
'!langcode!': 'zh-cn',
'!langname!': '中文',
'"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" 应为选择表达式, 格式如 "field1=\'value\'". 但是对 JOIN 的结果不可以使用 update 或者 delete"',
'%s %%{row} deleted': '已删除 %s 笔',
'%s %%{row} updated': '已更新 %s... |
import unittest
import requests_mock
from alertaclient.api import Client
class HeartbeatTestCase(unittest.TestCase):
def setUp(self):
self.client = Client()
self.heartbeat = """
{
"heartbeat": {
"createTime": "2017-10-02T23:54:05.214Z",
"cust... |
import os
import sys
sys.path.insert(0, os.path.abspath('lib'))
from ansible.release import __version__, __author__
try:
from setuptools import setup, find_packages
except ImportError:
print("Ansible now needs setuptools in order to build. Install it using"
" your package manager (usually python-se... |
from __future__ import with_statement
from alembic import context
from sqlalchemy import engine_from_config, pool
from logging.config import fileConfig
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python... |
from m5.params import *
from MemObject import MemObject
class ExternalMaster(MemObject):
type = 'ExternalMaster'
cxx_header = "mem/external_master.hh"
port = MasterPort("Master port")
port_type = Param.String('stub', 'Registered external port handler'
' to pass this port to in instantiation')... |
"""Smart cropping of an image by maximizing information entropy."""
from __future__ import division
import numpy as np
def image_entropy(img, img_min, img_max):
"""Calculate the entropy of an image.
Parameters
----------
img : numpy array
The image data.
img_min, img_max : float, float
... |
"""Decodes various date / timestamp formats."""
# stdlib imports
import sys
from datetime import datetime
from optparse import OptionParser
from binascii import hexlify
from struct import unpack, pack
# local imports
from lf.time import (
FILETIMETodatetime, DOSDateTimeTodatetime, VariantTimeTodatetime,
POSIX... |
"""Support for LiteJet lights."""
import logging
from homeassistant.components import litejet
from homeassistant.components.light import (
ATTR_BRIGHTNESS, SUPPORT_BRIGHTNESS, Light)
_LOGGER = logging.getLogger(__name__)
ATTR_NUMBER = 'number'
def setup_platform(hass, config, add_entities, discovery_info=None)... |
#from rainmaker.tox_manager import ToxManager
#from rainmaker.fs_manager import FsManager
#from rainmaker.scan_manager import ScanManager
#from rainmaker.sync_manager import SyncManager
from rainmaker.sync_manager.scan_manager import scan_sync, refresh_sync
import rainmaker.logger
log = rainmaker.logger.create_log(__n... |
import psycopg2
from split_mp4 import split_to_list
from hash_helper import file_to_b32_hash
import shutil
import sys
import os
import time
from datetime import datetime
dir_name = sys.argv[1]
root = "/Users/johannes/Documents/obama_puppet/segments"
if len(sys.argv) > 2:
root = sys.argv[2]
def hash_and_copy(file... |
"""
Script for exporting all courseware from Mongo to a directory
"""
from django.core.management.base import BaseCommand, CommandError
from xmodule.modulestore.xml_exporter import export_to_xml
from xmodule.modulestore.django import modulestore
from xmodule.contentstore.django import contentstore
from xmodule.course_m... |
import unittest
import chainer
import numpy
from chainer.backends import cuda
from chainer import functions
from chainer import gradient_check
from chainer import testing
from chainer.testing import attr
from chainer.utils import type_check
@testing.parameterize(*testing.product({
'shape': [(3, 2), ()],
'dt... |
#!/usr/bin/env python
"""pyclangcheck driver code
This code is the driver code for the pyclangcheck tool.
Copyright: (c) 2010, Knut Reinert, FU Berlin
License: 3-clause BSD (see LICENSE)
"""
from __future__ import with_statement
__author__ = 'Manuel Holtgrewe <<EMAIL>>'
import datetime
import optparse
import os
... |
import morb
from morb import rbms, stats, updaters, trainers, monitors
import theano
import theano.tensor as T
import numpy as np
import gzip, cPickle
import matplotlib.pyplot as plt
plt.ion()
from utils import generate_data, get_context
# DEBUGGING
from theano import ProfileMode
# mode = theano.ProfileMode(opti... |
import psycopg2
from dataset_importer.utils import HandleDatasetImportException
class PostgreSQLReader(object):
@staticmethod
def get_features(**kwargs):
try:
host = kwargs.get('postgres_host', None)
database = kwargs.get('postgres_database', None)
port = kwargs.... |
# coding: utf-8
from __future__ import absolute_import, division, print_function
from astropy.units import Quantity
from represent import ReprHelperMixin
from ..constants import (
WGS84_ANGULAR_VELOCITY, WGS84_EQUATORIAL_RADIUS, WGS84_FLATTENING,
WGS84_MU)
from ..utils import read_only_property, verify_unit
... |
#!/usr/bin/env python
# coding=utf-8
"""
This class collects data on NUMA utilization
#### Dependencies
* numactl
"""
import diamond.collector
from subprocess import Popen, PIPE
from re import compile as re_compile
import logging
node_re = re_compile('(?P<node>^node \d+ (free|size)): (?P<size>\d+) \MB')
class Num... |
"""Test Definitions."""
__author__ = '<EMAIL> (Lindsey Simon)'
from categories.jskb import ecmascript_snippets
from categories import test_set_base
import cgi
import re
import sys
_CATEGORY = 'jskb'
class JskbTest(test_set_base.TestBase):
TESTS_URL_PATH = '/%s/test' % _CATEGORY
def __init__(self, key, name,... |
"""Tests for GENSEC.
Note that this just tests the bindings work. It does not intend to test
the functionality, that's already done in other tests.
"""
from samba.credentials import Credentials
from samba import gensec, auth
import samba.tests
class GensecTests(samba.tests.TestCase):
def setUp(self):
s... |
#!/usr/bin/python
from spacewalk.server import rhnSQL
from spacewalk.server.importlib.backendOracle import OracleBackend
from spacewalk.server.importlib.backendLib import DBint, DBstring, DBdateTime, DBblob
tabs = OracleBackend.tables
utabs = {}
# convert table names to uppercase
for k, v in tabs.items():
utab... |
"""Implements settings for both test execution and output processing.
This package implements :class:`~robot.conf.settings.RobotSettings` and
:class:`~robot.conf.settings.RebotSettings` classes used internally by
the framework. There should be no need to use these classes externally.
This package can be considered re... |
import hashlib
import os
def CallAndRecordIfStale(
function, record_path=None, input_paths=None, input_strings=None,
force=False):
"""Calls function if the md5sum of the input paths/strings has changed.
The md5sum of the inputs is compared with the one stored in record_path. If
this has changed (or the... |
"""
=========================================================================
2 samples permutation test on source data with spatio-temporal clustering
=========================================================================
Tests if the source space data are significantly different between
2 groups of subjects (simu... |
"""add pid field to TaskInstance
Revision ID: 5e7d17757c7a
Revises: 8504051e801b
Create Date: 2016-12-07 15:51:37.119478
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '5e7d17757c7a'
down_revision = '8504051e801b'
branch_labels = None
depends_on = None
def u... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import re
import json
from itertools import chain
from ansible.module_utils._text import to_bytes, to_text
from ansible.module_utils.network.common.utils import to_list
from ansible.plugins.cliconf import CliconfBase, enable_mode... |
from unittest.mock import Mock
from pytest import fixture
from pytest import mark
from pytest import raises
class TestBadge:
@fixture
def meta(self):
from .badge import badge_meta
return badge_meta
def test_meta(self, meta):
from adhocracy_core import resources
from adhoc... |
from app import db, app
import flask.ext.whooshalchemy as whooshalchemy
from hashlib import md5
import re
ROLE_USER = 0
ROLE_ADMIN = 1
followers = db.Table('followers',
db.Column('follower_id', db.Integer, db.ForeignKey('user.id')),
db.Column('followed_id', db.Integer, db.ForeignKey('user.id'))
)
class User(... |
microcode = '''
def macroop BSWAP_D_R
{
roli reg, reg, 8, dataSize=2
roli reg, reg, 16, dataSize=4
roli reg, reg, 8, dataSize=2
};
def macroop BSWAP_Q_R
{
roli reg, reg, 8, dataSize=2
roli t1, reg, 16, dataSize=4
# Top 4 bytes of t1 are now zero
roli t1, t1, 8, dataSize=2
roli t1, t1, 3... |
# coding=utf-8
from django import forms
from django.contrib import messages
from django.shortcuts import render, redirect
from django.utils.translation import ugettext as _
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from servo.models.order import Order
from servo.models.common import Pro... |
from subprocess import Popen, PIPE, STDOUT
import os, sys
import xmlrpclib
import cPickle
class _Method(object):
def __init__(self, proxy, name):
self.proxy = proxy
self.name = name
def __call__(self, *args):
#print "CALL", self.name, args
z = getattr( self.proxy, self.name, ... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def __init__(self):
self.max_sum=-1<<31
def maxPathSum(self, root):
"""
:type root: ... |
"""Tests for utils"""
from os.path import join, abspath, dirname
import sys
import errno
import shutil
import unittest
from tempfile import mkdtemp, mkstemp
try:
from landsat import utils
except ImportError:
sys.path.append(abspath(join(dirname(__file__), '../landsat')))
import utils
class TestUtils(uni... |
"""Tests for periodic state space model components."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.timeseries.python.timeseries.state_space_models import periodic
from tensorflow.contrib.timeseries.python.timeseries.state_space_m... |
from pyschedule import Scenario, solvers, plotters
def plot(S) :
if solvers.mip.solve(S):
# %matplotlib inline
plotters.matplotlib.plot(S,task_colors=task_colors,fig_size=(10,5))
else:
print('no solution exists')
if __name__ == "__main__":
S = Scenario('bike_paint_shop', horizon=10... |
from kafka.tools.protocol.requests.topic_metadata_v0 import TopicMetadataV0Request
from kafka.tools.protocol.responses.metadata_v1 import MetadataV1Response
class TopicMetadataV1Request(TopicMetadataV0Request):
api_version = 1
response = MetadataV1Response
@classmethod
def process_arguments(cls, cmd_... |
# -*- encoding:utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
def label_smoothing(inputs, epsilon=0.1):
'''Applies label smoothing. See https://arxiv.org/abs/1512.00567.
# Args:
inputs: A 3d tensor with shape of ... |
from __future__ import print_function
import copy, datetime, os, pprint, socket, sys, time
startTime = time.time()
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir, 'common')))
import driver, scenario_common, utils, vcoptparse
op = vcoptparse.OptParser()
scenario_common.prepare... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.