content
stringlengths
4
20k
#!/usr/bin/python3 ''' Firmware Analysis and Comparison Tool (FACT) Copyright (C) 2015-2018 Fraunhofer FKIE 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 th...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import os.path import unittest import datetime from simiki.config import parse_config, get_default_config test_path = os.path.dirname(os.path.abspath(__file__)) class TestParseConfig(unittest.TestCase): def setUp(self): ...
# Tkinter font wrapper # # written by Fredrik Lundh, February 1998 # # FIXME: should add 'displayof' option where relevant (actual, families, # measure, and metrics) # __version__ = "0.9" import Tkinter # weight/slant NORMAL = "normal" ROMAN = "roman" BOLD = "bold" ITALIC = "italic" def nametofont(name): ...
""" Events module forms """ from django import forms from django.utils.translation import ugettext as _ from django.core.urlresolvers import reverse from treeio.events.models import Event from treeio.core.models import Object, Location from treeio.core.decorators import preprocess_form import datetime preprocess_form()...
# coding: utf-8 from __future__ import absolute_import import functools import re from flask.ext import login from flask.ext import wtf from flask.ext.oauthlib import client as oauth from google.appengine.ext import ndb import flask import unidecode import wtforms import cache import config import model import task...
from logging import config as log_config from alembic import context from magnum.db.sqlalchemy import api as sqla_api from magnum.db.sqlalchemy import models # this is the Alembic Config object, which provides # access to the values within the .ini file in use. config = context.config # Interpret the config file fo...
from tornado.testing import AsyncTestCase, gen_test from tornado.util import ArgReplacer import unittest import cythonapp class CythonCoroutineTest(AsyncTestCase): @gen_test def test_native_coroutine(self): x = yield cythonapp.native_coroutine() self.assertEqual(x, "goodbye") @gen_test ...
""" The I{xdate} module provides classes for converstion between XML dates and python objects. """ from logging import getLogger from suds import * from suds.xsd import * import time import datetime as dt import re log = getLogger(__name__) class Date: """ An XML date object. Supported formats: ...
import time from openerp.osv import osv from openerp.report import report_sxw class product_pricelist(report_sxw.rml_parse): def __init__(self, cr, uid, name, context): super(product_pricelist, self).__init__(cr, uid, name, context=context) self.pricelist=False self.quantity=[] sel...
#!/usr/bin/python3 # coding=utf-8 """reads barometric pressure sensor and writes it to UDP socket with timestamp available """ import socket from datetime import datetime from struct import pack from time import sleep from time import time from os import _exit as dumbnrun import ms5637 __author__ = 'Moe' __copyright_...
from __future__ import unicode_literals import xml.etree.ElementTree from .subtitles import SubtitlesInfoExtractor from ..utils import ExtractorError from ..compat import compat_HTTPError class BBCCoUkIE(SubtitlesInfoExtractor): IE_NAME = 'bbc.co.uk' IE_DESC = 'BBC iPlayer' _VALID_URL = r'https?://(?:ww...
"""Provides some utilities widely used by other modules""" import bisect import collections import collections.abc import functools import operator import os.path import random import math # ______________________________________________________________________________ # Functions on Sequences and Iterables def seq...
'''integration test topology builder''' import copy import heronpy.api.api_constants as api_constants from heronpy.api.stream import Stream, Grouping from heronpy.api.topology import TopologyBuilder, Topology, TopologyType from ..core import constants as integ_const from .aggregator_bolt import AggregatorBolt from .int...
from oslo_serialization import jsonutils from oslo_utils import versionutils from nova.objects import base from nova.objects import fields from nova import utils # NOTE(jwcroppe): Used to determine which fields whose value we need to adjust # (read: divide by 100.0) before sending information to the RPC notifier sin...
import numpy as np from ..core import indexing from ..core.utils import Frozen, FrozenDict from ..core.variable import Variable from .common import AbstractDataStore, BackendArray from .locks import SerializableLock, ensure_lock # FIXME: Add a dedicated lock, even if ecCodes is supposed to be thread-safe # in most ...
import unittest import hashlib import os class ExternalDataCoreTest(unittest.TestCase): def testExternalDataFile(self): """Asserts that the external data file was correctly downloaded.""" filepath = os.path.join( os.environ['GIRDER_TEST_DATA_PREFIX'], 'test_file.txt' ...
from django.db import models class Dac(models.Model): country = models.CharField(max_length=60) code = models.PositiveIntegerField() def __str__(self): return str(self.code) + ' - ' + self.country class Admin: list_display = ('country','code') ordering = ( 'code', ) # ...
from __main__ import * def unpack(sJavascript,iteration=1, totaliterations=1 ): aSplit = sJavascript.split("rn p}('") p1,a1,c1,k1=('','0','0','') ss="p1,a1,c1,k1=(\'"+aSplit[1].split(".spli")[0]+')';exec(ss) k1=k1.split('|') aSplit = aSplit[1].split("))'") e = '';d = '' sUnpacked1 = str(__unpack(p1, a1, c1, k1...
""" Test instructor.access """ from nose.tools import raises from nose.plugins.attrib import attr from student.tests.factories import UserFactory from xmodule.modulestore.tests.factories import CourseFactory from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase from student.roles import CourseBetaTes...
# -*- coding: utf-8 -*- import django.contrib.messages as django_messages from django.contrib.messages.storage import default_storage from django.http import HttpRequest from django.template import loader from django.utils.translation import ugettext import pytest from olympia.amo.messages import _make_message, info...
import json from lints.rst import RST2PseudoXMLLint def test_rst2pseudoxml_severe_dot_regex(): msg = [ 'Some Document.rst:355: (SEVERE/4) Unexpected section title or transition.', # noqa ] res = RST2PseudoXMLLint().parse_loclist(msg, 1) assert json.loads(res)[0] == { "lnum": "355", ...
import unittest import sys import os path = os.path.abspath("../pygorithms") sys.path.append(path) import knapsack_problem_DP as KPDP class TestKnapsackDPoptimality(unittest.TestCase): def test_knapsack_optimal_solution_exmp1(self): items = [(3, 4), (2, 3), (4, 2), (4, 3)] capacity = 6 an...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from contextlib import contextmanager from datetime import datetime, timedelta from itertools import accumulate from math import nan from struct import unpack, calcsize from activityio._types import ActivityData, special_columns from activityio._util import drydoc, except...
"""Android-specific implementation of the core backend interfaces. See core/backends.py for more docs. """ import datetime import glob import hashlib import json import os import posixpath import tempfile import time from memory_inspector import constants from memory_inspector.backends import adb_client from memory_...
import json from django.core.urlresolvers import reverse from django import http from mox import IsA # noqa from openstack_dashboard import api from openstack_dashboard.dashboards.admin.metadata_defs \ import constants from openstack_dashboard.test import helpers as test class MetadataDefinitionsView(test.Bas...
import unittest from mock import Mock import os, sys sys.path.append(os.path.join(os.path.dirname(__file__), "..", "..", "scripts", "support")) from run_bundler import ConfigLine from run_bundler import CopyFileConfigLine from run_bundler import JOSHUA_PATH from run_bundler import abs_file_path from run_bundler import ...
#!/usr/bin/env python import sys import logging sys.path.append('../../../target/gen-py') from packetstreamer import PacketStreamer from packetstreamer.ttypes import * from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol from thrift.server import TS...
''' ##################################################################### # Check an object that we will use as container element ##################################################################### >>> from vector_indexing_suite_ext import * >>> x = X('hi') >>> x hi >>> x.reset() # a member function that modifies X...
from samba.messaging import Messaging from unittest import TestCase class MessagingTests(TestCase): def get_context(self, *args, **kwargs): kwargs["messaging_path"] = "." return Messaging(*args, **kwargs) def test_register(self): x = self.get_context() def callback(): ...
import asyncio import contextlib import socket import struct from . import ql2_pb2 as p from .net import decodeUTF, Query, Response, Cursor, maybe_profile, convert_pseudo from .net import Connection as ConnectionBase from .errors import * __all__ = ['Connection'] pResponse = p.Response.ResponseType pQuery = p.Query....
""" Provide structured access to documentation. """ from __future__ import print_function import re from textwrap import wrap from nltk.data import load def brown_tagset(tagpattern=None): _format_tagset("brown_tagset", tagpattern) def claws5_tagset(tagpattern=None): _format_tagset("claws5_tagset", tagpatter...
import warnings from contextlib import contextmanager from copy import copy from django.utils.deprecation import RemovedInDjango20Warning # Hard-coded processor for easier use of CSRF protection. _builtin_context_processors = ('django.template.context_processors.csrf',) _current_app_undefined = object() class Cont...
# stdlib from functools import partial import logging import unittest # 3rd from mock import Mock # project from tests.checks.common import Fixtures log = logging.getLogger(__name__) WMISampler = None # Thoughts # Log WMI activity # Mechanism to timeout # Check when pywintypes.com_error are raised # Check the ro...
''' This manages remote shared Ansible objects, mainly roles''' from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os from ansible.errors import AnsibleError from ansible.module_utils.six import string_types # default_readme_template # default_meta_template cl...
#!/usr/bin/env python """ Given an input path and an output path, will put Gzipped versions of all files from the input path to the output path. If the file is not gzippable it will be copied uncompressed. """ from fnmatch import fnmatch import gzip import os import shutil import sys class FakeTime: def time(se...
#!/usr/bin/env python3 import itertools, operator # n is de grootte van de calcudoku. # total is de som van het block. # operator is de bewerking # cel_string is een lijst van decimale getallen dat de vorm van het vak weergeeft # printitems is een array van de juiste oplossingen. class problem: def Set(self,n,total...
# coding: utf-8 from __future__ import unicode_literals from .common import InfoExtractor from ..compat import compat_urlparse from ..utils import ( clean_html, get_element_by_class, int_or_none, parse_iso8601, remove_start, unified_timestamp, ) class NextMediaIE(InfoExtractor): IE_DESC =...
import time, sys import numpy as np import matplotlib.pyplot as plt sys.path.append('../../') from py2Periodic.physics import twoLayerQG from numpy import pi params = { 'f0' : 1.0e-4, 'Lx' : 1.0e6, 'beta' : 1.5e-11, 'defRadius' : 1.5e4, 'H1' : 500.0, 'H2' ...
""" <Program Name> reinstall.py <Started> January 2009 <Author> Carter Butaud <Purpose> Removes an old installation of seattle from a Linux computer and installs a fresh version. """ import os import sys import shutil import uninstall class ReinstallError(Exception): def __init__(self, value): ...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type from yaml.constructor import Constructor, ConstructorError from yaml.nodes import MappingNode from ansible.parsing.yaml.objects import AnsibleMapping, AnsibleSequence, AnsibleUnicode from ansible.vars.unsafe_proxy import wrap_var ...
import common.blockfunctions reload(common.blockfunctions) # import common.helpers as h # reload(h) import varengine.varengine as e reload(e) import maplex.maplex as m reload(m) import maplex.maplexmodel reload(maplex.maplexmodel) # import varengine.varenginemodel # reload(varengine.varenginemodel) import common.arrayo...
#-*- coding: utf-8 -*- from naoqi import ALProxy import time import argparse # 命令行参数解析 """ moveToward()函数用法示例 void ALMotionProxy::moveToward(const float& x, const float& y, const float& theta) 控制机器人以给定的速率移动(归一化的单位,并非m/s,与moveToward()的区别),参考系w为FRAME_ROBOT;非阻塞函数。 参数x, X轴的速率(+1表示正方向的最大速率, -1为反方向)。向X轴负方向则使用负速率。 参数y, Y...
#!/usr/bin/python __author__ = 'vilelag' import os import argparse import subprocess from multiprocessing import Pool import sys def create_parsers(): #parser for the main program parser = argparse.ArgumentParser(description='Run the compute-accuracy test over dictionaries created from word2vec.' ...
from .base import ischema_names from ... import types as sqltypes __all__ = ('INT4RANGE', 'INT8RANGE', 'NUMRANGE') class RangeOperators(object): """ This mixin provides functionality for the Range Operators listed in Table 9-44 of the `postgres documentation`__ for Range Functions and Operators. It i...
import logging import os from pytz import UnknownTimeZoneError, datetime, timezone class Formatter(logging.Formatter): def formatTime(self, record, datefmt=None): try: tz = timezone(os.environ['TZ']) except (KeyError, UnknownTimeZoneError): tz = None try: ct = datetime.datetime.fromti...
# -*- coding: utf-8 -*- """Logging module.""" from __future__ import absolute_import import logging from colorama import Back, Fore, Style class Logger(object): """Static class to store loggers.""" loggers = {} level = None @staticmethod def set_level(level): """ Set level of...
from django.contrib import admin from django.core.paginator import Paginator from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from .models import Event, Child, Parent, Swallow site = admin.AdminSite(name="admin") site.register(User, UserAdmin) class CustomPaginator(Pagin...
from pyanaconda import ui from pyanaconda.ui.communication import hubQ from pyanaconda.flags import flags from pyanaconda.threads import threadMgr from pyanaconda.ui.tui import simpleline as tui from pyanaconda.ui.tui.hubs.summary import SummaryHub from pyanaconda.ui.tui.spokes import StandaloneSpoke from pyanaconda.ui...
from django.db import models from django.forms import ModelForm from django.utils.translation import ugettext_lazy as _ class Patient(models.Model): email = models.EmailField(verbose_name=_(u'Email'), blank=True, null=True) first_name = models.CharField(verbose_name=_(u'First name'), max_length=100, blank=Tru...
#!/usr/bin/env python import io import os import re import sys import unittest import pytest from stakkr.configreader import Config base_dir = os.path.abspath(os.path.dirname(__file__)) sys.path.insert(0, base_dir + '/../') # https://docs.python.org/3/library/unittest.html#assert-methods class ConfigReaderTest(unitte...
from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * class InvalidateTest(BitcoinTestFramework): def __init__(self): super().__init__() self.setup_clean_chain = True self.num_nodes = 3 def setup_network(self): self.nodes...
import numpy as np from pyspark.mllib.common import callMLlibFunc from pyspark.rdd import RDD class KernelDensity(object): """ Estimate probability density at required points given an RDD of samples from the population. Examples -------- >>> kd = KernelDensity() >>> sample = sc.paralleli...
#! /usr/bin/env python ######################################################################## # $HeadURL$ # File : dirac-admin-bdii-info ######################################################################## """ Check info on BDII for a given CE or site """ __RCSID__ = "$Id$" import DIRAC from DIRAC.Core.Base ...
#! /usr/bin/env python3 import argparse import os.path import shutil import utils DIR = os.path.dirname(os.path.abspath(__file__)) DICT_DIR = os.path.join(DIR, "dicts") def parse_args(): parser = argparse.ArgumentParser() parser.add_argument( "url", help="URL from ftp://ftp.gnu.org/gnu/aspell/dict/...
"""High level API for learning with TensorFlow. ## Estimators Train and evaluate TensorFlow models. @@BaseEstimator @@Estimator @@ModeKeys @@DNNClassifier @@DNNRegressor @@LinearClassifier @@LinearRegressor ## Graph actions Perform various training, evaluation, and inference actions on a graph. @@NanLossDuringTra...
import os import re import cx_Oracle import collections import datetime earContentionCode = [2200,2210,2220,3140,3150,4130,4210,4700,4920,5000,5010,5710,6850] #Primary query, Look for all claims/contentions where the participant has at least one contention with an ear-related contention code. #Organize them based fir...
import os import pytest import flask_migrate from base64 import b64encode from powerdnsadmin import create_app from powerdnsadmin.models.base import db from powerdnsadmin.models.user import User from powerdnsadmin.models.setting import Setting from powerdnsadmin.models.api_key import ApiKey app = create_app('../confi...
from mock import Mock, patch try: from unittest2 import TestCase, main except ImportError: from unittest import TestCase, main from ..winterm import WinColor, WinStyle, WinTerm class WinTermTest(TestCase): @patch('colorama.winterm.win32') def testInit(self, mockWin32): mockAtt...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['stableinterface'], 'supported_by': 'core'} import os import traceback SELINUX_IMP_ERR = None try: import selinux HAVE_SELINU...
import json from tempest.api_schema.response.compute.v2_1 import limits as schema from tempest.common import service_client class LimitsClient(service_client.ServiceClient): def show_limits(self): resp, body = self.get("limits") body = json.loads(body) self.validate_response(schema.get_l...
import getopt import numpy as np import h5py import _readfile as readfile import _pysar_utilities as ut from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt import sys import os from matplotlib.colors import LinearSegmentedColormap def Usage(): print ''' plotting the geocoded PySAR product ...
import numpy as np import pytest from astropy.io import ascii from astropy.io.ascii.qdp import _read_table_qdp, _write_table_qdp from astropy.io.ascii.qdp import _get_lines_from_file from astropy.table import Table, Column, MaskedColumn from astropy.utils.exceptions import AstropyUserWarning def test_get_tables_from_...
#!/usr/bin/python results = {} # Test import with no from import ansible.module_utils.foo0 results['foo0'] = ansible.module_utils.foo0.data # Test depthful import with no from import ansible.module_utils.bar0.foo results['bar0'] = ansible.module_utils.bar0.foo.data # Test import of module_utils/foo1.py from ansible...
from __future__ import absolute_import, division, print_function __metaclass__ = type ################################################################################ # Documentation ################################################################################ ANSIBLE_METADATA = {'metadata_version': '1.1', 'statu...
import re import sys import xml.etree.ElementTree import gdb_rsp def GetTargetArch(connection): """Get the CPU architecture of the NaCl application.""" reply = connection.RspRequest('qXfer:features:read:target.xml:0,fff') assert reply[0] == 'l', reply tree = xml.etree.ElementTree.fromstring(reply[1:]) arch...
"""Query build slave hardware info, and print it to stdout as csv.""" import csv import json import logging import sys import urllib2 _MASTERS = [ 'chromium.perf', 'chromium.perf.fyi', 'client.catapult', 'tryserver.chromium.perf', 'tryserver.client.catapult', ] _KEYS = [ 'master', 'builder'...
import os from lib.common import helpers class Module: def __init__(self, mainMenu, params=[]): self.info = { 'Name': 'Invoke-Schtasks', 'Author': ['@mattifestation', '@harmj0y'], 'Description': ('Persist a stager (or script) using schtasks. This has a moderate detec...
# pylint: disable=wrong-import-position import ssl from os import path from functools import partial from pathlib import Path import h11 import pytest from anyio import create_task_group, open_file, EndOfStream from overly import ( Server, ssl_socket_wrapper, default_ssl_cert, send_200, send_303, ...
from __future__ import unicode_literals import sys import traceback from io import BytesIO from unittest import TestCase from wsgiref import simple_server # If data is too large, socket will choke, so write chunks no larger than 32MB # at a time. The rationale behind the 32MB can be found on Django's Trac: # https://...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { 'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community' } DOCUMENTATION = r''' --- module: aci_maintenance_group_node short_description: Manage maintenance group nodes version_a...
# This script is used to parse BOOST special function test data into something # we can easily import in numpy. It is ugly as hell, but it works. from __future__ import division, print_function, absolute_import import re import os from numpy import arccosh, log1p, expm1, arcsinh, arctanh from scipy.special import dig...
from pygments.token import Token def create_toolbar_tokens_func(get_key_bindings, token=None): """ Return a function that generates the toolbar tokens. """ assert callable(get_key_bindings) token = token or Token.Toolbar def get_toolbar_tokens(cli): result = [] result.append((...
""" Some unit tests for the S3 MultiDelete """ import unittest import time from boto.s3.key import Key from boto.s3.deletemarker import DeleteMarker from boto.s3.prefix import Prefix from boto.s3.connection import S3Connection from boto.exception import S3ResponseError class S3MultiDeleteTest(unittest.TestCase): ...
import sqlite3 import json from optparse import OptionParser def makeSchema(db): schemaFile = open('messages.sql', 'r') schema = schemaFile.read() schemaFile.close() conn = sqlite3.connect(db) cursor = conn.cursor() cursor.executescript(schema) cursor.close() conn.close() def loadMe...
from io import BytesIO import pytest from pyhdb.exceptions import InterfaceError from pyhdb.protocol.parts import OptionPart from pyhdb.protocol import constants def test_not_pack_none_value_items(): class DummyOptionPart(OptionPart): kind = 126 option_definition = { # Identifier, (...
from __future__ import print_function from pyspark.sql import SparkSession # $example on:schema_merging$ from pyspark.sql import Row # $example off:schema_merging$ """ A simple example demonstrating Spark SQL data sources. Run with: ./bin/spark-submit examples/src/main/python/sql/datasource.py """ def basic_datas...
# -*- coding: koi8-r -*- import unittest from test import test_support class PEP263Test(unittest.TestCase): def test_pep263(self): self.assertEqual( u"ðÉÔÏÎ".encode("utf-8"), '\xd0\x9f\xd0\xb8\xd1\x82\xd0\xbe\xd0\xbd' ) self.assertEqual( u"\ð".encode("u...
import errno import os import os.path import shutil import tempfile from unittest import mock from oslo_concurrency import processutils from oslo_utils import netutils from magnum.common import exception from magnum.common import utils import magnum.conf from magnum.tests import base CONF = magnum.conf.CONF class ...
#!/usr/bin/env python3 import curwrap import curses import snake import time import os import sys # initializes the curses standard screen stdscr = curses.initscr() def restart_snake(): """Restarts the CLSnake process.""" # exits curses loop curwrap.endC(stdscr) # executes CLSnake python = sys.executable os...
import zmarkdown from zmarkdown import inlinepatterns, util, Extension from zmarkdown.blockprocessors import BlockProcessor import re class MathJaxPattern(inlinepatterns.Pattern): def __init__(self): inlinepatterns.Pattern.__init__(self, r'(?<!\\)\$([^\n]+?)(?<!\\)\$') def handleMatch(self, m): ...
# test_pattern.py -- Tests for Pattern """Tests for Pattern objects""" from morph import ( pattern ) from morph.pattern import ( LiteralPattern, NumericCounterPattern, ) from morph.errors import ( PatternModeError ) from morph.tests import TestCase class PatternTestCase(TestCase): def gen(se...
from __future__ import absolute_import, unicode_literals import re from .w3dtf import _parse_date_w3dtf # 8-bit date handling routines written by ytrewq1. _korean_year = '\ub144' # b3e2 in euc-kr _korean_month = '\uc6d4' # bff9 in euc-kr _korean_day = '\uc77c' # c0cf in euc-kr _korean_am = '\uc624\uc804' # bfc...
#!/usr/bin/env python """ Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License");...
{ 'name': 'Payment Follow-up Management', 'version': '1.0', 'category': 'Accounting & Finance', 'description': """ Module to automate letters for unpaid invoices, with multi-level recalls. ========================================================================= You can define your multiple levels of r...
# ----------------------------------------------------------------------------- # yacc_error1.py # # Bad p_error() function # ----------------------------------------------------------------------------- import sys if ".." not in sys.path: sys.path.insert(0,"..") import ply.yacc as yacc from calclex import tokens # ...
#!/usr/bin/env python """ SYNOPSIS TODO helloworld [-h,--help] [-v,--verbose] [--version] DESCRIPTION TODO This describes how to use this script. This docstring will be printed by the script if there is an error or if the user requests help (-h or --help). EXAMPLES TODO: Show some examples of h...
from __future__ import absolute_import from .auto_number_format import AutoNumberFormat from .contact import Contact from .enums import ColumnType, Symbol, SystemColumnType from ..types import * from ..util import serialize from ..util import deserialize class Column(object): """Smartsheet Column data model."""...
try: import pkg_resources version = pkg_resources.require("Autobahn")[0].version except: ## i.e. no setuptools or no package installed .. version = "?.?.?" import util import useragent import httpstatus import utf8validator import xormasker import websocket import resource import prefixmap i...
from pyotp.otp import OTP import datetime import time import urllib class TOTP(OTP): def __init__(self, *args, **kwargs): """ @option options [Integer] interval (30) the time interval in seconds for OTP This defaults to 30 which is standard. """ self.interva...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals, division import random import string import timeit import os import zipfile import struct #import pstats #import cProfile import dawg def words100k(): zip_name = os.path.join( os.path.abspath(os.path.di...
""" Test clean shutdown functionality of the master """ import mock from twisted.cred import credentials from twisted.internet import defer from twisted.spread import pb from twisted.trial import unittest from buildbot import pbmanager class FakeMaster: initLock = defer.DeferredLock() def addService(self,...
ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} import atexit import mmap import errno import socket from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.pycompat24 import get_exception from ansible.m...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['stableinterface'], 'supported_by': 'core'} import os import re try: import selinux HAS_SELINUX = True except ImportError: ...
# cmdserver.py # Demo code that is not Pythonwin related, but too good to throw away... import win32api import sys from pywin.framework import winout import thread, sys import traceback class ThreadWriter: "Assign an instance to sys.stdout for per-thread printing objects - Courtesy Guido!" def __init__(self): ...
from django.core.management.base import BaseCommand, CommandError from optparse import make_option from django.conf import settings from booki.utils import config from booki.utils.json_wrapper import json class Command(BaseCommand): args = "<name> <value>" help = "Set value for configuration variable." ...
# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function) import math from chempy.chemistry import Equilibrium from chempy.util._expr import Expr from chempy.util.testing import requires from chempy.units import allclose, units_library, Backend, default_units as du, default_constants ...
__version__=''' $Id: rltempfile.py 3959 2012-09-27 14:39:39Z robin $ ''' __doc__='''Helper for the test suite - determines where to write output. When our test suite runs as source, a script "test_foo.py" will typically create "test_foo.pdf" alongside it. But if you are testing a package of compiled code inside a zip...
import unittest import paddle.fluid.framework as framework class ConditionalBlock(unittest.TestCase): def test_const_value(self): self.assertEqual(framework.GRAD_VAR_SUFFIX, "@GRAD") self.assertEqual(framework.TEMP_VAR_NAME, "@TEMP@") self.assertEqual(framework.GRAD_VAR_SUFFIX, "@GRAD") ...
""" Wrapper class that takes a list of template loaders as an argument and attempts to load templates from them in order, caching the result. """ import hashlib from django.template.base import TemplateDoesNotExist from django.template.loader import BaseLoader, get_template_from_string, find_template_loader, make_orig...
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" """ Test the ability to configure the $JARCOM construction variable. """ import TestSCons _python_ = TestSCons._python_ test = TestSCons.TestSCons() test.write('myjar.py', r""" import sys outfile = open(sys.argv[1], 'wb') for f in sys.argv[2:]: in...