content
stringlengths
4
20k
from __future__ import division, print_function, absolute_import import warnings import numpy as np from numpy import array from numpy.testing import (assert_array_almost_equal, assert_array_equal, run_module_suite, assert_raises, assert_allclose) from scipy import signal window_funcs = [ ...
import sys import Adafruit_DHT # Parse command line parameters. sensor_args = { '11': Adafruit_DHT.DHT11, '22': Adafruit_DHT.DHT22, '2302': Adafruit_DHT.AM2302 } if len(sys.argv) == 3 and sys.argv[1] in sensor_args: sensor = sensor_args[sys.argv[1]] pin = sys.argv[2] else: print 'usage: sudo ./Adafruit_DH...
import webob.exc from neutron.api.v2 import attributes as attr from neutron.common import exceptions as nexception from oslo.config import cfg allowed_address_pair_opts = [ #TODO(limao): use quota framework when it support quota for attributes cfg.IntOpt('max_allowed_address_pair', default=10, ...
import re import requests from pygerrit.rest import GerritRestAPI DEFAULT_GERRIT_URL = 'https://review.openstack.org' class GerritReview(object): def __init__(self, changeid, project, gerrit_url=DEFAULT_GERRIT_URL): self.changeid = changeid self.project = project self._gerrit_url = ger...
""" Collection of physical constants and conversion factors. Most constants are in SI units, so you can do print '10 mile per minute is', 10*mile/minute, 'm/s or', 10*mile/(minute*knot), 'knots' The list is not meant to be comprehensive, but just a convenient list for everyday use. """ """ BasSw 2006 physical consta...
"""Disassembler of Python byte code into mnemonics.""" import sys import types import collections import io from opcode import * from opcode import __all__ as _opcodes_all __all__ = ["code_info", "dis", "disassemble", "distb", "disco", "findlinestarts", "findlabels", "show_code", "get_instructi...
import os import pickle import time import numpy as np import torch from spotlight.layers import BloomEmbedding, ScaledEmbedding from spotlight.factorization.implicit import ImplicitFactorizationModel from spotlight.factorization.representations import BilinearNet from spotlight.sequence.implicit import ImplicitSequ...
"""Runs linker tests on a particular device.""" import logging import os.path import sys import traceback from pylib import constants from pylib.base import base_test_result from pylib.base import base_test_runner from pylib.linker import test_case from pylib.utils import apk_helper # Name of the Android package to...
import time import heapq from pax import plugin, utils, exceptions, datastructure from pax.parallel import queue, RabbitQueue, NO_MORE_EVENTS, REGISTER_PUSHER, PUSHER_DONE, DEFAULT_RABBIT_URI def get_queue_from_config(config): """Given a queueplugin config, get the queue from it Yeah, should have maybe made ...
import gobject import gtk import time import dbus import getopt import sys TRACKER = 'org.freedesktop.Tracker1' TRACKER_OBJ = '/org/freedesktop/Tracker1/Resources' SPARQL_QUERY = """ SELECT ?entry ?title ?date ?isRead WHERE { ?entry a nmo:FeedMessage ; nie:title ?title ; nie:contentLastMod...
__kupfer_name__ = _("Kupfer Plugins") __kupfer_sources__ = ("KupferPlugins", ) __description__ = _("Access Kupfer's plugin list in Kupfer") __version__ = "" __author__ = "Ulrik Sverdrup <<EMAIL>>" import os from kupfer.objects import Action, Source, Leaf, FileLeaf, TextLeaf from kupfer import icons from kupfer import...
#!/usr/bin/env python import warnings import re import subprocess import types import yaml import pandas as pd import numpy as np import rosbag import rospy from roslib.message import get_message_class def bag_to_dataframe(bag_name, include=None, exclude=None, parse_header=False, seconds=False): ''' Read i...
""" ************************************* **Module**: pydarn.sdio.fitexfilter ************************************* Filter fitexfiles natively in python .. warning:: This is very SLOW. We are currently working on this. We recommend using the c version which is folded into :func:`pydarn.sdio.radDataRead.radDataOpen...
import traceback import maya.cmds as cmds import _functions as fnt """ Attach to existing """ def attachTimeAndFile(node, jobInfo, isConstant=False): connAttr = cmds.connectionInfo(node+".inTime", sfd=True) if connAttr == "" and not isConstant: cmds.connectAttr(jobInfo.timeCtrl+".outTime", node+".inTime") nod...
import six import yaml from nailgun.errors import errors from nailgun import objects from nailgun.settings import settings from nailgun.test import base from nailgun.utils.restrictions import AttributesRestriction from nailgun.utils.restrictions import LimitsMixin from nailgun.utils.restrictions import RestrictionBase...
# This is the Python restserver module used in the websocket server by # restserver_wsh.py and AJAX server by ajaxserver.py. import logging, sqlite3, json, time, random, re logger = logging.getLogger('restserver') class Database(): def __init__(self, filename="restserver.db"): self.conn = sqlite3.connect...
"""Provides email services.""" __author__ = 'Sean Lip' from core import counters import feconf from google.appengine.api import app_identity from google.appengine.api import mail def send_mail_to_admin(subject, body): """Enqueues a 'send email' request with the GAE mail service. Args: - subject: st...
import os import sys from gunicorn.app.base import Application from gunicorn import util def is_setting_mod(path): return (os.path.isfile(os.path.join(path, "settings.py")) or os.path.isfile(os.path.join(path, "settings.pyc"))) def find_settings_module(path): path = os.path.abspath(path) pr...
"""Suite Finder Basics: Commonly-used Finder commands and object classes Level 1, version 1 Generated from /System/Library/CoreServices/Finder.app AETE/AEUT resource version 0/144, language 0, script 0 """ import aetools import MacOS _code = 'fndr' class Finder_Basics_Events: def copy(self, _no_object=None, _a...
import unittest from datetime import timedelta, datetime from mock import patch, MagicMock from pokemongo_bot.cell_workers.sleep_schedule import SleepSchedule from tests import FakeBot class SleepScheculeTestCase(unittest.TestCase): config = {'time': '12:20', 'duration': '01:05', 'time_random_offset': '00:05', 'd...
#!/usr/bin/python ''' Extract _("...") strings for translation and convert to Qt4 stringdefs so that they can be picked up by Qt linguist. ''' from subprocess import Popen, PIPE import glob import operator OUT_CPP="src/qt/freicoinstrings.cpp" EMPTY=['""'] def parse_po(text): """ Parse 'po' format produced by ...
"""I contain PythonScript, which is a very simple python script resource. """ import server import resource import html import error try: import cStringIO as StringIO except ImportError: import StringIO from twisted.web import http from twisted import copyright import traceback import os from twisted.web imp...
#!/usr/bin/env python """ Converts a pickle file containing CudaNdarraySharedVariables into a pickle file containing only TensorSharedVariables. Usage: gpu_pkl_to_cpu_pkl.py <gpu.pkl> <cpu.pkl> Loads gpu.pkl, replaces cuda shared variables with numpy ones, and saves to cpu.pkl. If you create a model while using GPU...
#!/usr/bin/env python # Test whether a connection is successful with correct username and password # when using a simple auth_plugin. import subprocess import socket import time import inspect, os, sys # From http://stackoverflow.com/questions/279237/python-import-a-module-from-a-folder cmd_subfolder = os.path.realp...
import math from gnuradio import gr, gr_unittest, digital class test_lfsr(gr_unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_lfsr_001(self): reglen = 8 l = digital.lfsr(1, 1, reglen) result_data = [] for i in xrange(4*(reglen+...
#!/usr/bin/python import copy import datetime import testing as T from core.util import EscapedDict from core.util import get_servlet_urlspec from core.util import pretty_date from core.util import add_to_tags_str from core.util import del_from_tags_str from core.util import tags_contain from core.util import tags_st...
"""Global IPython app to support test running. We must start our own ipython object and heavily muck with it so that all the modifications IPython makes to system behavior don't send the doctest machinery into a fit. This code should be considered a gross hack, but it gets the job done. """ from __future__ import abs...
from datetime import datetime from back.utils import parse_float, parse_int, parse_number, parse_string, parse_date, parse_list, preprocess_date, \ replace_field_space, check_if_list, convert_list, get_key_value, process_data def test_parse_float(): value = parse_float("10.2") assert value == 10.2 ...
"""Test fixtures.""" from builtins import super import pytest from napalm_base.test import conftest as parent_conftest from napalm_base.test.double import BaseTestDouble from napalm_base.utils import py23_compat from napalm_nxos_ssh import nxos_ssh @pytest.fixture(scope='class') def set_device_parameters(request): ...
# usage: genmetaindex.py <xml-files> > index.xml import sys, os from xml.etree.ElementTree import ElementTree, Element root = Element("index") for file in sys.argv[1:]: p = ElementTree() p.parse(file) package = Element("package") package.set("details", os.path.basename(file)) # we need all prerequisites pack...
import os import os.path from sickbeard import logger # This module tries to deal with the apparently random behavior of python when dealing with unicode <-> utf-8 # encodings. It tries to just use unicode, but if that fails then it tries forcing it to utf-8. Any functions # which return something should alway...
from jedi._compatibility import encoding, is_py3, u import inspect import os import time def _lazy_colorama_init(): """ Lazily init colorama if necessary, not to screw up stdout is debug not enabled. This version of the function does nothing. """ pass _inited=False try: if os.name == 'nt...
from __future__ import absolute_import, unicode_literals import os import sys import types from celery.app.defaults import strtobool from celery.utils import import_from_cwd DEFAULT_APPS = ('django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', ...
from sympy.physics.vector import dynamicsymbols, Point, ReferenceFrame def test_point_v1pt_theorys(): q, q2 = dynamicsymbols('q q2') qd, q2d = dynamicsymbols('q q2', 1) qdd, q2dd = dynamicsymbols('q q2', 2) N = ReferenceFrame('N') B = ReferenceFrame('B') B.set_ang_vel(N, qd * B.z) O = Poin...
ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} 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_utils.basic im...
import purchase_requisition import wizard # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['stableinterface'], 'supported_by': 'community'} import json import os import pipes import stat from ansible.module_utils.basic impor...
""" Graphical user interface widgets.""" from typing import Callable, Optional, List, Tuple, Generator from eaf import Timer from xo1 import Surface, Renderable from xoinvader.style import Style from xoinvader.utils import ( InfiniteList, Point, ) class TextWidget(Renderable): """Simple text widget. ...
#!/usr/bin/env python import unittest from ansible.modules.cloud.google.gce_tag import _get_changed_items, _intersect_items, _union_items class TestGCETag(unittest.TestCase): """Unit tests for gce_tag module.""" def test_union_items(self): """ Combine items in both lists removing dup...
oneline = "Create plots via GnuPlot plotting program" docstr = """ g = gnu() start up GnuPlot g.stop() shut down GnuPlot process g.plot(a) plot vector A against linear index g.plot(a,b) plot B against A g.plot(a,b,c,d,...) plot B against A, D against C, etc g.m...
""" Tests for Layer1 of Cloudsearch """ import time from tests.unit import unittest from boto.cloudsearch2.layer1 import CloudSearchConnection from boto.cloudsearch2.layer2 import Layer2 from boto.regioninfo import RegionInfo class CloudSearchLayer1Test(unittest.TestCase): cloudsearch = True def setUp(self)...
import time from datetime import datetime class DatabaseStorage(object): ''' Base class for database storages. ''' time_format = '%Y-%m-%d %H:%M:%S' tablename = 'METEO' mandatory_storage_fields = ['TEMP', 'HUM', 'DEW_POINT', 'WIND', 'WIND_DIR', 'WIND_GUST', ...
class RyuException(Exception): message = 'An unknown exception' def __init__(self, msg=None, **kwargs): self.kwargs = kwargs if msg is None: msg = self.message try: msg = msg % kwargs except Exception: msg = self.message super(RyuExc...
from __future__ import print_function import argparse import logging logging.basicConfig(level=logging.DEBUG) import numpy as np import mxnet as mx from mxnet import gluon, autograd from mxnet.gluon import nn # Parse CLI arguments parser = argparse.ArgumentParser(description='MXNet Gluon MNIST Example') parser.add_...
from django.contrib.messages import constants from django.contrib.messages.storage import default_storage from django.utils.functional import lazy, memoize __all__ = ( 'add_message', 'get_messages', 'get_level', 'set_level', 'debug', 'info', 'success', 'warning', 'error', ) class MessageFailure(Exception...
from utils import clean_html str = '''<b>redy</b> <img src="data:image/jpeg;base64,"> <<script></script>script> alert("Haha, I hacked your page."); <<script></script>script> ''' html = ''' both <em id="foo" style="color: black">can</em> have <img id="bar" src="foo"/...
class FileSystemError(Exception): pass class NodeDoesNotExistError(FileSystemError): pass class SourceNodeDoesNotExistError(NodeDoesNotExistError, FileSystemError): pass class DestinationNodeDoesNotExistError(NodeDoesNotExistError, FileSystemError): pass class FileSystemMountError(FileSystemErro...
import io import selectors import socket def is_readable(fileobj, *, timeout=None): """Check that the file-like resource is readable within the given timeout via polling. :param Union[int, SupportsFileNo] fileobj: :param Optional[int] timeout: (in seconds) :return bool """ with selectors.Defa...
import mox from unittest import TestCase from trayjenkins.event import Event, IEvent from trayjenkins.jobs import IModel as JobsModel, IFilter, JobModel from trayjenkins.status import IModel, IView, Presenter, IMessageComposer,\ IStatusReader, Model, StatusReader, DefaultMessageComposer from pyjenkins.job import J...
''' SASMOL: Copyright (C) 2011 Joseph E. Curtis, Ph.D. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ...
#!/usr/bin/env python ''' MIT License Copyright (c) 2017 Tairan Liu Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, mod...
import os import time from . import loggable import subprocess import sys import urllib.request, urllib.error, urllib.parse logcat = "httpserver" class HTTPServer(loggable.Loggable): """ Class to run a SimpleHttpServer in a process.""" def __init__(self, options): loggable.Loggable.__init__(self) ...
#!/usr/bin/env python3 """ Copyright (c) August Yip (http://august.hk/) """ import time import curses from curses import wrapper from datetime import datetime import sys, traceback from lib.core.config import config from lib.source.yahoo import yahoo from lib.source.tencent import tencent def main() : return ...
def _(): import sys if sys.platform == 'cli': import clr clr.AddReference('IronPython.SQLite') _() del _ from dbapi2 import *
# -*- encoding: utf-8 -*- from abjad.tools import mathtools def partition_sequence_by_weights( sequence, weights, cyclic=False, overhang=False, allow_part_weights=Exact, ): r'''Partitions `sequence` by `weights` exactly. :: >>> sequence = [3, 3, 3, 3, 4, 4, 4, 4, 5] .. ...
"""Celery tasks for export jobs.""" from __future__ import absolute_import, print_function from celery import shared_task from flask import current_app from .api import Exporter @shared_task def export_job(job_id=None): """Export job.""" job_definition = current_app.extensions['invenio-exporter'].job(job_i...
"""Wrappers for the single tasks, multi processor handling.""" from __future__ import division # Built ins import logging import os from shutil import rmtree import collections # External libs import pandas as pd import multiprocessing as mp # Locals import oggm from oggm import cfg, tasks, utils # MPI try: impo...
# -*- coding: utf-8 -*- """ pygments.lexers.automation ~~~~~~~~~~~~~~~~~~~~~~~~~~ Lexers for automation scripting languages. :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ from pygments.lexer import RegexLexer, include, bygroups, com...
from __future__ import absolute_import, unicode_literals from django.contrib.syndication import views from django.core.exceptions import ObjectDoesNotExist from django.utils import feedgenerator, tzinfo from .models import Article, Entry class ComplexFeed(views.Feed): def get_object(self, request, foo=None): ...
import os import re import sys import subprocess from os.path import dirname, abspath from pip._vendor.six.moves.urllib import request as urllib_request from pip.utils import rmtree src_folder = dirname(dirname(abspath(__file__))) if sys.platform == 'win32': bin_dir = 'Scripts' else: bin_dir = 'bin' def ...
import frappe from erpnext.setup.install import create_compact_item_print_custom_field from frappe.utils import cint def execute(): frappe.reload_doctype('Stock Settings') stock_settings = frappe.get_doc('Stock Settings', 'Stock Settings') stock_settings.show_barcode_field = cint(frappe.db.get_value("Features Setu...
import web import json import threading urls = ('/(.*)', 'API') app = web.application(urls, globals()) db = {} nextid = 0 # Very simple REST API application built with web.py class API(): def GET(self, id=None): global db, nextid if(len(id) == 0): return json.dumps(db...
"""Tests for debugger functionalities under multiple (i.e., >1) GPUs.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import shutil import tempfile from tensorflow.core.protobuf import config_pb2 from tensorflow.python.client import device_lib ...
""" The :mod:`sklearn.exceptions` module includes all custom warnings and error classes used across scikit-learn. """ __all__ = ['NotFittedError', 'ChangedBehaviorWarning', 'ConvergenceWarning', 'DataConversionWarning', 'DataDimensionalityWarning', 'EfficiencyWarn...
import os import tempfile from distutils.version import StrictVersion try: from passlib.apache import HtpasswdFile, htpasswd_context from passlib.context import CryptContext import passlib except ImportError: passlib_installed = False else: passlib_installed = True apache_hashes = ["apr_md5_crypt"...
from collections import namedtuple import textwrap import sys SHARD_FILENAME_TEMPLATE = "test/mjsunit/compiler/inline-exception-{shard}.js" # Generates 2 files. Found by trial and error. SHARD_SIZE = 97 PREAMBLE = """ // Copyright 2016 the V8 project authors. All rights reserved. // Use of this source code is govern...
"""Volume v1 Volume action implementations""" import argparse import six from openstackclient.common import command from openstackclient.common import parseractions from openstackclient.common import utils from openstackclient.i18n import _ class CreateVolume(command.ShowOne): """Create new volume""" def g...
from __future__ import absolute_import from django.test import TestCase from .models import Reporter, Article class ManyToOneNullTests(TestCase): def setUp(self): # Create a Reporter. self.r = Reporter(name='John Smith') self.r.save() # Create an Article. self.a = Article...
import posixpath from file_system import FileSystem, FileNotFoundError from future import Future from test_file_system import _List, _StatTracker, TestFileSystem from path_util import IsDirectory class MockFileSystem(FileSystem): '''Wraps FileSystems to add a selection of mock behaviour: - asserting how often St...
""" Flask-Informal -------------- Adds form abstraction and helpers to your Flask application. """ from setuptools import setup setup( name="Flask-Informal", version="0.1.0", url="https://github.com/pnelson/flask-informal", license="BSD", author="Philip Nelson", author_email="<EMAIL>", de...
from spack import * class PrintingPackage(Package): """This package prints some output from its install method. We use this to test whether that output is properly logged. """ homepage = "http://www.example.com/printing_package" url = "http://www.unit-test-should-replace-this-url/trivial_ins...
r''' This tests the '_objects' attribute of ctypes instances. '_objects' holds references to objects that must be kept alive as long as the ctypes instance, to make sure that the memory buffer is valid. WARNING: The '_objects' attribute is exposed ONLY for debugging ctypes itself, it MUST NEVER BE MODIFIED! '_object...
"""A class of Decoders that may sample to generate the next input. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections from tensorflow.contrib.rnn import core_rnn_cell from tensorflow.contrib.seq2seq.python.ops import decoder from tensor...
from __future__ import print_function import os, sys, time, threading, traceback 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 r = utils.import_python_driver() op = vcoptparse.OptParser()...
#!/usr/bin/python from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth.decorators import user_passes_test from django.db.models import Q from django.forms import modelformset_factory from django.shortcuts import render, redirect from elearning.course.fo...
from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) from pants.util.contextutil import temporary_dir from pants_test.pants_run_integration_test import PantsRunIntegrationTest class ScalastyleIntegrationTest(PantsRunIn...
import unittest import mock import hid_constants import keyboard_gadget import usb_constants class KeyboardGadgetTest(unittest.TestCase): def test_key_press(self): g = keyboard_gadget.KeyboardGadget() chip = mock.Mock() g.Connected(chip, usb_constants.Speed.FULL) g.KeyDown(0x04) self.assertEq...
# -*- coding: utf-8 -*- from __future__ import (unicode_literals, division, absolute_import, print_function) store_version = 1 # Needed for dynamic plugin loading __license__ = 'GPL 3' __copyright__ = '2011, John Schember <<EMAIL>>' __docformat__ = 'restructuredtext en' import re import urllib2 from contextlib impor...
from functools import reduce from stango.views import file_from_tar, static_file import collections import os import tarfile FilespecBase = collections.namedtuple('Filespec', 'path view kwargs') class Filespec(FilespecBase): def __new__(cls, path, view, kwargs={}): if not isinstance(path, str): ...
""" The OffsetBox is a simple container artist. The child artist are meant to be drawn at a relative position to its parent. The [VH]Packer, DrawingArea and TextArea are derived from the OffsetBox. The [VH]Packer automatically adjust the relative postisions of their children, which should be instances of the OffsetBo...
def drop_view_if_exists(cr, viewname): cr.execute("DROP view IF EXISTS %s CASCADE" % (viewname,)) cr.commit() # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
from fluentmock import UnitTests, when, verify, NEVER from mock import Mock from pybuilder.core import Project from pybuilder.plugins.filter_resources_plugin import ProjectDictWrapper class ProjectDictWrapperTest(UnitTests): def test_should_return_project_property_when_property_is_defined(self): project...
""" Module that provides a connection to the ModuleStore specified in the django settings. Passes settings.MODULESTORE as kwargs to MongoModuleStore """ from __future__ import absolute_import from importlib import import_module import logging import re from django.conf import settings # This configuration must be ...
class LRUCache: def __init__(self, capacity, dispose): self._cache = {} self._lru = [] self._capacity = capacity self._dispose = dispose def __setitem__(self, key, value): assert key not in self._cache, ( "Unexpected attempt to replace a cached item," ...
""" API v1 serializers. """ from rest_framework import serializers from commerce.api.v1.models import Course from course_modes.models import CourseMode class CourseModeSerializer(serializers.ModelSerializer): """ CourseMode serializer. """ name = serializers.CharField(source='mode_slug') price = serializ...
import tinctest import unittest2 as unittest from mpp.models import MPPTestCase from mpp.lib.PSQL import PSQL from gppylib.commands.base import Command from mpp.lib.gpConfig import GpConfig from tinctest.models.scenario import ScenarioTestCase class OOMTestCase(MPPTestCase, ScenarioTestCase): """ @product_ve...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import re import codecs from ansible.errors import AnsibleParserError from ansible.module_utils._text import to_text from ansible.parsing.quoting import unquote # Decode escapes adapted from rspeer's answer here: # http://stacko...
from xml.dom import minidom try: from urlparse import urlparse, parse_qsl except ImportError: from urllib.parse import urlparse, parse_qsl from django.conf import settings from django.test import TestCase from django.template import Template, Context from django.utils.unittest import skipIf from billing impor...
def normalize(path): """ normalize(path) Returns a normalized version of `path` taking care of ".." and "." parts. It removes all useless "/" but keeps the trailing one. Examples: # normalize path and remove trailing slashes path = normalize(path + "/.") # normalize path in...
""" Unittest for export to VCard """ import unittest import time import subprocess import sys import os import xml.etree.ElementTree as ET from ...lib.libgrampsxml import GRAMPS_XML_VERSION from gramps.version import VERSION from ..exportvcard import VCardWriter class VCardCheck(unittest.TestCase): def setUp(self...
import bson.json_util import pymongo import json from bson import ObjectId from pymongo import Connection import string import tangelo def convertStringToFloatPoint(lng,lat): print "(",lng,lat,")" if lat[-1:] == "S": outlat= -float(lat[:-1]) else: outlat = float(lat[:-1]) if lng[-1...
from django.conf import settings def format(number, decimal_sep, decimal_pos, grouping=0, thousand_sep=''): """ Gets a number (as a number or string), and returns it as a string, using formats definied as arguments: * decimal_sep: Decimal separator symbol (for example ".") * decimal_pos: Number of...
import pytest import shutil from unittest.mock import Mock, MagicMock, patch from libvirttestapi.utils import utils, process, nfs class Cmd_Result(): def __init__(self, exit_status, stderr, stdout): self.exit_status = exit_status self.stderr = stderr self.stdout = stdout ...
""" Initiate jobs at Browserstack Screenshots and downloads the images when they are complete. Optionally renames and slices images for use with PhantomCSS visual regression testing tool """ import math import os import sys import time import re import getopt import ConfigParser import subprocess from PIL import Im...
import pytest def test_my_api_select_bob(orb, my_sql, my_db, User): record = User.select(where=orb.Query('username') == 'bob').first() assert record is not None and record.get('username') == 'bob' def test_my_api_save_bill(orb, my_db, User): user = User({ 'username': 'bill', 'password': '...
""" Tests for user enrollment. """ import ddt import json import unittest from django.test.utils import override_settings from django.core.urlresolvers import reverse from rest_framework.test import APITestCase from rest_framework import status from django.conf import settings from datetime import datetime from mock i...
import abc import logging import traceback from multiprocessing.dummy import Pool class AbstractDownloader(object): """ Base class for download wrappers. Two methods should be implemented: `download` and `join`. """ __metaclass__ = abc.ABCMeta def __init__(self, file_downloader): supe...
from itools.core import prototype from itools.gettext import MSG ########################################################################### # Base classes ########################################################################### class Email(prototype): subject = None text = None def get_text_namespa...
from django.contrib.auth.models import User from gasistafelice.rest.views.blocks import users from flexi_auth.models import ParamRole from gasistafelice.consts import GAS_MEMBER from registration.models import RegistrationProfile from gasistafelice.gas.forms.base import GASSingleUserForm from django.forms.formsets...
import os from typing import Optional import semver from gitflow import _, version from gitflow.common import Result from gitflow.const import VersioningScheme from gitflow.version import VersionConfig def filter_sequence_number(version_config, prev_version, global_seq): if version_config.versioning_scheme == V...