content
stringlengths
4
20k
import csv #dm = ( #( 0,86,49,57,31,69,50), #(86, 0,68,79,93,24, 5), #(49,68, 0,16, 7,72,67), #(57,79,16, 0,90,69, 1), #(31,93, 7,90, 0,86,59), #(69,24,72,69,86, 0,81), #(50, 5,67, 1,59,81, 0)) dists = csv.reader(open('capdist.csv'), 'excel') dm = [[int(k) for k in t[2:33]] for t in dists if t[1]] ...
ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.pycompat24 import get_exception from ansible.module_utils.junos import junos_argument_spec try: ...
from odoo import _, api, fields, models class StorageCategory(models.Model): _name = 'stock.storage.category' _description = "Storage Category" _order = "name" name = fields.Char('Storage Category', required=True) max_weight = fields.Float('Max Weight', digits='Stock Weight') capacity_ids = f...
"""Fixer that changes 'a ,b' into 'a, b'. This also changes '{a :b}' into '{a: b}', but does not touch other uses of colons. It does not touch other uses of whitespace. """ from .. import pytree from ..pgen2 import token from .. import fixer_base class FixWsComma(fixer_base.BaseFix): explicit = True # The use...
from datetime import datetime import logging from google.appengine.ext import db from model.datastorefile import DataStoreFile class TestFile(DataStoreFile): master = db.StringProperty() builder = db.StringProperty() test_type = db.StringProperty() @classmethod def delete_file(cls, key, master,...
from django.contrib.postgres.aggregates import ( ArrayAgg, BitAnd, BitOr, BoolAnd, BoolOr, Corr, CovarPop, RegrAvgX, RegrAvgY, RegrCount, RegrIntercept, RegrR2, RegrSlope, RegrSXX, RegrSXY, RegrSYY, StatAggregate, StringAgg, ) from django.db.models.expressions import F, Value from django.test.utils import A...
""" ================================================= Demo of affinity propagation clustering algorithm ================================================= Reference: Brendan J. Frey and Delbert Dueck, "Clustering by Passing Messages Between Data Points", Science Feb. 2007 """ print(__doc__) from sklearn.cluster impor...
from ete3 import PhylomeDBConnector # This connects to the main phylomeDB server (default parameters) p = PhylomeDBConnector() # Obtains the phylomeDB internal ID for my gene of interest idmatches = p.search_id("ENSG00000146556") # Take the only match (several would be possible) geneid = idmatches[0] # Gets the 'geneid...
try: from zabbix_api import ZabbixAPI HAS_ZABBIX_API = True except ImportError: HAS_ZABBIX_API = False def create_group(zbx, host_group): try: result = zbx.hostgroup.create( { 'name': host_group } ) except BaseException as e: return 1...
{ 'name': 'Opportunity to Quotation', 'version': '1.0', 'category': 'Hidden', 'description': """ This module adds a shortcut on one or several opportunity cases in the CRM. =========================================================================== This shortcut allows you to generate a sales order bas...
# coding=utf-8 """ Collect stats from Apache HTTPD server using mod_status #### Dependencies * mod_status * httplib * urlparse """ import collections import re import httplib import urlparse import diamond.collector from subprocess import Popen, PIPE class HttpdCollector(diamond.collector.Collector): de...
import copy import operator from functools import wraps, update_wrapper import sys from django.utils import six from django.utils.six.moves import copyreg # You can't trivially replace this `functools.partial` because this binds to # classes and returns bound instances, whereas functools.partial (on CPython) # is a ...
""" An asynchronous FTP file download handler for scrapy which somehow emulates an http response. FTP connection parameters are passed using the request meta field: - ftp_user (required) - ftp_password (required) - ftp_passive (by default, enabled) sets FTP connection passive mode - ftp_local_filename - If not...
"""Fixer for 'raise E, V, T' raise -> raise raise E -> raise E raise E, V -> raise E(V) raise E, V, T -> raise E(V).with_traceback(T) raise E, None, T -> raise E.with_traceback(T) raise (((E, E'), E''), E'''), V -> raise E(V) raise "foo", V, T -> warns about string exceptions ...
import base64 import re import threading from binascii import hexlify, unhexlify from functools import partial from electrum_vtc.bitcoin import (bc_address_to_hash_160, xpub_from_pubkey, public_key_to_p2pkh, EncodeBase58Check, TYPE_ADDRESS, TYPE_SCRIPT, ...
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function import uuid from six.moves import range from ibeis import constants as const from ibeis.other import ibsfuncs from ibeis.control.accessor_decors import ( adder, deleter, setter, getter_1to1, getter_1toM, default_decorator, ider...
# coding: utf-8 import os import importlib import random import logging from .commands_collector import CommandsCollector logger = logging.getLogger() def load_from_packages(app): pass def load_from_folder(app): """ This code looks for any modules or packages in the given directory, loads th...
from __future__ import print_function import unittest import numpy as np import paddle import paddle.fluid as fluid import paddle.fluid.core as core import paddle.nn.functional as F from op_test import OpTest paddle.enable_static() np.random.seed(1) def maxout_forward_naive(x, groups, channel_axis): s0, s1, s2,...
#! /usr/bin/env python # # Create a new user to the running configuration using edit-config # and the test-option provided by the :validate capability. # # $ ./nc04.py broccoli bob 42 42 import sys, os, warnings warnings.simplefilter("ignore", DeprecationWarning) from ncclient import manager def demo(host, user, name...
# -*- coding: utf-8 -*- """ pygments.formatters ~~~~~~~~~~~~~~~~~~~ Pygments formatters. :copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import os.path import fnmatch from pygments.formatters._mapping import FORMATTERS from pygments.p...
{ 'array': array([('8C', 'TS', 'KC', '9H', '4S', '7D', '2S', '5D', '3S', 'AC'), ('5C', 'AD', '5D', 'AC', '9C', '7C', '5H', '8D', 'TD', 'KS'), ('3H', '7H', '6S', 'KC', 'JS', 'QH', 'TD', 'JC', '2D', '8S'), ('TH', '8H', '5C', 'QS', 'TC', '9H', '4D', 'JC', 'KS', 'JS'), ('7C', '5H', 'KC', 'QH', ...
import pytest from lemur.domains.views import * # noqa from .vectors import VALID_ADMIN_HEADER_TOKEN, VALID_USER_HEADER_TOKEN @pytest.mark.parametrize("token,status", [ (VALID_USER_HEADER_TOKEN, 200), (VALID_ADMIN_HEADER_TOKEN, 200), ('', 401) ]) def test_domain_get(client, token, status): assert ...
from django import forms from django.shortcuts import render from django.utils.translation import ugettext as _ from wagtail.wagtailadmin import messages from wagtail.wagtailadmin.forms import SearchForm from wagtail.wagtailadmin.widgets import AdminPageChooser, AdminDateInput, AdminTimeInput, AdminDateTimeInput from ...
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html from scrapy import signals from scrapy.contrib.exporter import XmlItemExporter import codecs import json class JsonWithEncodin...
from __future__ import unicode_literals from unittest import TestCase from django.template import Context, Engine class CallableVariablesTests(TestCase): @classmethod def setUpClass(cls): cls.engine = Engine() super(CallableVariablesTests, cls).setUpClass() def test_callable(self): ...
""" Contains distributor plugins and functionality for the Pulp plugin testing harness. """ import datetime import logging import os import shutil import time from pulp.server.plugins.plugins.distributor import Distributor from pulp.server.plugins.plugins.model import PublishReport # -- constants -------------------...
from functools import partial from mongoengine.queryset.queryset import QuerySet __all__ = ('queryset_manager', 'QuerySetManager') class QuerySetManager(object): """ The default QuerySet Manager. Custom QuerySet Manager functions can extend this class and users can add extra queryset functionality. ...
from cement.core import handler, controller from dscan.plugins import HumanBasePlugin from subprocess import call import os, sys, dscan BASE_FOLDER = '/var/www/drupal/' UPDATE_MAJOR = ['6', '7'] def recursive_grep(directory, needle): return_file = None for f in os.listdir(directory): if f.endswith('.p...
"""EDNS Options""" NSID = 3 class Option(object): """Base class for all EDNS option types. """ def __init__(self, otype): """Initialize an option. @param otype: The rdata type @type otype: int """ self.otype = otype def to_wire(self, file): """Convert ...
"""Creates an archive data YAML file from a stations CSV file.""" from collections import Counter, defaultdict from pathlib import Path import textwrap from vesper.util.bunch import Bunch WORKING_DIR_PATH = Path( '/Users/Harold/Desktop/NFC/Data/MPG Ranch/2018 MPG Ranch Archive/' 'Archive Data YAML') CSV_F...
import os from django.conf import settings from django.contrib.auth.models import User from django.contrib.auth.tests.utils import skipIfCustomUser from django.contrib.flatpages.models import FlatPage from django.test import TestCase, override_settings @override_settings( LOGIN_URL='/accounts/login/', MIDDLEW...
# pylint: disable=C0111 # pylint: disable=W0621 from lettuce import world, step from common import course_id, course_location from problems_setup import PROBLEM_DICT from nose.tools import assert_in from opaque_keys.edx.locations import SlashSeparatedCourseKey @step(u'I am viewing a course with multiple sections') d...
"""Smoke tests for the ``CLI`` end-to-end scenario.""" import random from fauxfactory import gen_alphanumeric, gen_ipaddr from robottelo import manifests, ssh from robottelo.cli.activationkey import ActivationKey from robottelo.cli.computeresource import ComputeResource from robottelo.cli.contenthost import ContentHos...
""" Test entitlements utilities """ from datetime import timedelta from django.conf import settings from django.utils.timezone import now from opaque_keys.edx.keys import CourseKey from common.djangoapps.course_modes.models import CourseMode from common.djangoapps.course_modes.tests.factories import CourseModeFacto...
from django.contrib.gis.gdal.base import GDALBase from django.contrib.gis.gdal.error import GDALException from django.contrib.gis.gdal.field import Field from django.contrib.gis.gdal.geometries import OGRGeometry, OGRGeomType from django.contrib.gis.gdal.prototypes import ds as capi, geom as geom_api from django.utils....
"""Base class for creating split nodes using one or more features.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc from tensorflow.contrib.boosted_trees.python.ops import batch_ops_utils from tensorflow.python.ops import control_flow_ops cla...
r""" ===== Swirl ===== Image swirling is a non-linear image deformation that creates a whirlpool effect. This example describes the implementation of this transform in ``skimage``, as well as the underlying warp mechanism. Image warping ````````````` When applying a geometric transformation on an image, we typically...
# -*- coding: utf-8 -*- import re,json from resources.lib.zmodules import client from resources.lib.zmodules import workers class youtube(object): def __init__(self, key=''): self.list = [] ; self.data = [] self.base_link = 'http://www.youtube.com' self.key_link = '&key=%s' % key ...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} import os from ansible.module_utils import crypto as crypto_utils from ansible.module_util...
import time from django.conf import settings from django.utils.cache import patch_vary_headers from django.utils.http import cookie_date TEST_COOKIE_NAME = 'testcookie' TEST_COOKIE_VALUE = 'worked' class SessionMiddleware(object): def process_request(self, request): engine = __import__(settings.SESSION...
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals from unittest import TestCase try: import numpy as np except ImportError: pass from jubakit.wrapper.regression import LinearRegression, NearestNeighborsRegression from . import requireEmbedded class Line...
from openerp.osv import osv class hr_payslip_employees(osv.osv_memory): _inherit ='hr.payslip.employees' def compute_sheet(self, cr, uid, ids, context=None): run_pool = self.pool.get('hr.payslip.run') if context is None: context = {} if context.get('active_id'): ...
import wx from cairis.core.armid import * from SecurityPatternEnvironmentPanel import SecurityPatternEnvironmentPanel __author__ = 'Shamal Faily' class SecurityPatternEnvironmentDialog(wx.Dialog): def __init__(self,parent,patternId,cmEnvs = []): wx.Dialog.__init__(self,parent,SPENVIRONMENT_ID,'Situate pattern',...
import json from zope import interface from twisted.internet import defer from piped.plugins.status_testing import statustest, processors from piped import processing class TestClientProcessor(processors.StatusTestProcessor): interface.classProvides(processing.IProcessor) name = 'test-client' class Tes...
import time from openerp.osv import osv from openerp.report import report_sxw def titlize(journal_name): words = journal_name.split() while words.pop() != 'journal': continue return ' '.join(words) class order(report_sxw.rml_parse): def __init__(self, cr, uid, name, context): super(...
"""gRPC debug server in Python.""" # pylint: disable=g-bad-import-order from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import json import threading import time from concurrent import futures import grpc from six.moves import queue from ...
import os import csv import copy import base64 from xml.dom.minidom import getDOMImplementation try: import release from osv import orm, osv, fields except ImportError: import openerp from openerp import release from openerp.osv import orm, osv, fields import tempfile import codecs import logging ...
from openerp.osv import osv from openerp.tools.translate import _ class PosInvoiceReport(osv.AbstractModel): _name = 'report.point_of_sale.report_invoice' def render_html(self, cr, uid, ids, data=None, context=None): report_obj = self.pool['report'] posorder_obj = self.pool['pos.order'] ...
import sys import os import shutil import subprocess def find_files(files, path): found = [] for fname in files: for dir in path: filepath = os.path.normpath(os.path.join(dir, fname)) if os.path.isfile(filepath): found.append(filepath) break ...
import Gaffer Gaffer.Metadata.registerNode( Gaffer.ContextVariablesComputeNode, "description", """ Adds variables which can be referenced by upstream expressions. """, plugs = { "variables" : [ "description", """ The variables to be added - arbitrary numbers of variables can be added here. ...
#!/usr/bin/env python # -- Content-Encoding: UTF-8 -- """ Tests the iPOPO utility methods. :author: Thomas Calmant """ # Tests from tests.ipopo import install_ipopo # Pelix from pelix.framework import FrameworkFactory import pelix.framework as pelix # iPOPO import pelix.ipopo.constants as constants # Standard libr...
ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['deprecated'], 'supported_by': 'community'} from ansible.module_utils.basic import AnsibleModule from ansible.module_utils._text import to_native try: import pan.xapi from pan.xapi import PanXapiError HAS_LI...
"""Install needed prerequisites on the AppVeyor/Travis CI. Note this file is written in python2 as this is more readily available on the CI machines. """ from __future__ import print_function import os import sys import subprocess import urllib try: import _winreg as winreg except ImportError: winreg = None...
"""Tests server and client side metadata API.""" import unittest import weakref import grpc from grpc import _channel from tests.unit import test_common from tests.unit.framework.common import test_constants _CHANNEL_ARGS = (('grpc.primary_user_agent', 'primary-agent'), ('grpc.secondary_user_agent'...
from __future__ import nested_scopes from twisted.trial import unittest from twisted.internet import protocol, reactor, interfaces, defer from twisted.protocols import basic from twisted.python import util, components, log from twisted.test import test_tcp import os try: from OpenSSL import SSL, crypto from t...
__all__ = ['Asset', 'AssetLibrary', 'ShotInstance','LayerInstance','SequenceInstance'] from pyasm.biz import Snapshot, Task, Pipeline, Project from pyasm.search import * from pyasm.common import * import re class Asset(SObject): SEARCH_TYPE = "prod/asset" def get_search_columns(): return ['code','n...
from __future__ import unicode_literals import frappe, unittest from frappe.utils import flt class TestMaterialRequest(unittest.TestCase): def setUp(self): frappe.defaults.set_global_default("auto_accounting_for_stock", 0) def test_make_purchase_order(self): from erpnext.stock.doctype.material_request.material_...
from collections import Counter def parse(lines): return [x.strip() for x in lines] def step1(input): """ >>> step1([ \ "eedadn", \ "drvtee", \ "eandsr", \ "raavrd", \ "atevrs", \ "tsrnev", \ "sdttsa", \ "rasrtv", \ "nssdts", \ ...
import socket import struct import sys from utils import color, StructPython2or3, NetworkSendBufferPython2or3, NetworkRecvBufferPython2or3 from packets import SMBHeader, SMBNego, SMBNegoFingerData, SMBSessionFingerData def OsNameClientVersion(data): try: if (sys.version_info > (3, 0)): length = struct.unpack('<...
import invoice # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
import sys import re import os import shutil import commands """Copy Special exercise """ # +++your code here+++ # Write functions and modify main() to call them # LAB(begin solution) def get_special_paths(dirname): """Given a dirname, returns a list of all its special files.""" result = [] paths = os.listdir(...
""" NTLM authenticating pool, contributed by erikcederstran Issue #10, see: http://code.google.com/p/urllib3/issues/detail?id=10 """ from __future__ import absolute_import try: from http.client import HTTPSConnection except ImportError: from httplib import HTTPSConnection from logging import getLogger from nt...
''' Core package of pubsub, holding the publisher, listener, and topic object modules. Functions defined here are used internally by pubsub so that the right modules can be found later, based on the selected messaging protocol. Indeed some of the API depends on the messaging protocol used. For instance sendMessage(), ...
""" Tests for django-analytical. """ from analytical.tests.test_tag_analytical import * from analytical.tests.test_tag_chartbeat import * from analytical.tests.test_tag_clickmap import * from analytical.tests.test_tag_clicky import * from analytical.tests.test_tag_crazy_egg import * from analytical.tests.test_tag_gaug...
import unittest import weblab.data.dto.users as Group class GroupTestCase(unittest.TestCase): def test_get_full_name(self): group1 = Group.Group("group 1") group12 = Group.Group("group 1.2") group121 = Group.Group("group 1.2.1") group12.add_child(group121) group1.add_chil...
from .. import util as importlib_test_util from . import util import imp import sys import unittest class BadLoaderFinder: bad = 'fine.bogus' @classmethod def find_module(cls, fullname, path): if fullname == cls.bad: return cls @classmethod def load_module(cls, fullname): ...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type # take a list of files and (optionally) a list of paths # return the first existing file found in the paths # [file1, file2, file3], [path1, path2, path3] # search order is: # path1/file1 # path1/file2 # path1/file3 # path2/file1 #...
"""Tests for json_with_comments.py.""" from google.apputils import basetest from googleapis.codegen.utilities import json_with_comments class JsonWithCommentsTest(basetest.TestCase): SOME_JSON_WITH_COMMENTS = """ # Garlic and sapphires in the mud # Clot the bedded axle-tree. {"author": "Timmy", ...
from ordereddict import OrderedDict from qapi import * import sys import os import getopt import errno def generate_fwd_struct(name, members): return mcgen(''' typedef struct %(name)s %(name)s; typedef struct %(name)sList { %(name)s *value; struct %(name)sList *next; } %(name)sList; ''', ...
"""Shim script for the SDK updater, to allow automatic updating. The purpose of this script is to be a shim which automatically updates sdk_tools (the bundle containing the updater scripts) whenever this script is run. When the sdk_tools bundle has been updated to the most recent version, this script forwards its arg...
import threading class StoppableThread(threading.Thread): """Basic Stoppable Thread Wrapper Adds event for stopping the execution loop and exiting cleanly.""" def __init__(self): threading.Thread.__init__(self, name= __class__) self.stop_event = threading.Event() self.daemon =...
import unittest import scriptures class TestUniversalURL(unittest.TestCase): def test_no_verses(self): uri = '/scriptures/ot/isa/40' universal_url = 'https://www.churchofjesuschrist.org/study/scriptures/ot/isa/40' self.assertEqual(scriptures.ref(uri).universal_url(), universal_url) de...
import ctypes import numpy from chainer import cuda from chainer import function from chainer.utils import type_check if cuda.cudnn_enabled: cudnn = cuda.cudnn libcudnn = cudnn.cudnn _mode = libcudnn.CUDNN_ACTIVATION_SIGMOID class Sigmoid(function.Function): """Logistic sigmoid function.""" de...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} import traceback try: import boto3 from botocore.exceptions import ClientError, NoC...
""" refcounting ~~~~~~~~~~~ Reference count annotations for C API functions. Has the same result as the sphinx.ext.refcounting extension but works for all functions regardless of the signature, and the reference counting information is written inline with the documentation instead of a sepa...
#!/usr/bin/env python import argparse import subprocess import logging from django.utils.timezone import datetime, utc from service.driver import get_account_driver from core.models import Provider, Identity, MachineRequest, Application, ProviderMachine from core.models.application import _generate_app_uuid def main...
from datetime import timedelta,datetime import copy import time class MDateTime(object): def __init__(self,dtime=None,delta=None): basetime = dtime if basetime is None: basetime = datetime.now() if delta is not None: basetime += delta self.year = basetime.yea...
"""Test-appropriate entry points into the gRPC Python Beta API.""" import grpc from grpc.beta import implementations def not_really_secure_channel(host, port, channel_credentials, server_host_override): """Creates an insecure Channel to a remote host. Args: host: The name of ...
from unittest import TestCase try: from unittest import mock except ImportError: import mock from routeros_api import exceptions from routeros_api import api_communicator class TestCommunicator(TestCase): def test_login_call(self): base = mock.Mock() base.receive_sentence.return_value = [...
# Problem 18 # By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23. # # 3 # 7 4 # 2 4 6 # 8 5 9 3 # # That is, 3 + 7 + 4 + 9 = 23. # # Find the maximum total from top to bottom of the triangle below...
ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'version': '1.0'} import re import uuid import time import sys HAS_PB_SDK = True try: from profitbricks.client import ProfitBricksService, Datacenter except ImportError: HAS_PB_SDK = False LOCATIO...
import re import sys import subprocess import sublime from .abstract import AbstractRegexLinkResolver DEFAULT_OPEN_PROMPT_LINK_COMMANDS = dict( darwin=['open', '-a', 'Terminal'], win32=['cmd'], linux=['gnome-terminal'], ) PATTERN_SETTING = 'orgmode.open_link.resolver.prompt.pattern' PATTERN_DEFAULT = r'^...
"""Tests for ExtractVolumePatches gradient.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import parameterized import numpy as np from tensorflow.python.eager import context from tensorflow.python.framework import constant_op from te...
#!/usr/bin/env python ''' BEGIN - Limit Tensoflow to only use specific GPU ''' import os gpu_num = 2 os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID' # see issue #152 os.environ['CUDA_VISIBLE_DEVICES'] = '{}'.format(gpu_num) os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # Supress Tensforflow debug messages import tensor...
import command command.model_obj_type_disable_submode('tacacs-plus-config') command.model_obj_type_disable_submode('tacacs-plus-host') command.model_obj_type_disable_edit('tacacs-plus-config', 'tacacs-plus-authn') command.model_obj_type_disable_edit('tacacs-plus-config', 'tacacs-plus-authz') command.model_obj_type_di...
import test_framework.loginit import time import sys if sys.version_info[0] < 3: raise "Use Python 3" import logging from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * from test_framework.blocktools import * from test_framework.script import * from test_framework.key ...
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """The dtk module provides basic functions for interfacing with Diffusion Toolkit tools. Currently these tools are supported: * TODO Examples -------- See the docstrings for the individual classes fo...
""" termcolors.py """ from django.utils import six color_names = ('black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white') foreground = {color_names[x]: '3%s' % x for x in range(8)} background = {color_names[x]: '4%s' % x for x in range(8)} RESET = '0' opt_dict = {'bold': '1', 'underscore': '4', 'blink...
# coding: utf-8 from __future__ import unicode_literals from .common import InfoExtractor from ..utils import ( int_or_none, float_or_none, ) class TenPlayIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?ten(play)?\.com\.au/.+' _TEST = { 'url': 'http://tenplay.com.au/ten-insider/extra/sea...
from bs4 import BeautifulSoup from couchpotato.core.helpers.encoding import tryUrlencode, toSafeString from couchpotato.core.helpers.variable import tryInt from couchpotato.core.logger import CPLog from couchpotato.core.providers.torrent.base import TorrentProvider import traceback log = CPLog(__name__) class IPTorr...
# -*- coding: utf-8 -*- """ An alphabetical list of Finnish municipalities for use as `choices` in a formfield. This exists in this standalone file so that it's only imported into memory when explicitly needed. """ MUNICIPALITY_CHOICES = ( ('akaa', u"Akaa"), ('alaharma', u"Alahärmä"), ('alajarvi', u"Alajä...
__author__ = 'Wander Lairson Costa' __all__ = ['methodtrace', 'functiontrace'] import logging import usb._interop as _interop def _trace_function_call(logger, fname, *args, **named_args): logger.debug( # TODO: check if 'f' is a method or a free function fname + '(' + \ ...
"""Tests for pooling layers.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.keras._impl import keras from tensorflow.python.keras._impl.keras import testing_utils from tensorflow.python.platform import test class GlobalPoolingTe...
import pytest from aiohttp.test_utils import make_mocked_coro async def test_find(mocker, snapshot, spawn_client, static_time): client = await spawn_client(authorize=True) await client.db.indexes.insert_many([ { "_id": "bar", "version": 1, "created_at": static_time...
# Tests that work for both bytes and buffer objects. # See PEP 3137. import struct import sys class MixinBytesBufferCommonTests(object): """Tests that work for both bytes and buffer objects. See PEP 3137. """ def marshal(self, x): """Convert x into the appropriate type for these tests.""" ...
from __future__ import division, print_function, absolute_import __all__ = ['fftshift', 'ifftshift', 'fftfreq', 'rfftfreq'] from numpy import arange from numpy.fft.helper import fftshift, ifftshift, fftfreq def rfftfreq(n, d=1.0): """DFT sample frequencies (for usage with rfft, irfft). The returned float a...
import os from avocado import Test from avocado.utils import archive, build, process, distro, cpu from avocado.utils.software_manager import SoftwareManager class Numatop(Test): """ Test case of numatop functionality Test runs mgen application to check numatop snapshot registers it :avocado: tags=c...
""" Provider related utilities """ from libcloud.compute.types import Provider from libcloud.common.providers import get_driver as _get_provider_driver from libcloud.common.providers import set_driver as _set_provider_driver from libcloud.compute.types import OLD_CONSTANT_TO_NEW_MAPPING from libcloud.compute.deprecate...
#!/usr/bin/env python """ Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License");...
import time import re import os import sys from subprocess import Popen, PIPE import threading illegal_predicates = [ ('library(?!\(myddas\))', 'library'), ('use_module(?!\(library\(myddas\)\))', 'use_module'), ('\[.+\]', '[]'), \ 'abort', 'absolute_file_name', 'access', 'access_file', 'add_to_path', 'alarm', ...