content
string
from collections import OrderedDict import os from django.apps import apps from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.files.storage import default_storage, Storage, FileSystemStorage from django.utils.functional import empty, LazyObject from django.utils.m...
import Ice import sys from PyQt4.QtCore import * from PyQt4.QtGui import * from PyQt4.Qt import * class C(QWidget): def __init__(self, endpoint, modules): QWidget.__init__(self) self.ic = Ice.initialize(sys.argv) self.mods = modules self.prx = self.ic.stringToProxy(endpoint) self.proxy = self.mo...
import os import re import sys import argparse import collections from types import NoneType try: import json except: import simplejson as json try: import pyrax except ImportError: print('pyrax is required for this module') sys.exit(1) NON_CALLABLES = (basestring, bool, dict, int, list, NoneTyp...
""" WSGI middleware Gzip-encodes the response. """ import gzip from paste.response import header_value, remove_header from paste.httpheaders import CONTENT_LENGTH import six class GzipOutput(object): pass class middleware(object): def __init__(self, application, compress_level=6): self.application ...
import sys from tdbus import * CONN_AVAHI = 'org.freedesktop.Avahi' PATH_SERVER = '/' IFACE_SERVER = 'org.freedesktop.Avahi.Server' conn = Connection(DBUS_BUS_SYSTEM) dispatcher = BlockingDispatcher(conn) try: result = dispatcher.call_method(PATH_SERVER, 'GetVersionString', interface=IFAC...
import thread import time import os import sys sys.path.append(os.environ['PERF_EXEC_PATH'] + \ '/scripts/python/Perf-Trace-Util/lib/Perf/Trace') from perf_trace_context import * from Core import * from Util import * usage = "perf trace -s syscall-counts.py [comm] [interval]\n"; for_comm = None default_interval = ...
import code import readline import sys import ddt import mock from oslo_config import cfg import six from manila.cmd import manage as manila_manage from manila import context from manila import db from manila.db import migration from manila import test from manila import version CONF = cfg.CONF @ddt.ddt class Mani...
"""Aggregate interface.""" from novaclient import base class Aggregate(base.Resource): """An aggregates is a collection of compute hosts.""" def __repr__(self): return "<Aggregate: %s>" % self.id def update(self, values): """Update the name and/or availability zone.""" return se...
import os import json import stat import base64 import mimetools import mimetypes import httplib2 import ssl from httplib2 import httplib from time import gmtime, strftime from stratuslab import Util from stratuslab.ConfigHolder import ConfigHolder from stratuslab.Exceptions import ServerException from stratuslab.Excep...
"""Fixer for dict methods. d.keys() -> list(d.keys()) d.items() -> list(d.items()) d.values() -> list(d.values()) d.iterkeys() -> iter(d.keys()) d.iteritems() -> iter(d.items()) d.itervalues() -> iter(d.values()) d.viewkeys() -> d.keys() d.viewitems() -> d.items() d.viewvalues() -> d.values() Except in certain very...
""" Django settings for konnichiwa project. Generated by 'django-admin startproject' using Django 1.8.3. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build p...
#!/usr/bin/env python3 __author__ = 'DSOWASP' import socket import os import hashlib ip_port = ('127.0.0.1',9999) sk = socket.socket() sk.connect(ip_port) while True: cmd_input = input("cmd> ") # print("发送:%s"%cmd) cmd,fname = cmd_input.split() if os.path.exists(fname): ftell = os.path.gets...
from .web_reqrep import Response __all__ = ( 'HTTPException', 'HTTPError', 'HTTPRedirection', 'HTTPSuccessful', 'HTTPOk', 'HTTPCreated', 'HTTPAccepted', 'HTTPNonAuthoritativeInformation', 'HTTPNoContent', 'HTTPResetContent', 'HTTPPartialContent', 'HTTPMultipleChoices', ...
'''resourcegroups.py - azurerm functions for Resource Groups.''' import json from .restfns import do_delete, do_get, do_post, do_put from .settings import get_rm_endpoint, RESOURCE_API def create_resource_group(access_token, subscription_id, rgname, location): '''Create a resource group in the specified location....
"""Getting uniprot txt files for proteins parsing them loading parsed data.""" import os, time, sys import files from collections import defaultdict def parseProteinName(protein): with open(mkTxtFile(protein)) as f: for line in f: # DE RecName: Full=Fatty acid synthase; if l...
"""For internal use only. It provides a slice-like file reader.""" import os try: # pylint: disable=no-name-in-module from multiprocessing import Lock except ImportError: from threading import Lock class FileBuffer(object): """A slice-able file reader""" def __init__(self, database): s...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} import os import tempfile from ansible.module_utils.basic import AnsibleModule def packa...
import sys import datetime import requests def check_arguments(argv): date1 = date2 = None today = datetime.datetime.now().date() if len(argv)==1: date1 = datetime.date(year=datetime.datetime.now().date().year, month=datetime.datetime.now().date().month, day=1) date2 = today try: if len(argv)>1: if argv...
import sys import css_properties import in_generator from name_utilities import enum_for_css_keyword import template_expander class CSSOMTypesWriter(css_properties.CSSProperties): def __init__(self, in_file_path): super(CSSOMTypesWriter, self).__init__(in_file_path) for property in self._propert...
import account_voucher_sales_receipt # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
"""Component to allow users to login and get tokens. # POST /auth/token This is an OAuth2 endpoint for granting tokens. We currently support the grant types "authorization_code" and "refresh_token". Because we follow the OAuth2 spec, data should be send in formatted as x-www-form-urlencoded. Examples will be in JSON ...
import inspect import warnings from flask_admin.form import BaseForm, rules from flask_admin._compat import iteritems from wtforms.fields import HiddenField from wtforms.fields.core import UnboundField from wtforms.validators import InputRequired from .widgets import XEditableWidget def converts(*args): def _in...
""" Protocol agnostic implementations of SASL authentication mechanisms. """ from __future__ import absolute_import, division import binascii, random, time, os from hashlib import md5 from zope.interface import Interface, Attribute, implementer from twisted.python.compat import iteritems, networkString class ISAS...
""" File: WhoSampledScraper.py Author: Brad Jobe Version: 0.0.1 Scrapes relevant HTML content from an artist's track page """ import sys import eyed3 import urllib2 from lxml import html import httplib import json class WhoSampledScraper: URL_WHOSAMPLED = "www.whosampled.com" HTTP_PROTO = "http://" HTTP_...
import unittest from mock import Mock from mock import patch from airflow import configuration from airflow.contrib.hooks.jira_hook import JiraHook from airflow import models from airflow.utils import db jira_client_mock = Mock( name="jira_client" ) class TestJiraHook(unittest.TestCase): def setUp(self...
from .euctwfreq import (EUCTWCharToFreqOrder, EUCTW_TABLE_SIZE, EUCTW_TYPICAL_DISTRIBUTION_RATIO) from .euckrfreq import (EUCKRCharToFreqOrder, EUCKR_TABLE_SIZE, EUCKR_TYPICAL_DISTRIBUTION_RATIO) from .gb2312freq import (GB2312CharToFreqOrder, GB2312_TABLE_SIZE, ...
# -*- coding: utf-8 -*- import os import urlparse from django.db import models import markupsafe from addons.base import exceptions from addons.base.models import (BaseOAuthNodeSettings, BaseOAuthUserSettings, BaseStorageAddon) from addons.gitlab import utils from addons.gitlab.api imp...
import osc.core import osc.oscerr import os from common import OscTestCase FIXTURES_DIR = os.path.join(os.getcwd(), 'revertfile_fixtures') def suite(): import unittest return unittest.makeSuite(TestRevertFiles) class TestRevertFiles(OscTestCase): def _get_fixtures_dir(self): return FIXTURES_DIR ...
"""Tests for pylearn2.utils.video""" import numpy from theano.compat import six from pylearn2.compat import OrderedDict from pylearn2.utils.video import FrameLookup, spatiotemporal_cubes __author__ = "David Warde-Farley" __copyright__ = "Copyright 2011, David Warde-Farley / Universite de Montreal" __license__ = "BSD" ...
"""Test for Zenodo Auditor Record checks.""" from __future__ import absolute_import, print_function import logging import pytest from invenio_records.models import RecordMetadata from zenodo.modules.auditor.records import RecordAudit, RecordCheck from zenodo.modules.records.api import ZenodoRecord @pytest.fixture...
"""A Python interface for creating TensorFlow servers.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.core.framework import device_attributes_pb2 from tensorflow.python import pywrap_tensorflow def list_local_devices(session_config=Non...
from zaqarclient.auth import base from zaqarclient.auth import keystone from zaqarclient.auth import signed_url _BACKENDS = { 'noauth': base.NoAuth, 'keystone': keystone.KeystoneAuth, 'signed-url': signed_url.SignedURLAuth, } def get_backend(backend='keystone', options=None): """Loads backend `auth_b...
import os import socket import ssl from thriftpy3.transport import TSocket from thriftpy3.transport.TTransport import TTransportException class TSSLSocket(TSocket.TSocket): """ SSL implementation of client-side TSocket This class creates outbound sockets wrapped using the python standard ssl module for encr...
import getopt import math import os import struct import sys import wave def hide(sound_path, file_path, output_path, num_lsb): sound = wave.open(sound_path, "r") params = sound.getparams() num_channels = sound.getnchannels() sample_width = sound.getsampwidth() num_frames = sound.getnframes()...
import asyncio import aioxmpp import logging from aioxmpp.service import Service from . import xso logger = logging.getLogger(__name__) async def get_registration_fields(xmlstream, timeout=60): """ A query is sent to the server to obtain the fields that need to be filled to register with the server. ...
""" Tests for internal links and destinations """ __version__='''$Id: test_pdfgen_links.py 3959 2012-09-27 14:39:39Z robin $''' from reportlab.lib.testutils import setOutDir,makeSuiteForClasses, outputfile, printLocation setOutDir(__name__) # # Fit tests # # Modification History # ==================== # # 11-Mar-2003 ...
""" These are PreCanned Reports. PreCanned Reports are the PyFlag equivalent of the google 'Im Feeling Lucky' feature - we basically just dump out some simple queries which are used to get you started. """ import pyflag.Reports as Reports import pyflag.conf config=pyflag.conf.ConfObject() import pyflag.Registry as Re...
import boto3 from gzip import GzipFile from cStringIO import StringIO import sys import csv class S3CompressedWriter(object): def __init__(self, bucket, path, mimetype='text/plain'): self.bucket = bucket self.path = path self.mimetype = mimetype self._buffer = None def __enter_...
import sys import traceback import logging import base64 import threading import csv import tempfile import psycopg2 import openerp.pooler as pooler from openerp.osv import orm, fields from openerp.tools.translate import _ _logger = logging.getLogger(__name__) class move_line_importer(orm.Model): """Asynchron...
""" File : dispatch.py Author : ian Created : 04-21-2017 Last Modified By : ian Last Modified On : 04-21-2017 *********************************************************************** The MIT License (MIT) Copyright © 2017 Ian Cooper <<EMAIL>> Permission is hereby granted, free of charge,...
""" This script generates a pandadoc.hpp file representing the Python wrappers that can be parsed by doxygen to generate the Python documentation. You need to run this before invoking Doxyfile.python. It requires a valid makepanda installation with interrogatedb .in files in the lib/pandac/input directory. """ __all_...
import re from migrate.changeset import UniqueConstraint from oslo_db import exception as db_exception from sqlalchemy import and_, func, orm from sqlalchemy import MetaData, Table from sqlalchemy.exc import OperationalError, ProgrammingError NEW_KEYNAME = 'image_members_image_id_member_deleted_at_key' ORIGINAL_KEYN...
#!/usr/bin/env python """ Script which takes one or more file paths and reports on their detected encodings Example:: % chardetect somefile someotherfile somefile: windows-1252 with confidence 0.5 someotherfile: ascii with confidence 1.0 If no paths are provided, it takes its input from stdin. """ from...
import logging from ryu.ofproto import ofproto_v1_2 from ryu.ofproto import ether from ryu.ofproto import inet from ryu.tests.integrated import tester LOG = logging.getLogger(__name__) class RunTest(tester.TestFlowBase): """ Test case for add flows of Actions """ OFP_VERSIONS = [ofproto_v1_2.OFP_VERSION...
"""Support for Google travel time sensors.""" from datetime import datetime, timedelta import logging import googlemaps import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( ATTR_ATTRIBUTION, ATTR_LATITUDE, ATTR_LONGITUDE, CONF_API_KEY, ...
#!/usr/bin/env python '''Constants defined by SDL, and needed in pygame. Note that many of the flags for SDL are not needed in pygame, and are not included here. These constants are generally accessed from the `pygame.locals` module. This module is automatically placed in the pygame namespace, but you will usually ...
# -*- coding: utf-8 -*- from django.db import models import jsonschema from website.util import api_v2_url from osf.models.base import BaseModel, ObjectIDMixin from osf.utils.datetime_aware_jsonfield import DateTimeAwareJSONField from osf.exceptions import ValidationValueError from website.project.metadata.utils imp...
# -*- coding: utf-8 -*- # # Python Fedora Module documentation build configuration file, created by # sphinx-quickstart on Mon Jun 9 08:12:44 2008. # # This file is execfile()d with the current directory set to its containing # dir. # The contents of this file are pickled, so don't put values in the namespace # that ...
from ..excel_comparsion_test import ExcelComparisonTest from ...workbook import Workbook class TestCompareXLSXFiles(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.maxDiff = None filename = 'chart_font05.xlsx' ...
import argparse import contextlib from fnmatch import fnmatch import os from pathlib import Path import re import shutil import subprocess import sys import hashlib SHA256_SUMS = { "d40f18b4e43c6e6370ef7db9131f584fbb137276ec2e3dba67a4b267f81cb644": "bitcoin-0.15.2-aarch64-linux-gnu.tar.gz", "54fb877a148a6ad189a1e1ab1...
"""A dumb and slow but simple dbm clone. For database spam, spam.dir contains the index (a text file), spam.bak *may* contain a backup of the index (also a text file), while spam.dat contains the data (a binary file). XXX TO DO: - seems to contain a bug when updating... - reclaim free space (currently, space once o...
import logging from airflow.contrib.hooks.gcs_hook import GoogleCloudStorageHook from airflow.operators.sensors import BaseSensorOperator from airflow.utils.decorators import apply_defaults class GoogleCloudStorageObjectSensor(BaseSensorOperator): """ Checks for the existence of a file in Google Cloud Storag...
from sympy import S from sympy.physics.vector import Vector, ReferenceFrame, Dyadic from sympy.utilities.pytest import raises Vector.simp = True A = ReferenceFrame('A') def test_output_type(): A = ReferenceFrame('A') v = A.x + A.y d = v | v zerov = Vector(0) zerod = Dyadic(0) # dot products ...
from __future__ import unicode_literals import frappe, os import frappe.modules from frappe.utils import cstr from frappe.modules import export_doc, get_module_path, scrub def listfolders(path, only_name=0): """ Returns the list of folders (with paths) in the given path, If only_name is set, it returns only the...
from openerp.osv import fields, osv import openerp.addons.decimal_precision as dp class bid_line_qty(osv.osv_memory): _name = "bid.line.qty" _description = "Change Bid line quantity" _columns = { 'qty': fields.float('Quantity', digits_compute=dp.get_precision('Product Unit of Measure'), required=Tr...
# -*- coding: utf-8 -*- import json import warnings from django.core.serializers.json import DjangoJSONEncoder from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden def allow_remote_invocation(func, method='auto'): """ All methods which shall be callable through a given Ajax 'act...
"""Unit test utilities for Google C++ Mocking Framework.""" __author__ = '<EMAIL> (Zhanyong Wan)' import os import sys # Determines path to gtest_test_utils and imports it. SCRIPT_DIR = os.path.dirname(__file__) or '.' # isdir resolves symbolic links. gtest_tests_util_dir = os.path.join(SCRIPT_DIR, '../gtest/test'...
import wx class ModelInterface(object): """"Defines an interface for a simple value generator model""" def __init__(self): super(ModelInterface, self).__init__() self.value = 0 self.observers = list() def Generate(self): """Interface method to be implemented by subclasses...
""" Collection of Model instances for use with the odrpack fitting package. """ from __future__ import division, print_function, absolute_import import numpy as np from scipy.odr.odrpack import Model __all__ = ['Model', 'exponential', 'multilinear', 'unilinear', 'quadratic', 'polynomial'] def _lin_fcn(B,...
from collections import defaultdict from telemetry.value import failure from telemetry.value import merge_values from telemetry.value import skip class Summary(object): """Computes summary values from the per-page-run values produced by a test. Some telemetry benchmark repeat a number of times in order to get a...
# -*- coding: utf-8 -*- r""" werkzeug.contrib.iterio ~~~~~~~~~~~~~~~~~~~~~~~ This module implements a :class:`IterIO` that converts an iterator into a stream object and the other way round. Converting streams into iterators requires the `greenlet`_ module. To convert an iterator into a stream...
from twisted.internet import defer from deluge.ui.console.main import BaseCommand import deluge.ui.console.colors as colors import deluge.component as component class Command(BaseCommand): """displays help on other commands""" usage = "Usage: help [command]" def handle(self, *args, **options): ...
"""Wrapper for webbrowser library, to invoke the http handler on win32.""" __author__ = '<EMAIL> (Thomas Stromberg)' import os.path import subprocess import sys import traceback import webbrowser import util def output(string): print string def create_win32_http_cmd(url): """Create a comman...
import logging import logging.handlers as handlers __author__ = "Sylvain Hellegouarch" __version__ = "0.5.1" __all__ = ['WS_KEY', 'WS_VERSION', 'configure_logger', 'format_addresses'] WS_KEY = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11" WS_VERSION = (8, 13) def configure_logger(stdout=True, filepath=None, level=logging....
""" RESTx: Sane, simple and effective data publishing and integration. Copyright (C) 2010 MuleSoft Inc. http://www.mulesoft.com 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...
import header import company import report_helper import webkit_report import ir_report import wizard import convert import report # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
from vitrage.common.constants import VertexProperties as VProps from vitrage.entity_graph.mappings.datasource_info_mapper \ import DEFAULT_INFO_MAPPER from vitrage.evaluator.template_fields import TemplateFields class BaselineTools(object): @staticmethod def get_score(action_info): return 1 # no ...
from warnings import warn from numpy import asarray from scipy.sparse import isspmatrix_csc, isspmatrix_csr, isspmatrix, \ SparseEfficiencyWarning, csc_matrix import _superlu noScikit = False try: import scikits.umfpack as umfpack except ImportError: import umfpack noScikit = True isUmfpack = ha...
from __future__ import absolute_import import email.utils import mimetypes from .packages import six def guess_content_type(filename, default='application/octet-stream'): """ Guess the "Content-Type" of a file. :param filename: The filename to guess the "Content-Type" of using :mod:`mimetypes`. ...
from __future__ import absolute_import, division, print_function, \ with_statement import string import struct import hashlib __all__ = ['ciphers'] cached_tables = {} if hasattr(string, 'maketrans'): maketrans = string.maketrans translate = string.translate else: maketrans = bytes.maketrans tra...
from __future__ import division import numpy as np from .perspective import Base3DRotationCamera class TurntableCamera(Base3DRotationCamera): """ 3D camera class that orbits around a center point while maintaining a view on a center point. For this camera, the ``scale_factor`` indicates the zoom level,...
from __future__ import absolute_import import socket try: from select import poll, POLLIN except ImportError: # `poll` doesn't exist on OSX and other platforms poll = False try: from select import select except ImportError: # `select` doesn't exist on AppEngine. select = False def is...
from __future__ import absolute_import import re from xml.etree import ElementTree from httpie.plugins import FormatterPlugin DECLARATION_RE = re.compile('<\?xml[^\n]+?\?>', flags=re.I) DOCTYPE_RE = re.compile('<!DOCTYPE[^\n]+?>', flags=re.I) DEFAULT_INDENT = 4 def indent(elem, indent_text=' ' * DEFAULT_INDENT):...
import os from oslo_log import log as logging # For more information please visit: https://wiki.openstack.org/wiki/TaskFlow from taskflow.listeners import base from taskflow.listeners import logging as logging_listener from taskflow import task from cinder import exception LOG = logging.getLogger(__name__) def _ma...
"""WebSocket opening handshake processor. This class try to apply available opening handshake processors for each protocol version until a connection is successfully established. """ import logging from mod_pywebsocket import common from mod_pywebsocket.handshake import hybi00 from mod_pywebsocket.handshake import h...
import os from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives import serialization from cryptography import x509 from cryptography.x509.oid import NameOID from oslo_seria...
from oslo_serialization import jsonutils from nova import db from nova import exception from nova import objects from nova.objects import base from nova.objects import fields from nova.objects import pci_device_pool from nova import utils # TODO(berrange): Remove NovaObjectDictCompat class ComputeNode(base.NovaPersi...
from __future__ import unicode_literals from .common import InfoExtractor class HentaiStigmaIE(InfoExtractor): _VALID_URL = r'^https?://hentai\.animestigma\.com/(?P<id>[^/]+)' _TEST = { 'url': 'http://hentai.animestigma.com/inyouchuu-etsu-bonus/', 'md5': '4e3d07422a68a4cc363d8f57c8bf0d23', ...
import datetime import os import mock from oslo_config import cfg from oslo_utils import timeutils from ironic.common import driver_factory from ironic.common import exception from ironic.common import swift from ironic.conductor import task_manager from ironic.conductor import utils as manager_utils from ironic.driv...
import struct import dns.exception import dns.rdata import dns.rdatatype import dns.name from dns._compat import xrange class NSEC(dns.rdata.Rdata): """NSEC record @ivar next: the next name @type next: dns.name.Name object @ivar windows: the windowed bitmap list @type windows: list of (window n...
"""PyGotham user profiles.""" from flask import ( Blueprint, flash, g, redirect, render_template, request, url_for ) from flask_login import current_user from flask_security import login_required from pygotham.core import db from pygotham.frontend import route from pygotham.models import Talk, Volunteer __all__ ...
import math import numpy as np import matplotlib.pyplot as plt import Tkinter, tkFileDialog from collections import deque # This program will plot X/Y/Z data logged via drivers/storage/logger.c, and # assumes we are getting vector data in CSV format generated using the # 'sensorsLogSensorsEvent' helper function in dri...
from setuptools import setup, find_packages from pkg_resources import parse_requirements import os with open(os.path.join("oplus", "version.py")) as f: version = f.read().split("=")[1].strip().strip("'").strip('"') with open("requirements.txt", "r") as f: requirements = [str(r) for r in parse_requirements(f....
""" Python Interchangeable Virtual Instrument Library Copyright (c) 2012-2014 Alex Forencich 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...
""" Submit or Cancel spot instance requests. When submit, the process will block until the request is fulfilled or the process is killed by user(like CTRL + C), if the process is killed, the requests will be automatically canceled. """ import os import time import pickle import argparse import subprocess import yaml...
from __future__ import division, absolute_import, print_function import numpy.polynomial as poly from numpy.testing import TestCase, run_module_suite, assert_ class test_str(TestCase): def test_polynomial_str(self): res = str(poly.Polynomial([0, 1])) tgt = 'poly([0., 1.])' assert_(res, tg...
# -*- test-case-name: buildbot.test.test_svnpoller -*- import time from twisted.internet import defer from twisted.trial import unittest from buildbot.changes.svnpoller import SVNPoller # this is the output of "svn info --xml # svn+ssh://svn.twistedmatrix.com/svn/Twisted/trunk" prefix_output = """\ <?xml version="1.0...
def sensu_check(module, path, name, state='present', backup=False): changed = False reasons = [] try: import json except ImportError: import simplejson as json try: try: stream = open(path, 'r') config = json.load(stream.read()) except IOErro...
""" Automated tests for checking various utils functions. """ import logging import unittest from gensim import utils class TestIsCorpus(unittest.TestCase): def test_None(self): # test None result = utils.is_corpus(None) expected = (False, None) self.assertEqual(expected, result...
"""Detect changes in Ansible code.""" from __future__ import absolute_import, print_function import re import os from lib.util import ( ApplicationError, SubprocessError, MissingEnvironmentVariable, CommonConfig, display, ) from lib.http import ( HttpClient, urlencode, ) from lib.git im...
""" This file defines the text for various default files. Values are used in pychron.paths when building directory structure """ from __future__ import absolute_import import yaml from pychron.core.helpers.strtools import to_bool # PIPELINE_TEMPLATES = '''- Isotope Evolutions # - Blanks # - IC Factor # - Flux # - I...
"""Incremental Principal Components Analysis.""" # License: BSD 3 clause import numpy as np from scipy import linalg from .base import _BasePCA from ..utils import check_array, gen_batches from ..utils.extmath import svd_flip, _batch_mean_variance_update class IncrementalPCA(_BasePCA): """Incremental principal...
from __future__ import unicode_literals import os import sys import unittest from django.conf import settings from django.contrib.staticfiles import finders, storage from django.contrib.staticfiles.management.commands import collectstatic from django.contrib.staticfiles.management.commands.collectstatic import \ ...
import re # Valid query types (a dictionary is used for speedy lookups). QUERY_TERMS = dict([(x, None) for x in ( 'exact', 'iexact', 'contains', 'icontains', 'gt', 'gte', 'lt', 'lte', 'in', 'startswith', 'istartswith', 'endswith', 'iendswith', 'range', 'year', 'month', 'day', 'week_day', 'isnull', 'search'...
#!/usr/local/bin/python import sys import getopt from ..genxmlif import GenXmlIfError from xsvalErrorHandler import ErrorHandler, XsvalError from ..minixsv import * from pyxsval import parseAndValidate ########################################## # minixsv Wrapper for calling mi...
''' Created on 2013-08-24 Unittest for the GeoPy main package geodata. @author: Andre R. Erler, GPL v3 ''' import unittest import netCDF4 as nc import numpy as np import numpy.ma as ma import scipy.stats as ss import os import gc from copy import deepcopy import shutil # internal imports # from ensemble.base impor...
import numpy as np from numpy.testing import assert_allclose import pytest from astropy.utils import NumpyRNGContext from astropy.nddata import StdDevUncertainty from astropy import units as u from ccdproc.core import (cosmicray_lacosmic, cosmicray_median, background_deviation_box, background_devi...
#!/usr/bin/env python3 import sys import numpy as np from arthur.imaging import full_calculation, calculate_lag from arthur.io import read_full from arthur.plot import plot_image, plot_lag, plot_chan_power, plot_corr_mat, plot_diff from arthur.constants import NUM_CHAN from matplotlib import pyplot FRQ = 58398437.5 ...
import time import Adafruit_ADS1x15 import sys addr = 0 def convert( aString ): if aString.startswith("0x") or aString.startswith("0X"): return int(aString,16) elif aString.startswith("0"): return int(aString,8) else: return int(aString) milli_time = lambda: int(round(time.time() ...
import pytest from unleash.depgraph import DependencyGraph @pytest.fixture def dg(): # our example dependency graph. it looks like this # # D -> B # \ # A E -> F # / # C g = DependencyGraph() g.add_obj('D', ['B']) g.add_obj('B', ['A']) g.add_obj...