content
stringlengths
4
20k
import sys import traceback from org.apache.nifi.processor.io import InputStreamCallback from java.io import BufferedReader, InputStreamReader class ReadFirstLine(InputStreamCallback) : __line = None; def __init__(self) : pass def getLine(self) : return self.__line def process(self, ...
from awsrequests import AwsRequester import boto3 import click import subprocess @click.command() @click.option('--host', help="Hostname of the api gateway") @click.option('--stage', help="Deployment stage") @click.option('--public-key-file', type=click.Path(exists=True), help="ssh public key file") def main(host, st...
from django.contrib.messages import constants from django.contrib.messages.storage import default_storage from django.http import HttpRequest __all__ = ( 'add_message', 'get_messages', 'get_level', 'set_level', 'debug', 'info', 'success', 'warning', 'error', 'MessageFailure', ) class MessageFailure(E...
"""Implementation of an S3-like storage server based on local files. Useful to test features that will eventually run on S3, or if you want to run something locally that was once running on S3. We don't support all the features of S3, but it does work with the standard S3 client for the most basic semantics. To use t...
""" Element Software Snapshot Restore """ from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'certified'} import traceback from ansible.module_utils.basi...
from __future__ import absolute_import, unicode_literals import warnings from django.template.loader import render_to_string from debug_toolbar import settings as dt_settings from debug_toolbar.utils import get_name_from_obj class Panel(object): """ Base class for panels. """ def __init__(self, too...
from openerp import api from openerp.osv import osv, fields import uuid import time import datetime import openerp.addons.decimal_precision as dp class sale_quote_template(osv.osv): _name = "sale.quote.template" _description = "Sale Quotation Template" _columns = { 'name': fields.char('Quotation T...
"""Constants.""" import os import platform import gettext _ = lambda m: gettext.dgettext(message=m, domain='ovirt-engine-setup') from otopi import util from . import config from ovirt_engine_setup import constants as osetupcons from ovirt_engine_setup.constants import classproperty from ovirt_engine_setup.constan...
# -*- coding: utf-8 -*- r""" werkzeug.contrib.sessions ~~~~~~~~~~~~~~~~~~~~~~~~~ This module contains some helper classes that help one to add session support to a python WSGI application. For full client-side session storage see :mod:`~werkzeug.contrib.securecookie` which implements a secure,...
""" Unit test for the programmable tuple metaclass """ import unittest import itertools from programmabletuple import ProgrammableTuple, ProgrammableExpr # # The programmable tuples class definition # ======================================== # # Some utility functions # ---------------------- # def _get_full_nam...
import pygame import threading import time from lib import colors as color # In Pygame, the Sprite class helps to detect collisions between # sprites. This is not our case (yet) because there is only a bouncing # ball in the screen, and the limits of the screen should not be # considered as an huge sprite with a big h...
#!/usr/bin/env python import unittest def suite(): modules_to_test = ( 'test_corebio.test_array_io', 'test_corebio.test_astral', 'test_corebio.test_clustal_io', 'test_corebio.test_data', 'test_corebio.test_db', 'test_corebio.test_dssp', 'test_corebio.test_fa...
############################################################################## # # eggcacher # # EggCacher searches a directory for egg files, and loads # them all into the model-cache. This is used as part of the # panda installation process. # #########################################################################...
import partner import account import installer import account_invoice import account_bank_statement import account_bank import account_cash_statement import account_move_line import account_analytic_line import account_financial_report import wizard import report import product import ir_sequence import company import ...
from __future__ import absolute_import from datetime import datetime, timedelta from celery import current_app from celery import states from celery.result import AsyncResult from celery.task import PeriodicTask from celery.utils import gen_unique_id from djcelery.backends.database import DatabaseBackend from djcele...
import httplib as http from django.utils.translation import ugettext_lazy as _ from rest_framework import status from rest_framework.exceptions import APIException, AuthenticationFailed def dict_error_formatting(errors, index=None): """ Formats all dictionary error messages for both single and bulk requests ...
"""Functional tests for slice op.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from six.moves import xrange # pylint: disable=redefined-builtin import tensorflow as tf class SliceTest(tf.test.TestCase): def _testEmpty(self, use...
from ctypes import * import unittest, sys def callback_func(arg): 42 / arg raise ValueError(arg) if sys.platform == "win32": class call_function_TestCase(unittest.TestCase): # _ctypes.call_function is deprecated and private, but used by # Gary Bishp's readline module. If we have it, we m...
from . import widget from browser import doc,html class Slider(widget.Widget): def __init__(self, id=None, label=False): self._div_shell=html.DIV(Class="ui-slider ui-slider-horizontal ui-widget ui-widget-content ui-corner-all") widget.Widget.__init__(self, self._div_shell, 'slider', id) ...
import os from flask import Flask from flask.ext.mail import Mail from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager from flask.ext.assets import Environment from flask.ext.wtf import CsrfProtect from flask.ext.compress import Compress from flask.ext.rq import RQ from config import co...
from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ObjectDoesNotExist from django.http import Http404 from rest_framework import status, generics, viewsets from rest_framework.views import APIView from rest_framework.response import Response from shared_schema_tenants.utils im...
from __future__ import absolute_import from builtins import object import contextlib2 import wrapt from opentracing.ext import tags as ext_tags from ._current_span import current_span_func from .. import utils from ..local_span import func_span # Utils for instrumenting DB API v2 compatible drivers. # PEP-249 - http...
#!/usr/bin/env python """ Simple example for an OpenID consumer. Once you understand this example you'll know the basics of OpenID and using the Python OpenID library. You can then move on to more robust examples, and integrating OpenID into your application. """ __copyright__ = 'Copyright 2005-2008, Janrain, Inc.' f...
import numpy from chainer import distributions from chainer import testing from chainer import utils @testing.parameterize(*testing.product({ 'shape': [(2, 3), ()], 'is_variable': [True, False], 'sample_shape': [(3, 2), ()], })) @testing.fix_random() @testing.with_requires('scipy') class TestLogNormal(te...
import attr from . import Attachment from .._common import attrs_default from typing import Any, Optional @attrs_default class QuickReply: """Represents a quick reply.""" #: Payload of the quick reply payload = attr.ib(None, type=Any) #: External payload for responses external_payload = attr.ib(...
import res_company import base_vat # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
# coding: utf-8 from os import environ from fabric.api import env, cd, run from fabric.colors import yellow, green REPOSITORY = '<EMAIL>:luanfonceca/speakerfight.git' REMOTE = 'origin' BRANCH = 'master' env.hosts = ['speakerfight.com'] env.user = 'root' env.password = environ.get('PASSWORD') env.app_dir = '/home/spe...
""" SASL transports for Thrift. """ # Initially copied from the Impala repo from __future__ import absolute_import import six import sys import struct from thrift.transport.TTransport import (TTransportException, TTransportBase, CReadableTransport) # TODO: Check whether the following distinction is necessary. Does...
"""SCons.Tool.sunlink Tool-specific initialization for the Sun Solaris (Forte) linker. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001 - 2016 The SCons Foundation # # Permission is here...
import numpy as np from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import SkipTest from sklearn.linear_model.bayes import BayesianRidge, ARDRegression from sklearn import datasets from sklearn.utils.testing import assert_array_almost_equal def test_bayesian_on_diabetes(): """ ...
from libcloud.utils.py3 import httplib from libcloud.common.brightbox import BrightboxConnection from libcloud.loadbalancer.base import Driver, Algorithm, Member from libcloud.loadbalancer.base import LoadBalancer from libcloud.loadbalancer.types import State from libcloud.utils.misc import reverse_dict API_VERSION = ...
#!/usr/bin/env python3 """ turtle-example-suite: tdemo_paint.py A simple event-driven paint program - left mouse button moves turtle - middle mouse button changes color - right mouse button toogles betweem pen up (no line drawn when the turtle moves) and pen down (line is drawn). If pen up follows...
from kivy.utils import platform from kivy.core.window import Window import webbrowser webbrowser._opened = False if platform == 'android': from jnius import autoclass from android.runnable import run_on_ui_thread WebView = autoclass('android.webkit.WebView') print "webview" WebViewClient = autocl...
"""User settings/configuration loading. """ from gi.repository import Gio import os import logging from ConfigParser import ConfigParser from sugar3 import env from sugar3 import util from sugar3.graphics.xocolor import XoColor _profile = None class Profile(object): """Local user's current options/profile inf...
DATE_FORMAT = 'j. F Y' TIME_FORMAT = 'H:i' DATETIME_FORMAT = 'j. F Y H:i' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'd.m.Y' SHORT_DATETIME_FORMAT = 'd.m.Y H:i' FIRST_DAY_OF_WEEK = 1 # Monday DATE_INPUT_FORMATS = ( '%Y-%m-%d', '%j.%m.%Y', '%j.%m.%y', # '2006-10-25', '25.10.2006...
from django.db import ( models, transaction ) from django.utils.translation import ugettext class Inbox(models.Model): """ Inbox """ did = models.CharField(ugettext("device id"), max_length="250") ctime = models.DateTimeField(ugettext("ctime"), auto_now_add=True) utime = models.DateTimeField(u...
from msrest.serialization import Model class Resource(Model): """Azure resource. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :param name: Resource Name. :type name: str :param kind: Kind of resource. ...
"""Tests for TensorFlow Debugger (tfdbg) Utilities.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.core.protobuf import config_pb2 from tensorflow.python.client import session from tensorflow.python.debug.lib import de...
import sys, os, os.path, popen2 import gtk # To configure the script, you should only need to edit these values device = '0,0,0' driver = 'mmc_cdr' options = 'driveropts=burnproof' dummy = '-dummy' # To actually burn CDs, uncomment the following line and comment out the next one #burn_command_template = 'mkisofs -gu...
def generate_dot(data, root_node): prefix = '<f0>' dotcode = ''' graph G { graph [ overlap="scale", bgcolor="#475672", concentrate="true",rankdir="LR" , root="%s"] node [color=azure3, fontcolor=white, fillcolor="#373D49", shape=circle, style=filled, height=0.7,width=0.7]; "%s" [height=1, width=1,...
""" Metric data handler Used to add entries to the database or fetch data from it. Only handles the requests get/post. Fetching or inserting data is done in the database module """ import time from flask import request from flask.json import jsonify from werkzeug.exceptions import abort from pyMetricServer import a...
#!/usr/bin/env python2 """ Miscellaneous Routines. """ import struct from sys import maxint as INF ## Matrix operations ## MATRIX_IDENTITY = (1, 0, 0, 1, 0, 0) def mult_matrix((a1,b1,c1,d1,e1,f1), (a0,b0,c0,d0,e0,f0)): """Returns the multiplication of two matrices.""" return (a0*a1+c0*b1, b0*a1+d0*b1, ...
ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'version': '1.0'} import re from ansible.module_utils.nxos import get_config, load_config from ansible.module_utils.nxos import nxos_argument_spec, check_args from ansible.module_utils.basic import AnsibleMo...
""" opcode module - potentially shared between dis and other modules which operate on bytecodes (e.g. peephole optimizers). """ __all__ = ["cmp_op", "hasconst", "hasname", "hasjrel", "hasjabs", "haslocal", "hascompare", "hasfree", "opname", "opmap", "HAVE_ARGUMENT", "EXTENDED_ARG"] cmp_op = ('<'...
from __future__ import absolute_import import ast from mccabe import PathGraphingAstVisitor from prospector.message import Location, Message from prospector.tools.base import ToolBase __all__ = ( 'McCabeTool', ) class McCabeTool(ToolBase): def __init__(self, *args, **kwargs): super(McCabeTool, sel...
import os import pytest import sh from molecule import config from molecule.dependency import ansible_galaxy @pytest.fixture def _patched_ansible_galaxy_has_requirements_file(mocker): m = mocker.patch(('molecule.dependency.ansible_galaxy.' 'AnsibleGalaxy._has_requirements_file')) m.ret...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'network'} import re from copy import deepcopy from ansible.module_utils.network.nxos.nxos import get_co...
from importLib import Import, InvalidArchError, \ InvalidChannelError, InvalidChannelFamilyError, MissingParentChannelError from spacewalk.common.rhnConfig import CFG from spacewalk.satellite_tools.syncLib import log class ChannelImport(Import): def __init__(self, batch, backend): Import.__init__(self,...
# pylint: skip-file # flake8: noqa # pylint: disable=too-many-instance-attributes class OCProcess(OpenShiftCLI): ''' Class to wrap the oc command line tools ''' # pylint allows 5. we need 6 # pylint: disable=too-many-arguments def __init__(self, namespace, tname=None...
import marsyas import json from marsyas_util import * net = marsyas.system_from_script(""" Network : Series { + public frequency = 440.0 + public g0 = 1.0 + public g1 = 0.1 + public g2 = 0.2 + public g3 = 0.1 israte = 44100.0 -> Fanout { -> f0: Series {-> sin1: SineS...
"""Implement a workflow for testing.""" from invenio_workflows.tasks.sample_tasks import task_b, add_data, generate_error class demo_workflow_error(object): """Test workflow for unit-tests.""" workflow = [ task_b, task_b, add_data(15), generate_error ]
import unittest from urllib3.connectionpool import ( connection_from_url, HTTPConnection, HTTPConnectionPool, ) from urllib3.util.timeout import Timeout from urllib3.packages.ssl_match_hostname import CertificateError from urllib3.exceptions import ( ClosedPoolError, EmptyPoolError, HostChanged...
# Embedded file name: /usr/lib/enigma2/python/Components/Converter/RdsInfo.py from enigma import iRdsDecoder, iPlayableService from Components.Converter.Converter import Converter from Components.Element import cached class RdsInfo(Converter, object): RASS_INTERACTIVE_AVAILABLE = 0 RTP_TEXT_CHANGED = 1 ...
""" Profile all bench_list """ import subprocess as sp import pandas as pd import argparse from util import * import socket rpt_cmd = "opreport -l -n".split() # read a list of interested kernels def trim_func_param(infile, outfile): with open(infile, "r") as inf, open(outfile, "w") as outf: for line in ...
import uuid import mock from sahara import conductor from sahara import context from sahara.tests.unit import base from sahara.tests.unit.conductor import test_api from sahara.utils import cluster_progress_ops as cpo class FakeInstance(object): def __init__(self): self.id = uuid.uuid4() self.nam...
from rpc import RPC, RPCReply from ncclient.xml_ import * import util class GetReply(RPCReply): """Adds attributes for the *data* element to `RPCReply`.""" def _parsing_hook(self, root): self._data = None if not self._errors: self._data = root.find(qualify("data")) @pro...
"""Sparse DIAgonal format""" from __future__ import division, print_function, absolute_import __docformat__ = "restructuredtext en" __all__ = ['dia_matrix', 'isspmatrix_dia'] import numpy as np from .base import isspmatrix, _formats from .data import _data_matrix from .sputils import isshape, upcast_char, getdtype...
DATE_FORMAT = 'j. F Y.' TIME_FORMAT = 'H:i' DATETIME_FORMAT = 'j. F Y. H:i' YEAR_MONTH_FORMAT = 'F Y.' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'j.m.Y.' SHORT_DATETIME_FORMAT = 'j.m.Y. H:i' FIRST_DAY_OF_WEEK = 1 # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/libr...
import json from ansible.module_utils._text import to_text from ansible.module_utils.basic import env_fallback from ansible.module_utils.network.common.utils import to_list, ComplexList from ansible.module_utils.connection import Connection, ConnectionError _DEVICE_CONFIGS = {} routeros_provider_spec = { 'host': ...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os from ansible.compat.six import iteritems, string_types from ansible.errors import AnsibleError, AnsibleParserError from ansible.module_utils._text import to_native from ansible.parsing.mod_args import ModuleArgsParser fr...
from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _, ugettext from readthedocs.builds.models import Version from readthedocs.projects.models import Project class Bookmark(models.Model): user = models.ForeignKey(User, verbose_name=_('Use...
"""Examine Xorg log in guest for qxl presence. """ import logging from spice.lib import act from spice.lib import stest from spice.lib import utils logger = logging.getLogger(__name__) def run(vt_test, test_params, env): """Inspects Xorg logs for QLX presence. Parameters ---------- vt_test : avoca...
import urllib import urlparse import hashlib from django import template from django.template.loader import render_to_string from django.utils.translation import ugettext as _ from django.core.urlresolvers import reverse from avatar.settings import (AVATAR_GRAVATAR_BACKUP, AVATAR_GRAVATAR_DEFAULT, ...
import re from stemming.porter2 import stem from robly_data import stop_words class QueryParser(object): """ The QueryParser class parses the context and the search query form the string typed by the user. """ search_query = "" search_context = "" initial_search_query = "" search_token...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type class FactNamespace: def __init__(self, namespace_name): self.namespace_name = namespace_name def transform(self, name): '''Take a text name, and transforms it as needed (add a namespace prefix, etc)''' ...
"""Abstraction form AEMET OpenData sensors.""" from homeassistant.components.sensor import SensorEntity from homeassistant.const import ATTR_ATTRIBUTION from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import ATTRIBUTION, SENSOR_DEVICE_CLASS, SENSOR_NAME, SENSOR_UNIT from .weather_upd...
"""Base script for generated CLI.""" import atexit import code import logging import os import readline import rlcompleter import sys from google.apputils import appcommands import gflags as flags from apitools.base.py import encoding from apitools.base.py import exceptions __all__ = [ 'ConsoleWithReadline', ...
from threading import Thread import datetime import time import os from PIL import Image from .. import test_image, test_dm3_tilt_series class TIFFWriter(Thread): def __init__(self, path, delay=1): """ Thread to write a TIFF image stack to a particular path. The files are written using the...
from xml.etree.cElementTree import parse from Tools.XMLTools import elementsWithTag, mergeText, stringToXML from enigma import eDVBCIInterfaces, eDVBCI_UI, eEnv, eServiceCenter, eServiceReference from timer import TimerEntry import NavigationInstance import os class CIHelper: CI_ASSIGNMENT_LIST = None CI_ASSIGNME...
## \file ## \ingroup tutorial_pyroot ## \notebook -nodraw ## example of macro to read data from an ascii file and ## create a root file with a Tree. ## ## NOTE: comparing the results of this macro with those of staff.C, you'll ## notice that the resultant file is a couple of bytes smaller, because the ## code below str...
import time import numpy as np import random import colorsys from animation.abstract_animation import AbstractAnimation class MoodlightAnimation(AbstractAnimation): def __init__(self, width, height, frame_queue, repeat=False, mode="wish_down_up"): super().__init__(width, height, frame_q...
#!/usr/bin/env python ######################################################################### # Reinforcement Learning with PGPE on the FlexCube Environment # # The FlexCube Environment is a Mass-Spring-System composed of 8 mass points. # These resemble a cube with flexible edges. # # Control/Actions: # The agent ca...
from __future__ import absolute_import, division, print_function, with_statement __all__ = ['Queue', 'PriorityQueue', 'LifoQueue', 'QueueFull', 'QueueEmpty'] import collections import heapq from tornado import gen, ioloop from tornado.concurrent import Future from tornado.locks import Event class QueueEmpty(Except...
import unittest raise unittest.SkipTest("Unit test temporarily disabled - see: https://github.com/opencog/opencog/issues/442") from unittest import TestCase from opencog.atomspace import AtomSpace, types, Atom, TruthValue from pln.rules import * from pln.chainers import Chainer class RulesTest(TestCase): def set...
from __future__ import absolute_import, division, unicode_literals from types import ModuleType from pip._vendor.six import text_type try: import xml.etree.cElementTree as default_etree except ImportError: import xml.etree.ElementTree as default_etree __all__ = ["default_etree", "MethodDispatcher", "isSurr...
from polynomial import Poly def LexPoly(*args): """Returns a polynomial with lexicographic order of terms. """ return Poly(*args, **{ 'order' : 'lex' }) from algorithms import poly_div, poly_pdiv, poly_groebner, poly_lcm, poly_gcd, \ poly_half_gcdex, poly_gcdex, poly_sqf, poly_resultant, poly_subresultant...
import requests from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter, OAuth2LoginView, OAuth2CallbackView) from .provider import SoundCloudProvider class SoundCloudOAuth2Adapter(OAut...
import copy import mock from nova.api.openstack.compute.contrib import hypervisors as hypervisors_v2 from nova.api.openstack.compute.plugins.v3 import hypervisors \ as hypervisors_v21 from nova.api.openstack import extensions from nova import exception from nova import objects from nova import test from nova.test...
import yaml from pychron.canvas.canvas2D.scene.primitives.strat import StratItem from pychron.canvas.canvas2D.scene.scene import Scene class StratScene(Scene): def load(self, p): self.reset_layers() heights = [] ages = [] lowages = [] highages = [] # items=[] ...
""" Module to read / write Fortran unformatted sequential files. This is in the spirit of code written by Neil Martinsen-Burrell and Joe Zuntz. """ import warnings import numpy as np __all__ = ['FortranFile', 'FortranEOFError', 'FortranFormattingError'] class FortranEOFError(TypeError, IOError): """Indicates t...
from __future__ import unicode_literals import frappe, os, copy, json, re from frappe import _ from frappe.modules import get_doc_path from jinja2 import TemplateNotFound from frappe.utils import cint, strip_html from frappe.utils.pdf import get_pdf no_cache = 1 no_sitemap = 1 base_template_path = "templates/pages/...
ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['stableinterface'], 'supported_by': 'community'} import traceback SSHPUBKEYS_IMP_ERR = None try: import sshpubkeys HAS_LIB_SSHPUBKEYS = True except ImportError: SSHPUBKEYS_IMP_ERR = traceback.format_exc() ...
import re xpath_tokenizer = re.compile( "(::|\.\.|\(\)|[/.*:\[\]\(\)@=])|((?:\{[^}]+\})?[^/:\[\]\(\)@=\s]+)|\s+" ).findall class xpath_descendant_or_self: pass ## # Wrapper for a compiled XPath. class Path: ## # Create an Path instance from an XPath expression. def __init__(self, path): ...
from dateutil.tz import tzlocal, tzutc from lxml import etree def ensure_timezone(dt, tz=None): """ Make sure the datetime <dt> has a timezone set, using timezone <tz> if it doesn't. <tz> defaults to the local timezone. """ if dt.tzinfo is None: return dt.replace(tzinfo=tz or tzlocal()) ...
from __future__ import absolute_import from __future__ import print_function import autograd.numpy as np import itertools as it from autograd.core import grad, safe_type from copy import copy from autograd.numpy.use_gpu_numpy import use_gpu_numpy from autograd.container_types import ListNode, TupleNode import six from ...
import os import sys try: import DIRECT except ImportError: raise ImportError(""" In order to use this module, DIRECT need to be installed. Try running pip install direct """) import numpy as np from robo.maximizers.base_maximizer import BaseMaximizer class Direct(BaseMaximizer): d...
class FitDataCache: def __init__(self): self._data = {} def clearForFit(self, fitID): if fitID in self._data: del self._data[fitID] def clearAll(self): self._data.clear()
import os def enforce_tmp(name, contents=None): """ Enforce a temp file has the desired contents. name The name of the file to change. (Under '/tmp'.) contents The value you will be storing. """ return_dict = { 'name': name, 'changes': {}, 'result': Fal...
from django.test import TestCase class AdminBasicTest(TestCase): def test_admin_loads(self): self.assertTrue(self.client.login(username='staff', password='123')) res = self.client.get('/admin/') self.assertEqual(res.status_code, 200) def test_permissions(self): self.assertTrue(...
class NodeVisitor(object): def visit(self, node): # This is ugly as hell, but we don't have multimethods and # they aren't trivial to fake without access to the class # object from the class body func = getattr(self, "visit_%s" % (node.__class__.__name__)) return func(node) ...
""" ============= Masked Arrays ============= Arrays sometimes contain invalid or missing data. When doing operations on such arrays, we wish to suppress invalid values, which is the purpose masked arrays fulfill (an example of typical use is given below). For example, examine the following array: >>> x = np.array(...
""" Useful form fields for use with SQLAlchemy ORM. """ from __future__ import unicode_literals import operator from wtforms import widgets from wtforms.compat import text_type, string_types from wtforms.fields import SelectFieldBase from wtforms.validators import ValidationError try: from sqlalchemy.orm.util im...
import logging logging.basicConfig(level=logging.DEBUG) from plex_metadata import Guid def test_tvdb_show(): guids = [ 'com.plexapp.agents.thetvdb://12345?lang=en' ] for item in guids: r = Guid.parse(item) assert r.agent == 'tvdb' assert r.sid == '12345' assert ...
__author__ = '<EMAIL> (Jeff Scudder)' import unittest import atom.http_core import atom.auth import atom.client import atom.mock_http_core class AtomPubClientEchoTest(unittest.TestCase): def test_simple_request_with_no_client_defaults(self): client = atom.client.AtomPubClient(atom.mock_http_core.EchoHttpClie...
from __future__ import absolute_import, division, print_function __metaclass__ = type import pytest from units.modules.utils import set_module_args, exit_json, fail_json, AnsibleExitJson from ansible.module_utils import basic from ansible.modules.network.check_point import cp_mgmt_dns_domain_facts OBJECT = { "fr...
from django import db from django.conf import settings from django.contrib.contenttypes.models import ContentType from django.contrib.sites.models import Site from django.contrib.contenttypes.views import shortcut from django.core.exceptions import ObjectDoesNotExist from django.http import HttpRequest from django.test...
import numpy as np from sklearn_pmml.convert.test.jpmml_test import JPMMLClassificationTest, JPMMLRegressionTest, TARGET_NAME, TARGET from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor from sklearn_pmml.convert import TransformationContext, pmml_row, ModelMode, Schema from sklearn_pmml.convert.fea...
''' Helper classes for management commands. ''' from django.core.management.base import BaseCommand, CommandError from django.db import transaction from optparse import make_option from weblate.trans.models import Unit, SubProject, Translation class WeblateCommand(BaseCommand): ''' Command which accepts proj...
import numpy as np from numba import double, jit import k3d @jit((double[:,:], double[:], double, double)) def lennardjones(U, box, sigma = 0.3405, epsilon=0.9959): ndim = len(U) npart = len(U[0]) F = np.zeros((ndim, npart)) Epot = 0.0 Vir = 0.0 C = epsilon/sigma**2*48 rc2 ...
import sys import dlib from skimage import io detector = dlib.get_frontal_face_detector() win = dlib.image_window() for f in sys.argv[1:]: print("Processing file: {}".format(f)) img = io.imread(f) # The 1 in the second argument indicates that we should upsample the image # 1 time. This will make ev...