content
string
import sys import string from ldif import LDIFParser, LDIFWriter class SchemaParser(LDIFParser): def __init__(self, input): LDIFParser.__init__(self, input) self.objectclasses = {} self.attributes = {} def __repr__(self): s = '' oc_list = self.objectclasses.keys() ...
import os import time from datetime import date import osgtest.library.core as core import osgtest.library.files as files import osgtest.library.osgunittest as osgunittest import osgtest.library.service as service class TestStartPBS(osgunittest.OSGTestCase): pbs_config = """ create queue batch queue_type=executi...
import logging import inspect from json import loads, dumps from datetime import datetime, timedelta from redis import Redis, RedisError from thumbor.storages import BaseStorage from thumbor.utils import on_exception from tornado.concurrent import return_future logger = logging.getLogger('thumbor') class Storage(...
#!/usr/bin/env python import sys import types from traceback import format_exc def rec_gen(func, callback=None, err_callback=None): ''' callback accept arguments with output of func err_callback is called after Exception occured, accept Exception instance as it's arguments ''' def trans_func(*args...
from contextlib import contextmanager import os from os.path import dirname, abspath, join as pjoin import shutil from subprocess import check_call import sys from tempfile import mkdtemp from . import compat _in_proc_script = pjoin(dirname(abspath(__file__)), '_in_process.py') @contextmanager def tempdir(): td...
from __future__ import unicode_literals import re # A list of regular expressions for headers in the source code that we can # display in collapsed regions of diffs and diff fragments in reviews. HEADER_REGEXES = { '.cs': [ re.compile( r'^\s*((public|private|protected|static)\s+)+' ...
#!/usr/bin/python import sys import time import os import string sys.path.insert(0, "python") import libxml2 # # the testsuite description # DIR="xinclude-test-suite" CONF="testdescr.xml" LOG="check-xinclude-test-suite.log" log = open(LOG, "w") os.chdir(DIR) test_nr = 0 test_succeed = 0 test_failed = 0 test_error =...
#!/usr/bin/python import os import sys import re from subprocess import * import time def run(cmd): print "run:", cmd os.system(cmd) def get_image_dim(fn): output = Popen(["file", fn], stdout=PIPE).communicate()[0] r = re.compile("(\d+)\s*x+\s*(\d+)") m = r.search(output) if m: return...
from openerp import _, api, fields, models class Job(models.Model): _inherit = "hr.job" _name = "hr.job" _inherits = {'mail.alias': 'alias_id'} @api.model def _default_address_id(self): return self.env.user.company_id.partner_id address_id = fields.Many2one( 'res.partner', "J...
# ACTION_CHECKBOX_NAME is unused, but should stay since its import from here # has been referenced in documentation. from django.contrib.admin.decorators import register from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME from django.contrib.admin.options import (HORIZONTAL, VERTICAL, ModelAdmin, StackedI...
import unittest from mantid.kernel import V3D from mantid.simpleapi import CreateSimulationWorkspace, CreatePeaksWorkspace import numpy as np import numpy.testing as npt class IPeakTest(unittest.TestCase): def setUp(self): # IPeak cannot currently be instatiated so this is a quick way # getting a...
""" ========================================================= Multidimensional image processing (:mod:`scipy.ndimage`) ========================================================= .. currentmodule:: scipy.ndimage This package contains various functions for multidimensional image processing. Filters ======= .. autosum...
# -*- coding: utf-8 -*- """ samsara_sdk.constants ~~~~~~~~~~~~~~~~~~~~~ Samsara SDK client constants """ # Samara specific HTTP Header PUBLISHED_TIMESTAMP_HEADER = "X-Samsara-publishedTimestamp" API_PATH = '/v1/events' DEFAULT_CONFIG = { # a samsara ingestion api endpoint "http://samsara-ingestion.lo...
""" Tool to update all branches to have the latest changes from their upstreams. """ import argparse import collections import logging import sys import textwrap import os from fnmatch import fnmatch from pprint import pformat import git_common as git STARTING_BRANCH_KEY = 'depot-tools.rebase-update.starting-branc...
#/usr/bin/python2.7 #*-coding:utf-8-*- from structure import DependencyTree from DepNN import DepNN #Main class to execute the task. class Execute(object): def __init__(self): self.depnn = DepNN() self.depnn.extendLookUp('../data/depcheck2') self.depnn.load_wordvector('../data/word-vec.bin'...
from django.conf import settings from django.http import HttpResponseRedirect from django.utils.cache import patch_cache_control LOGIN_REQUIRED_PREFIXES = getattr(settings, 'LOGIN_REQUIRED_PREFIXES', ()) NO_LOGIN_REQUIRED_PREFIXES = getattr(settings, 'NO_LOGIN_REQUIRED_PREFIXES', ()) ALLOWED_DOMAINS = getattr(setting...
# -*- coding: utf-8 -*- from flask import url_for from flask_login import login_user def test_new_project_require_name(client, login): resp = client.post(url_for('dashboard.new_project'), data={'name': ''}) assert resp.status_code == 400 assert resp.json['errors']['name'] def test_new_project_success(cli...
import pickle import time import os from indra.sources.isi.api import process_preprocessed from indra.sources.isi.preprocessor import IsiPreprocessor def abstracts_runtime(): pfile = '/Users/daniel/Downloads/text_content_sample.pkl' dump = pickle.load(open(pfile, 'rb')) all_abstracts = dump['pubmed'] ...
import os import shutil import inspect from random import randint from copy import copy import myhdl from myhdl._block import _Block as Block from .extintf import Port from .extintf import Clock from .extintf import Reset class FPGA(object): """ """ vendor = "" # FPGA vendor, Altera, Xilinx, Lattice dev...
"""Essential attributes of photos in Google Photos/Picasa Web Albums are expressed using elements from the `media' namespace, defined in the MediaRSS specification[1]. Due to copyright issues, the elements herein are documented sparingly, please consult with the Google Photos API Reference Guide[2], alternatively t...
# -*- coding: utf-8 -*- # # Mock documentation build configuration file, created by # sphinx-quickstart on Mon Nov 17 18:12:00 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 aren't pickleable...
''' This file generates Ixia Library wrapper in Python, using TCL functions from IxTclHal. Params: - IxOS TCL lib path - IP address of Ixia chassis ''' from Tkinter import Tcl from collections import OrderedDict import re import socket import sys import os chassis_ip = '10.100.100.45' tcl_lib_path = '/home/tw...
import os import tarfile class package: def short_name(self): return "fhs-manpages" def long_name(self): return "Verifies correct installation of man pages" def prereq(self): return "tar" def analyze(self, pkginfo, tar): gooddir = 'usr/share/man' bad_dir = 'usr/man' ret = [[],[],[]] for i in tar.getm...
""" Test for distributed trial worker side. """ import os from cStringIO import StringIO from zope.interface.verify import verifyObject from twisted.trial.reporter import TestResult from twisted.trial.unittest import TestCase from twisted.trial._dist.worker import ( LocalWorker, LocalWorkerAMP, LocalWorkerTransp...
"""SocksiPy - Python SOCKS module. Version 1.00 Copyright 2006 Dan-Haim. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this ...
from boto.exception import BotoServerError class InvalidLimitException(BotoServerError): pass class NoSuchBucketException(BotoServerError): pass class InvalidSNSTopicARNException(BotoServerError): pass class ResourceNotDiscoveredException(BotoServerError): pass class MaxNumberOfDeliveryChannel...
#!/usr/bin/env python """ Copyright (c) 2006-2013 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ import ntpath import os from lib.core.common import getLimitRange from lib.core.common import isNumPosStrValue from lib.core.common import isTechniqueAvailable from lib.core....
from bambou import NURESTFetcher class NUIPFilterProfilesFetcher(NURESTFetcher): """ Represents a NUIPFilterProfiles fetcher Notes: This fetcher enables to fetch NUIPFilterProfile objects. See: bambou.NURESTFetcher """ @classmethod def managed_class(cls): ...
from subprocess import Popen,PIPE import sys import json result = {} result['all'] = {} pipe = Popen(['jls', '-q', 'name'], stdout=PIPE, universal_newlines=True) result['all']['hosts'] = [x[:-1] for x in pipe.stdout.readlines()] result['all']['vars'] = {} result['all']['vars']['ansible_connection'] = 'jail' if len(s...
#!/usr/bin/env python # encoding: utf-8 import os from efl.evas import EVAS_HINT_EXPAND, EVAS_HINT_FILL from efl import elementary from efl.elementary.window import StandardWindow from efl.elementary.box import Box from efl.elementary.icon import Icon from efl.elementary.segment_control import SegmentControl EXPAND_...
from copy import deepcopy import hashlib from bs4 import BeautifulSoup from rest_framework import serializers from instanotifier.notification.models import RssNotification from instanotifier.notification.utils import html def _parse_country(summary): soup = BeautifulSoup(summary, features="html5lib") countr...
import os from testtools.matchers import ( DirExists, Not ) import integration_tests class MakePluginTestCase(integration_tests.TestCase): def test_stage_make_plugin(self): project_dir = 'simple-make' self.run_snapcraft('stage', project_dir) binary_output = self.get_output_igno...
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Backup.origin' db.add_column(u'client_backup', 'origin', ...
# Python's datetime strftime doesn't handle dates before 1900. # These classes override date and datetime to support the formatting of a date # through its full "proleptic Gregorian" date range. # # Based on code submitted to comp.lang.python by Andrew Dalke # # >>> datetime_safe.date(1850, 8, 2).strftime("%Y/%m/%d was...
from django.views.generic.edit import FormMixin from django.shortcuts import get_object_or_404 from widgy.models import Node class HandleFormMixin(FormMixin): """ An abstract view mixin for handling form_builder.Form submissions. """ def post(self, *args, **kwargs): """ copied from dja...
"""Tokenization help for Python programs. generate_tokens(readline) is a generator that breaks a stream of text into Python tokens. It accepts a readline-like method which is called repeatedly to get the next line of input (or "" for EOF). It generates 5-tuples with these members: the token type (see token.py) ...
# -*- coding: utf-8 -*- """The compressed stream file-like object implementation.""" import os from dfvfs.compression import manager as compression_manager from dfvfs.file_io import file_io from dfvfs.lib import errors from dfvfs.resolver import resolver class CompressedStream(file_io.FileIO): """File input/outpu...
"""Tests for SoftmaxOp and LogSoftmaxOp.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys import numpy as np import tensorflow as tf class SoftmaxTest(tf.test.TestCase): def _npSoftmax(self, features, dim=-1, log=False): if dim is -1: ...
# -*- coding: utf-8 -*- from __future__ import print_function, division from sympy.core.compatibility import range from sympy.core import cacheit, Dummy, Eq, Integer, Rational, S, Wild from sympy.functions import binomial, sin, cos, Piecewise # TODO sin(a*x)*cos(b*x) -> sin((a+b)x) + sin((a-b)x) ? # creating, each ...
"""Various types of useful iterators and generators.""" __all__ = [ 'body_line_iterator', 'typed_subpart_iterator', 'walk', # Do not include _structure() since it's part of the debugging API. ] import sys from cStringIO import StringIO # This function will become a method of the ...
__title__ = "Fem Commands" __author__ = "Przemo Firszt" __url__ = "http://www.freecadweb.org" import FreeCAD if FreeCAD.GuiUp: import FreeCADGui import FemGui from PySide import QtCore class FemCommands(object): def __init__(self): self.resources = {'Pixmap': 'fem-frequency-analysis'...
import pecan import pecan.decorators from sentinel.api.controllers.base import BaseController from sentinel.scope import Scope class NetworkV2FloatingipsController(BaseController): service = u'network' resource = u'floatingip' collection = u'floatingips' @pecan.expose('json') @pecan.decorators....
from django.db import IntegrityError from django.test import TestCase from student.tests.factories import UserFactory from user_api.tests.factories import UserPreferenceFactory from user_api.models import UserPreference class UserPreferenceModelTest(TestCase): def test_duplicate_user_key(self): user = Use...
import logging import os import shutil import time import teuthology from teuthology.contextutil import safe_while log = logging.getLogger(__name__) # If we see this in any directory, we do not prune it PRESERVE_FILE = '.preserve' def main(args): """ Main function; parses args and calls prune_archive() ...
# -*- coding: utf-8 -*- """ pygments.lexers.factor ~~~~~~~~~~~~~~~~~~~~~~ Lexers for the Factor language. :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re from pygments.lexer import RegexLexer, bygroups, default, words from ...
__all__ = ( "build_info", "SOURCE_DIR", ) import sys if not sys.version.startswith("3"): print("\nPython3.x needed, found %s.\nAborting!\n" % sys.version.partition(" ")[0]) sys.exit(1) import os from os.path import join, dirname, normpath, abspath SOURCE_DIR = join(dirname(__file__), ...
# coding: utf-8 from __future__ import unicode_literals import re import json import itertools from .common import InfoExtractor from ..utils import ( determine_ext, error_to_compat_str, ExtractorError, int_or_none, parse_iso8601, sanitized_Request, str_to_int, unescapeHTML, mimet...
# This is a helper for the win32trace module # If imported from a normal Python program, it sets up sys.stdout and sys.stderr # so output goes to the collector. # If run from the command line, it creates a collector loop. # Eg: # C:>start win32traceutil.py (or python.exe win32traceutil.py) # will start a pr...
import datetime import sys def tripletize(line): begin = line[:11] middle = line[11:23] end = line[23:] return (begin,middle,end) def text2delta(t): h = int( t[0:2] ) m = int( t[3:5] ) s = int( t[6:8] ) milli = int( t[9:12] ) return datetime.timedelta(hours=h,minutes=m,seconds=s,milliseconds=milli) def delt...
# -*- coding: utf-8 -*- # Tests for the contrib/localflavor/ UY form fields. tests = r""" # UYDepartamentSelect ######################################################### >>> from django.contrib.localflavor.uy.forms import UYDepartamentSelect >>> f = UYDepartamentSelect() >>> f.render('departamentos', 'S') u'<select n...
"""Database migration from Cuckoo 0.6 to Cuckoo 1.1. Revision ID: 263a45963c72 Revises: None Create Date: 2014-03-23 23:30:36.756792 """ # Revision identifiers, used by Alembic. revision = "263a45963c72" mongo_revision = "1" down_revision = None import os import sys import sqlalchemy as sa from datetime import dat...
ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'core'}
from __future__ import unicode_literals from __future__ import print_function from prompt_toolkit.key_binding.manager import KeyBindingManager from prompt_toolkit.keys import Keys def get_key_manager(set_long_options, get_long_options): #pragma: no cover assert callable(set_long_options) assert callable(get_long...
import numpy import six from chainer import cuda from chainer import function from chainer.utils import type_check from chainer.utils import walker_alias class NegativeSampling(function.Function): """Implementation of negative sampling. In natural language processing, especially language modeling, the numbe...
import datetime import posixpath from django import forms from django.core import checks from django.core.files.base import File from django.core.files.images import ImageFile from django.core.files.storage import default_storage from django.core.validators import validate_image_file_extension from django.db.models im...
""" 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...
# flasky extensions. flasky pygments style based on tango style from pygments.style import Style from pygments.token import Keyword, Name, Comment, String, Error, \ Number, Operator, Generic, Whitespace, Punctuation, Other, Literal class FlaskyStyle(Style): background_color = "#f8f8f8" default_style = "...
import os import tempfile from django import forms from django.core.files.storage import FileSystemStorage from django.forms.formsets import formset_factory from django.http import HttpResponse from django.template import Template, Context from django.contrib.auth.models import User from django.contrib.formtools.wiz...
from openerp.osv import orm, fields from openerp import SUPERUSER_ID from openerp.tools.translate import _ class ir_model(orm.Model): _inherit = 'ir.model' _columns = { 'avoid_quick_create': fields.boolean('Avoid quick create'), } def _wrap_name_create(self, old_create, model): d...
from oslo_config import cfg from oslo_log import log as logging from neutron_lib import constants from neutron.extensions import portbindings from neutron.services.trunk import constants as trunk_consts from neutron.services.trunk.drivers import base LOG = logging.getLogger(__name__) NAME = 'linuxbridge' SUPPORTED_...
""" Base classes for writing management commands (named commands which can be executed through ``django-admin.py`` or ``manage.py``). """ import os import sys from optparse import make_option, OptionParser import django from django.core.exceptions import ImproperlyConfigured from django.core.management.color import ...
# -*- coding: utf-8 -*- """ *************************************************************************** PointsInPolygon.py --------------------- Date : August 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com ***********************...
from optparse import make_option import os import re import sys import socket from django.core.management.base import BaseCommand, CommandError from django.core.servers.basehttp import AdminMediaHandler, run, WSGIServerException, get_internal_wsgi_application from django.utils import autoreload naiveip_re = re.compil...
import sys sampleText = "Hello World!" if __name__=="__main__": args = sys.argv[1:] if args[0] == "1": # print sample text to stderr sys.stdout.write(sampleText) elif args[0] == "2": # print sample text to stderr sys.stderr.write(sampleText) # Add any other helper programs here, with differ...
from azure.common import ( AzureException, ) from .._constants import ( _ENCRYPTION_PROTOCOL_V1, ) from .._encryption import ( _generate_encryption_data_dict, _dict_to_encryption_data, _generate_AES_CBC_cipher, _validate_and_unwrap_cek, _EncryptionAlgorithm, ) from json import (...
""" Test for LMS instructor background task views. """ import json from celery.states import SUCCESS, FAILURE, REVOKED, PENDING from mock import Mock, patch from django.utils.datastructures import MultiValueDict from instructor_task.models import PROGRESS from instructor_task.tests.test_base import (InstructorTaskTe...
import BoostBuild import os import string t = BoostBuild.Tester(use_test_config=False) # Stage the binary, so that it will be relinked without hardcode-dll-paths. # That will check that we pass correct -rpath-link, even if not passing -rpath. t.write("jamfile.jam", """\ stage dist : main ; exe main : main.cpp b ; """...
from __future__ import unicode_literals import datetime import logging import re import time from django.core.cache import cache from django.contrib.auth.models import User from django.db.models.aggregates import Count from django.db.models.signals import post_save, post_delete from django.template.context import Req...
from __future__ import unicode_literals, division, absolute_import, print_function import sys PY3 = sys.version_info[0] == 3 if PY3: text_type = str binary_type = bytes unicode = str basestring = str else: range = xrange text_type = unicode binary_type = str chr = unichr """Use the HTM...
""" Module of helper functions for distributed ccresponse computations. Defines functions for retrieving data computed at displaced geometries. """ from psi4.driver import p4util def collect_displaced_matrix_data(db, signature, row_dim): """ Gathers a list of tensors, one at each displaced geometry. ...
import openerp.tests.common as common class test_menu(common.TransactionCase): def setUp(self): super(test_menu,self).setUp() self.Menus = self.registry('ir.ui.menu') def test_00_menu_deletion(self): """Verify that menu deletion works properly when there are child menus, and those ...
"""SCons.exitfuncs Register functions which are executed when SCons exits for any reason. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associate...
import os import urlparse from collections import namedtuple, defaultdict from wptmanifest.node import (DataNode, ConditionalNode, BinaryExpressionNode, BinaryOperatorNode, VariableNode, StringNode, NumberNode, UnaryExpressionNode, UnaryOperatorNode, KeyValue...
import socks import socket from urllib.request import urlopen import requests import header_s import time from bs4 import BeautifulSoup socks.set_default_proxy(socks.SOCKS5, "localhost", 9050) socket.socket = socks.socksocket print(requests.get('http://icanhazip.com').text) print(urlopen('http://icanhazip.com').r...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['stableinterface'], 'supported_by': 'community'} try: import boto.ec2.cloudwatch from boto.ec2.cloudwatch import MetricAlarm...
#!/usr/bin/python """ Configuration Handler """ import logging # noinspection PyCompatibility import ConfigParser import data.Constants logger = logging.getLogger(data.Constants.Constant.LOGGER_NAME) class ConfigurationReader(object): """ Class handling the configuration parser from the configuration.ini fil...
from twisted.protocols import basic from twisted.trial import unittest from buildbot.util import netstrings class NetstringParser(unittest.TestCase): def test_valid_netstrings(self): p = netstrings.NetstringParser() p.feed("5:hello,5:world,") self.assertEqual(p.strings, [b'hello', b'worl...
from __future__ import absolute_import, division, print_function, \ with_statement import os import sys import logging import signal import time from shadowsocks import common, shell # this module is ported from ShadowVPN daemon.c def daemon_exec(config): if 'daemon' in config: if os.name != 'posix'...
from __future__ import print_function, unicode_literals import json import os import sys from six import iteritems, itervalues import wptserve from wptserve import sslutils from . import environment as env from . import instruments from . import mpcontext from . import products from . import testloader from . impor...
from matplotlib import pyplot as plt import numpy as np import math import pickle from scipy import signal from numpy.fft import rfft, irfft from numpy import argmax, sqrt, mean, absolute, arange, log10 from scipy.signal import blackmanharris import thdn def single_frequency_filter(input_signal): y_f_all = np.fft....
from netforce import set_module_version set_module_version("3.1.0",115)
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2007 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") h...
#Created by Dmytro Konobrytskyi, 2013 (github.com/Akson) import wx from RCP3.Backends.Sources.ZMQ.Tools.RoutersListProvider import GetAvailableRoutersList class ServerSelectionDialog(wx.Dialog): def __init__(self, currentServerAddress = None): super(ServerSelectionDialog, self).__init__(parent=None, size=(...
""" AUTHOR : Alex Mathew EMAIL : <EMAIL> There is a lot I can do to improve this implementation. """ """For a given binary word, print out its corresponding Hamming Coded word""" import math def FindKeyBits(n): keyBits=[] pad = int(math.ceil(math.log(n)/math.log(2))) for i in xrange(1, n+1): b = "{0:b}"...
"""Runs Idle Workload by resetting appliance and enabling specific roles with no providers.""" import time import pytest from cfme.utils.conf import cfme_performance from cfme.utils.grafana import get_scenario_dashboard_urls from cfme.utils.log import logger from cfme.utils.smem_memory_monitor import add_workload_qua...
#!/usr/bin/env python from nlpy import __version__ from nlpy.model import AmplModel from nlpy.optimize.solvers.funnel import Funnel, LSTRFunnel, LDFPFunnel, \ StructuredLDFPFunnel from nlpy.tools.timing import cputime from optparse import OptionParser import numpy import nlpy.t...
from openerp import api, fields, models from datetime import * def format_code(code_seq): code = map(int, str(code_seq)) code_len = len(code) while len(code) < 14: code.insert(0, 0) while len(code) < 16: n = sum([(len(code) + 1 - i) * v for i, v in enumerate(code)]) % 11 if n ...
""" $Id: Base.py,v 1.12.2.4 2007/05/22 20:28:31 customdesigned Exp $ This file is part of the pydns project. Homepage: http://pydns.sourceforge.net This code is covered by the standard Python License. Base functionality. Request and Response classes, that sort of thing. """ import socket, string, types, time im...
import os import xbmc import xbmcaddon import xbmcgui import xbmcvfs ADDON = xbmcaddon.Addon() ADDONVERSION = ADDON.getAddonInfo('version') ADDONNAME = ADDON.getAddonInfo('name') ADDONPATH = ADDON.getAddonInfo('path').decode('utf-8') ADDONPROFILE = xbmc.translatePath( ADDON.getAddonInfo('profile') ).decod...
def patch_nustar_caldb(version, nupatchserver = "hassif.caltech.edu", nupatchworkdir = "/pub/nustar/pipeline", caldb = "/FTP/caldb", caldbstage = "/FTP/caldb/staging", ck_file_exists='True'): """ C...
#!/usr/bin/env python3 from argparse import ArgumentParser import sys import os import subprocess import re import glob import threading import time DESCRIPTION = """Regressor is a tool to run regression tests in a CI env.""" class PrintDotsThread(object): """Prints a dot every "interval" (default is 300) second...
__all__ = [ 'Process', 'current_process', 'active_children', 'freeze_support', 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Condition', 'Event', 'Barrier', 'Queue', 'Manager', 'Pipe', 'Pool', 'JoinableQueue' ] # # Imports # import threading import sys import weakref import array from .connectio...
import sys import os import traceback try: import sqlite3 except ImportError: import pysqlite2.dbapi2 as sqlite3 import re import glob def parse_stdout(s): argv = re.search('^===ARGV=(.*?)$', s, re.M).group(1) argv = argv.split() testname = argv[-1] del argv[-1] hub = None reactor = Non...
REPO_OPTS = ['alias', 'name', 'priority', 'enabled', 'autorefresh', 'gpgcheck'] def zypper_version(module): """Return (rc, message) tuple""" cmd = ['/usr/bin/zypper', '-V'] rc, stdout, stderr = module.run_command(cmd, check_rc=False) if rc == 0: return rc, stdout else: return rc, st...
#!/usr/bin/env python """ """ from mininet.topo import Topo from mininet.net import Mininet from mininet.node import RemoteController from mininet.node import Node from mininet.node import CPULimitedHost from mininet.link import TCLink from mininet.cli import CLI from mininet.log import setLogLevel from mininet.util i...
from math import radians, cos, sin, sqrt, atan2 import random import operator def aco(petrol_stations, gas_type, capacity, initial_petrol, overall_dist, consumption, source, target, ants=2, a=1, b=1, iterations=10): pheromone = {station['id']: 4 for station in petrol_stations} probability = lambda sour...
"""Basic http server for tests to simulate PyPI or custom indexes """ import sys import time import threading from setuptools.compat import BaseHTTPRequestHandler from setuptools.compat import (urllib2, URLError, HTTPServer, SimpleHTTPRequestHandler) class IndexServer(HTTPServer): ""...
"""distutils.command.upload Implements the Distutils 'upload' subcommand (upload package to PyPI).""" import os import socket import platform from urllib2 import urlopen, Request, HTTPError from base64 import standard_b64encode import urlparse import cStringIO as StringIO from hashlib import md5 from distutils.errors...
from django.template.defaultfilters import dictsortreversed from django.test import SimpleTestCase class FunctionTests(SimpleTestCase): def test_sort(self): sorted_dicts = dictsortreversed( [{'age': 23, 'name': 'Barbara-Ann'}, {'age': 63, 'name': 'Ra Ra Rasputin'}, {...
import cStringIO import logging import os import sys import unittest ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, ROOT_DIR) from proc_maps import ProcMaps class ProcMapsTest(unittest.TestCase): _TEST_PROCMAPS = '\n'.join([ '00000000-00001000 r--p 00000000 fc:00 0...