content
stringlengths
4
20k
import math import os import hashlib from urllib.request import urlretrieve import zipfile import gzip import shutil import numpy as np from PIL import Image from tqdm import tqdm def _read32(bytestream): """ Read 32-bit integer from bytesteam :param bytestream: A bytestream :return: 32-bit integer ...
"""Provide a TestCase base class for PageTest subclasses' unittests.""" import unittest from telemetry import benchmark from telemetry.core import exceptions from telemetry.core import util from telemetry.internal import story_runner from telemetry.page import page as page_module from telemetry.page import page_set a...
""" Copyright (c) 2018 Red Hat, Inc All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. Very small subset of tests for the YumRepo class. Most testing is done in test_add_yum_repo_by_url """ from __future__ import absolute_import fr...
import ConfigParser import getopt import os import sys import tempfile def usage(rc): print """usage: %s [--inplace|-i] conf/checksums.ini --inplace, -i: update file in place (default is to write to stdout) If no input file is given, will read from standard input. """ % sys.argv[0] sys.exit(rc) ...
import time from openerp import pooler from openerp.report.interface import report_rml from openerp.tools import to_xml from openerp.report import report_sxw from datetime import datetime from openerp.tools.translate import _ class report_custom(report_rml): def create_xml(self, cr, uid, ids, datas, context=None):...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Unit tests for contribs """ import sys import os import unittest def fix_sys_path(): """ logic to have always the correct sys.path '', web2py/gluon, web2py/site-packages, web2py/ ... """ def add_path_first(path): sys.path = [path] + [p f...
is_correct = False router = widget_inputs["check1"] template = widget_inputs["check2"] service = widget_inputs["check3"] controller = widget_inputs["check4"] module = widget_inputs["check5"] comments = [] def commentizer(new): if new not in comments: comments.append(new) if not router: is_correct = i...
from django.contrib import admin from testproject.inline_registrations.models import (ArticleWithSimpleRegistration, ArticleWithExternalInline, ArticleWithInternalInline) import multilingual ######################...
import sqlalchemy as sa import db import dblp def insert(conn, ins): """Attempt to run an insertion statement; return results, None if error.""" try: ins_res = conn.execute(ins) except sa.exc.IntegrityError as err: # a paper already exists with this id logging.error(str(err)) ...
# -*- coding: utf-8 -*- """ Demonstrates use of PlotWidget class. This is little more than a GraphicsView with a PlotItem placed in its center. """ import initExample ## Add path to library (just for examples; you do not need this) from pyqtgraph.Qt import QtGui, QtCore import numpy as np import pyqtgraph as pg #...
__author__ = 'api.jscudder (Jeff Scudder)' import atom.http_interface import atom.url class Error(Exception): pass class NoRecordingFound(Error): pass class MockRequest(object): """Holds parameters of an HTTP request for matching against future requests. """ def __init__(self, operation, url, data=Non...
""" .. py:module:: serializers :platform: Unix Predefined serializers for routers. """ import pickle from numpy import array, ndarray from creamas.core.artifact import Artifact def get_serializers(): """Get all basic serializers defined in this module as a list. """ return [artifact_serializer, arr...
import socket import base64 from httplib import HTTPSConnection, HTTPException import json from ssl import SSLError import sickbeard from sickbeard import logger, common class PushbulletNotifier: def test_notify(self, pushbullet_api): return self._sendPushbullet(pushbullet_api, event="Test", message="Test...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import sys import copy import json from ansible import constants as C from ansible.module_utils._text import to_text from ansible.module_utils.connection import Connection from ansible.plugins.action.normal import ActionModule as ...
# -*- coding: utf-8 -*- import httplib as http from flask import redirect from framework.auth.decorators import must_be_logged_in from framework.exceptions import HTTPError from website.oauth.models import ExternalAccount from website.oauth.utils import get_service from website.oauth.signals import oauth_complete @...
""" pretty debug errors (part of web.py) portions adapted from Django <djangoproject.com> Copyright (c) 2005, the Lawrence Journal-World Used under the modified BSD license: http://www.xfree86.org/3.3.6/COPYRIGHT2.html#5 """ __all__ = ["debugerror", "djangoerror", "emailerrors"] import sys, urlparse, pprint, traceb...
"""WSGI script for Nova EC2 API EXPERIMENTAL support script for running Nova EC2 API under Apache2 etc. """ from oslo_config import cfg from oslo_log import log as logging from paste import deploy from nova import config from nova import objects from nova import service # noqa from nova import utils CONF = cfg.CO...
"""Interceptor that ensures a specific header is present.""" import grpc def _unary_unary_rpc_terminator(code, details): def terminate(ignored_request, context): context.abort(code, details) return grpc.unary_unary_rpc_method_handler(terminate) class RequestHeaderValidatorInterceptor(grpc.ServerI...
from tempest_lib import auth from tempest.common import cred_provider from tempest import config from tempest import exceptions CONF = config.CONF class Manager(object): """ Base manager class Manager objects are responsible for providing a configuration object and a client object for a test case ...
# -*- coding: utf-8 -*- """Easy install Tests """ from __future__ import absolute_import import sys import os import shutil import tempfile import site import contextlib import tarfile import logging import itertools import distutils.errors import pytest try: from unittest import mock except ImportError: imp...
from modularodm.exceptions import ValidationValueError from website.addons.base.exceptions import AddonError class WikiError(AddonError): """Base exception class for Wiki-related error.""" pass class NameEmptyError(WikiError, ValidationValueError): """Raised if user tries to provide an empty name value.""...
from openerp.osv import fields, osv from openerp.tools.translate import _ class stock_invoice_onshipping(osv.osv_memory): _inherit = "stock.invoice.onshipping" def _get_journal_type(self, cr, uid, context=None): if context is None: context = {} res_ids = context and context.get...
"""Pathname and path-related operations for the Macintosh.""" import os from stat import * __all__ = ["normcase","isabs","join","splitdrive","split","splitext", "basename","dirname","commonprefix","getsize","getmtime", "getatime","getctime", "islink","exists","lexists","isdir","isfile", ...
import _winreg import verifier class RegistryVerifier(verifier.Verifier): """Verifies that the current registry matches the specified criteria.""" def _RootKeyConstant(self, root_key): """Converts a root registry key string into a _winreg.HKEY_* constant.""" root_key_mapping = { 'HKEY_CLASSES_RO...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import parameterized import numpy as np import tensorflow.compat.v1 as tf1 import tensorflow.compat.v2 as tf import tensorflow_probability as tfp from tensorflow_probability.python.internal i...
import os import urlparse from StringIO import StringIO blacklist = ["/", "/tools/", "/resources/", "/common/", "/conformance-checkers/", "_certs"] def rel_path_to_url(rel_path, url_base="/"): assert not os.path.isabs(rel_path) if url_base[0] != "/": url_base = "/" + url_base if url_base[-1] != "/...
import os import stat from ansible.cli import CLI from ansible.errors import AnsibleError, AnsibleOptionsError from ansible.executor.playbook_executor import PlaybookExecutor from ansible.inventory import Inventory from ansible.parsing import DataLoader from ansible.utils.vars import load_extra_vars from ansible.vars ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import reppy.cache import tldextract import requests from BeautifulSoup import BeautifulSoup from time import sleep import datetime import platform import sys import os import logging import json import Queue from urlparse import urlparse #http://stackoverflow.com/quest...
# Calculate level completion rates via mixpanel export API # TODO: why are our 'time' fields in PST time? targetLevels = ['dungeons-of-kithgard', 'the-raised-sword', 'endangered-burl'] eventFunnel = ['Started Level', 'Saw Victory'] import sys from datetime import datetime, timedelta from mixpanel import Mixpanel t...
""" Command to get statistics about open ended problems. """ import csv import time from django.core.management.base import BaseCommand from optparse import make_option from xmodule.modulestore.django import modulestore from opaque_keys.edx.locations import SlashSeparatedCourseKey from xmodule.open_ended_grading_clas...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Rebuild sphinx/README.rst from sphinx/README.template.rst.""" import re from os import sys, path SCRIPT_DIR = path.dirname(path.abspath(__file__)) if __name__ == "__main__" and __package__ is None: sys.path.append(path.dirname(SCRIPT_DIR)) SPHINX_DIR = path.join...
from __future__ import unicode_literals from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.views import shortcut from django.contrib.sites.models import Site, get_current_site from django.http import HttpRequest, Http404 from django.test import Test...
""" ======================= Decoding real-time data ======================= Supervised machine learning applied to MEG data in sensor space. Here the classifier is updated every 5 trials and the decoding accuracy is plotted """ # Authors: Mainak Jas <<EMAIL>> # # License: BSD (3-clause) import numpy as np import matp...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jun 22 00:52:20 2017 @author: max """ import math import random import numpy as np import pandas as pd from sklearn.datasets import fetch_mldata from sklearn.cross_validation import train_test_split import matplotlib.pyplot as plt from sklearn.manifol...
# -*- coding: utf-8 -*- """ *************************************************************************** ClipVectorByExtent.py --------------------- Date : November 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com ******************...
from __future__ import print_function from serial import Serial import time class Adafruit_Thermal(Serial): resumeTime = 0.0 byteTime = 0.0 dotPrintTime = 0.033 dotFeedTime = 0.0025 prevByte = '\n' column = 0 maxColumn = 32 charHeight = 24 lineSpacing = ...
from airflow.contrib.hooks.vertica_hook import VerticaHook from airflow.models import BaseOperator from airflow.utils.decorators import apply_defaults class VerticaOperator(BaseOperator): """ Executes sql code in a specific Vertica database :param vertica_conn_id: reference to a specific Vertica database...
#!/usr/bin/env python from __future__ import print_function import sys import argparse import numpy as np import netCDF4 as nc """ Create a NetCDF grid definition file in SCRIP format. The grid created is a uniform lat-lon grid. """ class LatLonGrid: """ """ def __init__(self, num_lon_points, num_lat_p...
from ironic.common import exception from ironic.common import states from ironic.conductor import task_manager from ironic.openstack.common import excutils from ironic.openstack.common import log LOG = log.getLogger(__name__) @task_manager.require_exclusive_lock def node_set_boot_device(task, node, device, persisten...
"""Fixer for generator.throw(E, V, T). g.throw(E) -> g.throw(E) g.throw(E, V) -> g.throw(E(V)) g.throw(E, V, T) -> g.throw(E(V).with_traceback(T)) g.throw("foo"[, V[, T]]) will warn about string exceptions.""" # Local imports from .. import pytree from ..pgen2 import token from .. import fixer_base from ..f...
""" Helper for testing. """ import sys import warnings import os.path import re import subprocess import threading from sklearn.externals.joblib._compat import PY3_OR_LATER def warnings_to_stdout(): """ Redirect all warnings to stdout. """ showwarning_orig = warnings.showwarning def showwarning(msg...
from django.test import TestCase from mock import patch, Mock import six import silk from silk.profiling.dynamic import _get_module, _get_parent_module, profile_function_or_method class TestGetModule(TestCase): """test for _get_module""" def test_singular(self): module = _get_module('silk') ...
""" Support for MQTT room presence detection. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.mqtt_room/ """ import asyncio import logging import json from datetime import timedelta import voluptuous as vol from homeassistant.core import callback...
''' Setup script for M-LOOP using setuptools. See the documentation of setuptools for further details. ''' from __future__ import absolute_import, division, print_function import multiprocessing as mp import mloop as ml from setuptools import setup, find_packages from os import path def main(): long_description...
{ 'name' : 'Claim on Deliveries', 'version' : '1.0', 'author' : 'OpenERP SA', 'category' : 'Warehouse Management', 'depends' : ['base', 'crm_claim', 'stock'], 'demo' : [], 'description': """ Create a claim from a delivery order. ===================================== Adds a Claim link to the...
import wizard import purchase_requisition
__all__ = ['Parser'] import zlib import logging import StringIO import struct from exceptions import ParseError import core # get logging object log = logging.getLogger(__name__) # http://developer.apple.com/documentation/QuickTime/QTFF/index.html # http://developer.apple.com/documentation/QuickTime/QTFF/QTFFChap4/...
""" Microsoft Office documents parser. OLE2 files are also used by many other programs to store data. Informations: * wordole.c of AntiWord program (v0.35) Copyright (C) 1998-2003 A.J. van Os Released under GNU GPL http://www.winfield.demon.nl/ * File gsf-infile-msole.c of libgsf library (v1.14.0) Copyright (C...
""" oyPivotSwitcher.py by Erkan Ozgur Yilmaz (c) 2009 v10.5.17 Description : ------------- A tool for easy animating of switching of pivots Version History : ----------------- v10.5.17 - modifications for Maya 2011 and PyMel 1.0.2 v9.12.25 - removed oyAxialCorrectionGroup script import - moved to new versioning sch...
from django.db import models as md class ActiveAdminComments(md.Model): namespace = md.CharField(max_length=255) body = md.TextField() resource_id = md.CharField(max_length=255) resource_type = md.CharField(max_length=255) author_id = md.IntegerField() author_type = md.Cha...
"""WebUpload web interface""" __revision__ = "$Id$" __lastupdated__ = """$Date$""" from invenio.legacy.wsgi.utils import Field from invenio.config import CFG_SITE_SECURE_URL from invenio.utils.url import redirect_to_url from invenio.base.i18n import gettext_set_language from invenio.ext.legacy.handler import wash_ur...
""" Tests for user handling. """ from django.test import TestCase from django.core.urlresolvers import reverse from django.contrib.auth.models import User, Group from django.core import mail from django.core.management import call_command class RegistrationTest(TestCase): def test_register(self): respons...
{ 'name': 'French Payroll', 'category': 'Localization/Payroll', 'author': 'Yannick Buron (SYNERPGY)', 'depends': ['hr_payroll', 'l10n_fr'], 'version': '1.0', 'description': """ French Payroll Rules. ===================== - Configuration of hr_payroll for French localization - All main c...
""" Python package for statistical functions in MLlib. """ from pyspark.mllib.stat._statistics import * from pyspark.mllib.stat.distribution import MultivariateGaussian from pyspark.mllib.stat.test import ChiSqTestResult from pyspark.mllib.stat.KernelDensity import KernelDensity __all__ = ["Statistics", "Multivariate...
#============================================================================== # GLOBAL IMPORTS #============================================================================== import simtk.unit as units #============================================================================== # SOLVENT #=======================...
"""$Id: content.py 699 2006-09-25 02:01:18Z rubys $""" __author__ = "Sam Ruby <http://intertwingly.net/> and Mark Pilgrim <http://diveintomark.org/>" __version__ = "$Revision: 699 $" __date__ = "$Date: 2006-09-25 02:01:18 +0000 (Mon, 25 Sep 2006) $" __copyright__ = "Copyright (c) 2002 Sam Ruby and Mark Pilgrim" from ...
"""A SQLObject emulation layer for Storm. L{SQLObjectBase} is the central point of compatibility. """ import re from storm.properties import ( RawStr, Int, Bool, Float, DateTime, Date, TimeDelta) from storm.references import Reference, ReferenceSet from storm.properties import SimpleProperty, PropertyPublisherMe...
from __future__ import unicode_literals from six import string_types from prompt_toolkit.completion import Completer, Completion __all__ = ( 'WordCompleter', ) class WordCompleter(Completer): """ Simple autocompletion on a list of words. :param words: List of words. :param ignore_case: If True,...
# -*- coding: utf8 -*- import sys try: import cPickle as pickle except: import pickle with open('tld.pkl', 'rb') as f: TLD_LIST = pickle.loads(f.read()) def isIP(s): import re IP_RE = re.compile(r'^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$') retur...
import re def regexp_flags(regexp_modifier=None): flags = 0 set_unicode = True for c in regexp_modifier: if c == 'b': # Treat strings as binary octets rather than UTF-8 characters. set_unicode = False elif c == 'c': # Forces the match to be case sensitive...
from django.db import models class Author(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() friends = models.ManyToManyField('self', blank=True) def __str__(self): return self.name class Publisher(models.Model): name = models.CharField(max_length=255) ...
__revision__ = "test/LoadableModule.py rel_2.5.1:3735:9dc6cee5c168 2016/11/03 14:02:02 bdbaddog" import os import sys import TestCmd import TestSCons dll_ = TestSCons.dll_ _dll = TestSCons._dll test = TestSCons.TestSCons() # Some systems apparently need -ldl on the link line, others don't. no_dl_lib = "env.Program...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.errors import AnsibleAction, AnsibleActionFail from ansible.plugins.action import ActionBase class ActionModule(ActionBase): TRANSFERS_FILES = False UNUSED_PARAMS = { 'systemd': ['pattern', 'runlev...
from flask import Flask, Blueprint from flask.ext.restplus import Api, Resource, fields api_v1 = Blueprint('api', __name__, url_prefix='/api/1') api = Api(api_v1, version='1.0', title='Todo API', description='A simple TODO API extracted from the original flask-restful example', ) ns = api.namespace('todos', desc...
"""This example gets all campaigns with AWQL. To add a campaign, run add_campaign.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 authentication information" section of ...
import config from gi.repository import Gtk import cups import gettext gettext.install(domain=config.PACKAGE, localedir=config.localedir, unicode=True) import ppdippstr def OptionWidget(option, ppd, gui, tab_label=None): """Factory function""" ui = option.ui if (ui == cups.PPD_UI_BOOLEAN and len (o...
"""Script for publishing new versions of Selenium to cloud storage. When you run this script, it will use OAuth 2.0 to authenticate with Google Cloud Storage before attempting to upload any files. This script will fail if the authenticated account does not have write access to the indicated bucket. By default, this s...
""" Our own implementation of the Newton algorithm Unlike the scipy.optimize version, this version of the Newton conjugate gradient solver uses only one function call to retrieve the func value, the gradient value and a callable for the Hessian matvec product. If the function call is very expensive (e.g. for logistic ...
from flask import url_for from tracker.advisory import advisory_get_label from tracker.model.cve import issue_types from tracker.model.enum import Publication from tracker.model.enum import Remote from tracker.model.enum import Severity from tracker.model.enum import Status from .conftest import DEFAULT_ADVISORY_ID f...
"""provides the Lexer class for parsing template strings into parse trees.""" import re import codecs from mako import parsetree, exceptions, compat from mako.pygen import adjust_whitespace _regexp_cache = {} class Lexer(object): def __init__(self, text, filename=None, disable_unicode=False, ...
# 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 'ScheduledQuest' db.create_table('quests_scheduledquest', ( ('id', self.gf('dja...
"""Better tokenizing for coverage.py.""" import codecs, keyword, re, sys, token, tokenize from coverage.backward import set # pylint: disable=W0622 from coverage.parser import generate_tokens def phys_tokens(toks): """Return all physical tokens, even line continuations. tokenize.genera...
from __future__ import print_function import os import sys import six import pyrax import pyrax.exceptions as exc pyrax.set_setting("identity_type", "rackspace") creds_file = os.path.expanduser("~/.rackspace_cloud_credentials") pyrax.set_credential_file(creds_file) dns = pyrax.cloud_dns domain_name = "abc.example....
try: from cs import CloudStack, CloudStackException, read_config has_lib_cs = True except ImportError: has_lib_cs = False # import cloudstack common from ansible.module_utils.cloudstack import * class AnsibleCloudStackAffinityGroup(AnsibleCloudStack): def __init__(self, module): super(Ansibl...
from tune.models import User, Playlist, Artist, Album, Track, PlaylistSong from django.shortcuts import redirect, render, get_object_or_404 from django.contrib.auth import authenticate, login, logout from django.core.cache import cache from json import loads, dumps from urllib2 import urlopen # TODO @login_required de...
from openerp.osv import osv, fields class res_partner(osv.Model): _inherit = 'res.partner' _order = 'display_name' def _display_name_compute(self, cr, uid, ids, name, args, context=None): return dict(self.name_get(cr, uid, ids, context=context)) _display_name_store_triggers = { 'res.p...
# This is the reverse_tcp payload, completely ported from the Metasploit # Framework. # https://github.com/rapid7/metasploit-framework/blob/master/modules/payloads/stagers/windows/reverse_tcp.rb import binascii import re import socket import sys class RevTCPAP: def __init__(self): self.name = "Reverse T...
import logging from django.core.urlresolvers import reverse from django.utils.translation import ugettext_lazy as _ from openstack_dashboard.dashboards.project.routers.extensions.routerrules\ import rulemanager from horizon import tables LOG = logging.getLogger(__name__) class AddRouterRule(tables.LinkAction)...
"""Class for post-handshake certificate checking.""" from utils.cryptomath import hashAndBase64 from X509 import X509 from X509CertChain import X509CertChain from errors import * class Checker: """This class is passed to a handshake function to check the other party's certificate chain. If a handshake f...
from __future__ import absolute_import import hashlib from pip.exceptions import HashMismatch, HashMissing, InstallationError from pip.utils import read_chunks from pip._vendor.six import iteritems, iterkeys, itervalues # The recommended hash algo of the moment. Change this whenever the state of # the art changes; ...
from oslo_serialization import jsonutils as json from six.moves.urllib import parse as urllib from tempest.lib.api_schema.response.compute.v2_1 import floating_ips as schema from tempest.lib.common import rest_client from tempest.lib import exceptions as lib_exc from tempest.lib.services.compute import base_compute_cl...
from LogAnalyzer import Test,TestResult import DataflashLog import math class TestCompass(Test): '''test for compass offsets and throttle interference''' def __init__(self): Test.__init__(self) self.name = "Compass" def run(self, logdata, verbose): self.result = TestResult() ...
"""Provides implementations of basic image processing functions. Implements basic image processing functions, such as reading/writing images, cropping, finding the bounding box of a color and diffing images. When numpy is present, image_util_numpy_impl is used for the implementation of this interface. The old bitmap ...
import argparse from influxdb import InfluxDBClient def main(host='localhost', port=8086): user = 'root' password = 'root' dbname = 'example' dbuser = 'smly' dbuser_password = 'my_secret_password' query = 'select value from cpu_load_short;' json_body = [ { "measurement...
from scrapy.item import BaseItem from scrapy.http import Request from scrapy.exceptions import ContractFail from . import Contract # contracts class UrlContract(Contract): """ Contract to set the url of the request (mandatory) @url http://scrapy.org """ name = 'url' def adjust_request_args(...
#!/usr/bin/env python import argparse import os import server def abs_path(path): return os.path.abspath(path) def parse_args(): parser = argparse.ArgumentParser(description="HTTP server designed for extreme flexibility " "required in testing situations.") parser.add...
# -*- coding: utf-8 -*- #------------------------------------------------------------ # pelisalacarta - XBMC Plugin # Conector para uploadstation # http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/ #------------------------------------------------------------ import urlparse,urllib2,urllib,re import os from core...
"""A parser for SGML, using the derived class as a static DTD.""" # XXX This only supports those SGML features used by HTML. # 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 ...
"""A Windows-only end-to-end integration test for the Chrome hang watcher. This test ensures that the hang watcher is able to detect when Chrome hangs and to generate a Kasko report. The report is then delivered to a locally hosted test crash server. If a crash report is received then all is well. Note that this test...
"""A generally useful event scheduler class. Each instance of this class manages its own queue. No multi-threading is implied; you are supposed to hack that yourself, or use a single instance per application. Each instance is parametrized with two functions, one that is supposed to return the current time, one that i...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['stableinterface'], 'supported_by': 'community'} import os # import module snippets from ansible.module_utils.basic import AnsibleMod...
"""fence_kdump listener plugin.""" import gettext from otopi import plugin, util from ovirt_engine_setup import constants as osetupcons from ovirt_engine_setup.engine import constants as oenginecons from ovirt_engine_setup.engine_common import constants as oengcommcons def _(m): return gettext.dgettext(messag...
import os import sys import shutil from optparse import make_option from django.conf import settings from django.core.files.storage import get_storage_class from django.core.management.base import CommandError, NoArgsCommand from django.contrib.staticfiles import finders class Command(NoArgsCommand): """ Com...
#!/usr/bin/env python import unittest import os from test import test_support # Skip this test if the _tkinter module wasn't built. _tkinter = test_support.import_module('_tkinter') from Tkinter import Tcl from _tkinter import TclError class TkinterTest(unittest.TestCase): def testFlattenLen(self): # ...
# -*- coding: utf-8 -*- from __future__ import (unicode_literals, division, absolute_import, print_function) __license__ = 'GPL 3' __copyright__ = '2011, John Schember <<EMAIL>>' __docformat__ = 'restructuredtext en' import os from calibre import guess_type from calibre.customize.conversion import InputFormatPlugin...
# -*- coding: utf-8 -*- """svn tests""" import io import os import subprocess import sys import unittest from setuptools.tests import environment from setuptools.compat import unicode, unichr from setuptools import svn_utils from setuptools.tests.py26compat import skipIf def _do_svn_check(): try: subpro...
'''Trains a simple xnor fully connected NN on the MNIST dataset. Modified from keras' examples/mnist_mlp.py Gets to 97.41% test accuracy after 20 epochs using tensorflow backend ''' from __future__ import print_function import numpy as np np.random.seed(1337) # for reproducibility import keras.backend as K from ker...
"""Unit test for depstree.""" __author__ = '<EMAIL> (Nathan Naze)' import unittest import depstree def _GetProvides(sources): """Get all namespaces provided by a collection of sources.""" provides = set() for source in sources: provides.update(source.provides) return provides class MockSource(objec...
""" Tests for VF2 isomorphism algorithm for weighted graphs. """ from nose.tools import assert_true, assert_false from operator import eq import networkx as nx import networkx.algorithms.isomorphism as iso def test_simple(): # 16 simple tests w = 'weight' edges = [(0,0,1),(0,0,1.5),(0,1,2),(1,0,3)] ...
import climate import gzip import io import joblib import lmj.cubes import logging import numpy as np import os TARGETS = '0123456789ab' def extract(trial, root, output, frames): fn = trial.root.replace(root, output).replace('.csv.gz', '') def save(df, targets, key): if not os.path.isdir(os.path.di...