content
string
#!/usr/bin/python #-*- coding:utf-8 -*- import socket, select, logging, errno import os, sys, json def cmdRunner(input): import commands cmd_ret = commands.getstatusoutput(input) return json.dumps({'ret':cmd_ret[0], 'out':cmd_ret[1]}, separators=(',', ':')) class _State: def __init__(self): ...
"""Utils for Estimator.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.util import tf_inspect def assert_estimator_contract(tester, estimator_class): """Asserts whether given estimator satisfies the expected contract. This ...
from south.db import db from django.db import models from cmsplugin_filer_file.models import * class Migration: depends_on = ( ("filer", "0008_polymorphic__del_field_file__file_type_plugin_name"), ) def forwards(self, orm): # Adding model 'FilerFile' db.create_table('...
import wx from service.fit import Fit import eos.db import gui.mainFrame from gui import globalEvents as GE from gui.fitCommands.helpers import InternalCommandHistory from gui.fitCommands.calc.fitSystemSecurity import CalcChangeFitSystemSecurityCommand class GuiChangeFitSystemSecurityCommand(wx.Command): def __...
# -*- coding: utf-8 -*- from datetime import timedelta from openerp import api, exceptions, fields, models class Session(models.Model): _name = 'openacademy.session' name = fields.Char(required=True) start_date = fields.Date(default=fields.Date.today) duration = fields.Float(digits=(6, 2), help=...
import re from collections import namedtuple from io import BytesIO try: from Crypto.Cipher import AES CAN_DECRYPT = True except ImportError: CAN_DECRYPT = False from livestreamer.compat import range from livestreamer.exceptions import StreamError from livestreamer.packages.flashmedia.tag import ( AAC...
"""Fixer for print. Change: 'print' into 'print()' 'print ...' into 'print(...)' 'print ... ,' into 'print(..., end=" ")' 'print >>x, ...' into 'print(..., file=x)' No changes are applied if print_function is imported from __future__ """ # Local imports from .. import patcomp from ....
from construct import * from sbp import SBP from sbp.utils import fmt_repr # Automatically generated from piksi/yaml/swiftnav/sbp/observation.yaml # with generate.py at 2015-03-24 09:47:42.317363. Please do not hand edit! class ObsGPSTime(object): """ObsGPSTime. A wire-appropriate GPS time, defined as the num...
import re xpath_tokenizer_re = re.compile( "(" "'[^']*'|\"[^\"]*\"|" "::|" "//?|" "\.\.|" "\(\)|" "[/.*:\[\]\(\)@=])|" "((?:\{[^}]+\})?[^/\[\]\(\)@=\s]+)|" "\s+" ) def xpath_tokenizer(pattern, namespaces=None): for token in xpath_tokenizer_re.findall(pattern): tag =...
"""Fixer for 'raise E, V, T' raise -> raise raise E -> raise E raise E, V -> raise E(V) raise E, V, T -> raise E(V).with_traceback(T) raise E, None, T -> raise E.with_traceback(T) raise (((E, E'), E''), E'''), V -> raise E(V) raise "foo", V, T -> warns about string exceptions CAVEATS:...
import os from datetime import datetime from api.bluemix_vision_recognition import VisionRecognizer from api.echonest import Echonest def read_file(path): lines = [] with open(path, "r", encoding="utf-8") as f: lines = f.readlines() lines = [ln.strip(os.linesep) for ln in lines] return li...
#!/usr/bin/env python import sys extras = {} try: from setuptools import setup extras['zip_safe'] = False if sys.version_info < (2, 6): extras['install_requires'] = ['multiprocessing'] except ImportError: from distutils.core import setup setup(name='futures', version='2.1.4', descr...
from CoreGraphics import * import math # for pi import string import sys, os import re def parselog(inFile): f = open(inFile) hunt = 'getTime' ipList = {} querySource = {} plotPoints = [] maxTime=0 minTime = 36*60*60 spaceExp = re.compile(r'\s+') print "Reading " + inFile while 1: lines = f.readlines(10...
class RegressionWindow(object): def __init__(self, build_before_failure, failing_build, failing_tests=None): self._build_before_failure = build_before_failure self._failing_build = failing_build self._failing_tests = failing_tests self._revisions = None def build_before_failure(...
#!/usr/bin/env python # -*- coding: utf-8 -*- def trim( name, length): if len( name ) <= length: return name else: last_space = name.find(" ") if last_space == -1: return name[:35] else: return trim( name[:last_space], length) def translate(...
""" Classes representing sampled trajectories. Sampled trajectories do not support evaluation of derivative values such as velocities or accelerations. To evaulate these properties a splined trajectory should be constructed. See L{splined} """ # Copyright (C) 2009-2011 University of Edinburgh # # This file is part of ...
import copy from oslo_serialization import jsonutils import six from nova import objects from nova.objects import base from nova.objects import fields class PciDevicePool(base.NovaObject): # Version 1.0: Initial version VERSION = '1.0' fields = { 'product_id': fields.StringField(), 'ven...
''' Blocks and utilities for ATSC (Advanced Television Systems Committee) module. ''' import os try: from atsc_swig import * except ImportError: dirname, filename = os.path.split(os.path.abspath(__file__)) __path__.append(os.path.join(dirname, "..", "..", "swig")) from atsc_swig import *
# testyacc.py import unittest try: import StringIO except ImportError: import io as StringIO import sys import os sys.path.insert(0,"..") sys.tracebacklimit = 0 import ply.yacc def check_expected(result,expected): resultlines = [] for line in result.splitlines(): if line.startswith("WARNING...
""" Maximum likelihood covariance estimator. """ # Gael Varoquaux <<EMAIL>> # Virgile Fritsch <<EMAIL>> # # License: BSD 3 clause # avoid division truncation from __future__ import division import warnings import numpy as np from scipy import linalg from ..base import BaseEstimator from ..utils impo...
# -*- coding: utf-8 -*- """ pygments.lexers.go ~~~~~~~~~~~~~~~~~~ Lexers for the Google Go language. :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re from pygments.lexer import RegexLexer, bygroups, words from pygments.token...
# -*- coding: utf-8 -*- """ jinja2.tests ~~~~~~~~~~~~ Jinja test functions. Used with the "is" operator. :copyright: (c) 2010 by the Jinja Team. :license: BSD, see LICENSE for more details. """ import re from collections import Mapping from jinja2.runtime import Undefined from jinja2._compat impor...
from pymomo.utilities import build from nose.tools import * import unittest import os.path import os import platform from pymomo.exceptions import * from pymomo.utilities.paths import MomoPaths class TestSettingsDirectory: def setUp(self): self.paths = MomoPaths() self.confdir = os.path.join(os.path.expanduser('~...
import boto def get_manager(cls): """ Returns the appropriate Manager class for a given Model class. It does this by looking in the boto config for a section like this:: [DB] db_type = SimpleDB db_user = <aws access key id> db_passwd = <aws secret access key> db_n...
HOSTS = [ "<EMAIL>", "<EMAIL>", ] ''' workspace configuration ''' #root dir for workspace, can be set as any director with real user account ROOT_DIR = "/home/paddle" ''' network configuration ''' #pserver nics PADDLE_NIC = "eth0" #pserver port PADDLE_PORT = 7164 #pserver ports num PADDLE_PORTS_NUM = 2 #pserver...
#!/home/upmc_aren/python_env/bin/python import SocketServer from threading import Thread import subprocess """ run few command on remote node in yanoama commands are coded two comma-separated integers only codes list: 0,0: update main sources 0,1: bootstrap 0,2: shutdown (kill pilot and amend) 0,3: start amen d...
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Complaint' db.create_table('bounces_complaint', ( ('id', self.gf('django.db.mo...
import os # make rtconfig.h from .config def mk_rtconfig(filename): try: config = file(filename) except: print 'open .config failed' return rtconfig = file('rtconfig.h', 'w') rtconfig.write('#ifndef RT_CONFIG_H__\n') rtconfig.write('#define RT_CONFIG_H__\n\n') empty_l...
# -*- coding: utf-8 -*- """ *************************************************************************** RasterOptionsWidget.py --------------------- Date : December 2016 Copyright : (C) 2016 by Alexander Bruy Email : alexander dot bruy at gmail dot com ****...
"""Utilities for working with threads and ``Futures``. ``Futures`` are a pattern for concurrent programming introduced in Python 3.2 in the `concurrent.futures` package (this package has also been backported to older versions of Python and can be installed with ``pip install futures``). Tornado will use `concurrent.f...
import unittest import boto3 from airflow import configuration from airflow.contrib.hooks.emr_hook import EmrHook try: from moto import mock_emr except ImportError: mock_emr = None @unittest.skipIf(mock_emr is None, 'moto package not present') class TestEmrHook(unittest.TestCase): @mock_emr def setU...
"""SCons.Tool.mslib Tool-specific initialization for lib (MicroSoft library archiver). There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, ...
class A(object): def __init__(self): pass class AA(A): def __init__(self): A.__init__(self) print("Constructor AA was called") class B(A): def <warning descr="Call to __init__ of super class is missed">__init__</warning>(self): print("Constructor B was called") class C(B): def __init__(self):...
import binascii import StringIO class PKCS7Encoder(object): ''' RFC 2315: PKCS#7 page 21 Some content-encryption algorithms assume the input length is a multiple of k octets, where k > 1, and let the application define a method for handling inputs whose lengths are not a multiple of k octets. F...
""" Copyright (c) 2012-2013 RockStor, Inc. <http://rockstor.com> This file is part of RockStor. RockStor 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 2 of the License, or (at your option) any la...
import sys import asyncio import os import types import functools from collections import namedtuple from collections.abc import Iterator import abc from typing import List, Union, NamedTuple import uuid import yaml import logging log = logging.getLogger(__name__) Fire = NamedTuple('Fire', [('rate', int), ('duration...
from selenium.common.exceptions import (ElementNotInteractableException, ElementNotSelectableException, ElementNotVisibleException, ErrorInResponseException, In...
"""SCons.Tool.dvi Common DVI Builder definition for various other Tool modules that use it. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated document...
import sys import attr import coverage import pytest from covimerage._compat import StringIO def test_filereporter(): from covimerage.coveragepy import FileReporter f = FileReporter('/doesnotexist') assert repr(f) == "<CovimerageFileReporter '/doesnotexist'>" with pytest.raises(coverage.misc.NoSou...
from airflow.hooks.postgres_hook import PostgresHook from airflow.hooks.S3_hook import S3Hook from airflow.models import BaseOperator from airflow.utils.decorators import apply_defaults class RedshiftToS3Transfer(BaseOperator): """ Executes an UNLOAD command to s3 as a CSV with headers :param schema: ref...
import os import sys import ctypes def get_resource(relative): # First try from the local directory. This might come handy in case we want # to provide updates or allow the user to run custom signatures. path = os.path.join(os.getcwd(), relative) # In case the resource doesn't exist in the current dire...
from random import uniform from .gameitem import GameItem class Greenery(GameItem): layer = 0 # ground level def __init__(self, **kwargs): GameItem.__init__(self, **kwargs) self.randomise_position() self.scale = uniform(0.5, 2) self.rot = uniform(0, 360) class Tree(Greenery): ...
from .utils import SKIP_IN_PATH, NamespacedClient, _make_path, query_params class IngestClient(NamespacedClient): @query_params("master_timeout", "summary") def get_pipeline(self, id=None, params=None, headers=None): """ Returns a pipeline. `<https://www.elastic.co/guide/en/elasticsea...
"""Dummy Socks5 server for testing.""" import socket import threading import queue import logging logger = logging.getLogger("TestFramework.socks5") # Protocol constants class Command: CONNECT = 0x01 class AddressType: IPV4 = 0x01 DOMAINNAME = 0x03 IPV6 = 0x04 # Utility functions def recvall(s, n):...
# -*- coding: utf-8 -*- # __ # /__) _ _ _ _ _/ _ # / ( (- (/ (/ (- _) / _) # / """ requests HTTP library ~~~~~~~~~~~~~~~~~~~~~ Requests is an HTTP library, written in Python, for human beings. Basic GET usage: >>> import requests >>> r = requests.get('http://python.org') >>> r.sta...
import uno import unohelper import string import re from com.sun.star.task import XJobExecutor if __name__<>"package": from lib.gui import * from LoginTest import * database="test" uid = 3 class ConvertFieldsToBraces( unohelper.Base, XJobExecutor ): def __init__(self, ctx): self.ctx = c...
import sys from getopt import getopt import os import re #import types TERM_BOLD_START = "\033[1m" TERM_BOLD_END = "\033[0m" class Option: def __init__(self, letter, name, desc, parser, set_once, default, excuses, requires, save): assert not name is None self.letter = letter self.name = na...
from spack import * class RAffyrnadegradation(RPackage): """The package helps with the assessment and correction of RNA degradation effects in Affymetrix 3' expression arrays. The parameter d gives a robust and accurate measure of RNA integrity. The correction removes the probe positional bias, an...
from VanishingPoint import * import os import time def direction(img,xa,ya,xb,yb,width,height): #xa,ya,xb,yb=point[0],point[1],point[2],point[3] cenx = xa+(xb-xa)/2 ceny = ya+(yb-ya)/2 centerx=width/2 centery = height/2 timeout = time.time() + 5 #while True: #_,img = cam.read() print("image center are :", cen...
# -*- coding: utf-8 -*- { 'name': "Open Academy", 'summary': """Manage trainings""", # 'description': """ # Open Academy module for managing trainings: # - training courses # - training sessions # - attendees registration 'author': "Vauxoo", 'website': "http://www.vauxoo.com", ...
from datetime import datetime, timedelta from openerp import api, fields, models, _ from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT, float_compare from openerp.exceptions import UserError class SaleOrder(models.Model): _inherit = "sale.order" @api.model def _default_warehouse_id(self): c...
from django.core.management.base import LabelCommand from optparse import make_option from extensions.management.jobs import get_job, print_jobs class Command(LabelCommand): option_list = LabelCommand.option_list + ( make_option('--list', '-l', action="store_true", dest="list_jobs", help="List ...
# -*- coding: utf-8 -*- import time from datetime import datetime from dateutil.relativedelta import relativedelta from openerp import api, fields, models, _ from openerp.exceptions import UserError class AccountAgedTrialBalance(models.TransientModel): _name = 'account.aged.trial.balance' _inherit = 'accoun...
"""Support for file notification.""" import os import voluptuous as vol from homeassistant.components.notify import ( ATTR_TITLE, ATTR_TITLE_DEFAULT, PLATFORM_SCHEMA, BaseNotificationService, ) from homeassistant.const import CONF_FILENAME import homeassistant.helpers.config_validation as cv import ho...
"""Test custom catalog index.""" from unittest.mock import Mock from pyramid import testing from pytest import fixture from pytest import raises class TestField: _marker = object() @fixture def inst(self): from hypatia.field import FieldIndex from BTrees import family64 def _dis...
""" The I{query} module defines a class for performing schema queries. """ from logging import getLogger from suds import * from suds.sudsobject import * from suds.xsd import qualify, isqref from suds.xsd.sxbuiltin import Factory log = getLogger(__name__) class Query(Object): """ Schema query base class. ...
import unittest import datetime import pytz import numpy as np from zipline.finance.trading import SimulationParameters from zipline.finance import trading from zipline.algorithm import TradingAlgorithm from zipline.protocol import ( Event, DATASOURCE_TYPE ) class BuyAndHoldAlgorithm(TradingAlgorithm): ...
from openerp.osv import fields, osv class account_common_partner_report(osv.osv_memory): _name = 'account.common.partner.report' _description = 'Account Common Partner Report' _inherit = "account.common.report" _columns = { 'result_selection': fields.selection([('customer','Receivable Accounts'...
# -*- coding: utf-8 -*- """ pygments.lexers.resource ~~~~~~~~~~~~~~~~~~~~~~~~ Lexer for resource definition files. :copyright: Copyright 2006-2019 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re from pygments.lexer import RegexLexer, bygroups, words from ...
__version__ = "2.2.1" from sys import version_info def detect(aBuf): if ((version_info < (3, 0) and isinstance(aBuf, unicode)) or (version_info >= (3, 0) and not isinstance(aBuf, bytes))): raise ValueError('Expected a bytes object, not a unicode object') from . import universaldetector ...
import datetime import uuid import mock from oslo_config import cfg from oslo_log import log as logging from oslo_messaging.rpc import client as rpc_client from mistral.db.v2 import api as db_api from mistral.db.v2.sqlalchemy import models from mistral.engine import default_engine as d_eng from mistral import excepti...
"""Win32 (win32ui and WGL)-specific font providers """ from OpenGLContext.scenegraph.text import fontprovider, wglfont class WGLOutlineFonts( fontprovider.FontProvider ): """Font provider for WGL outline (polygon) fonts""" format = "polygon" def get( self, fontStyle, mode=None ): """Get a WGLOutlin...
from ryu.controller import handler from ryu.controller import ofp_event from ryu.lib import dpid as dpid_lib from ryu.lib.packet import vrrp from ryu.ofproto import ether from ryu.ofproto import inet from ryu.ofproto import ofproto_v1_2 from ryu.ofproto import ofproto_v1_3 from ryu.services.protocols.vrrp import monito...
import os import unittest from datetime import datetime from esdl import CubeConfig from esdl.providers.precip import PrecipProvider from test.providers.provider_test_utils import ProviderTestBase from esdl.util import Config SOURCE_DIR = Config.instance().get_cube_source_path('CPC_precip') class PrecipProviderTest...
import json import os import pickle import unittest import sys from nose.plugins.skip import SkipTest try: from pyVmomi import vim, vmodl except ImportError: raise SkipTest("test_vmware_inventory.py requires the python module 'pyVmomi'") try: from vmware_inventory import VMWareInventory except ImportErro...
import re from .htmlformatters import LinkFormatter, HtmlFormatter _format_url = LinkFormatter().format_url _generic_escapes = (('&', '&amp;'), ('<', '&lt;'), ('>', '&gt;')) _attribute_escapes = _generic_escapes \ + (('"', '&quot;'), ('\n', '&#10;'), ('\r', '&#13;'), ('\t', '&#09;')) _illegal_chars_in_xml =...
from __future__ import absolute_import, division, print_function, \ with_statement import os import json import sys import getopt import logging from shadowsocks.common import to_bytes, to_str, IPNetwork from shadowsocks import encrypt VERBOSE_LEVEL = 5 verbose = 0 def check_python(): info = sys.version_i...
from metrics import power from measurements import smoothness_controller from telemetry.page import page_test class Smoothness(page_test.PageTest): def __init__(self): super(Smoothness, self).__init__() self._power_metric = None self._smoothness_controller = None @classmethod def CustomizeBrowserOp...
import datetime from openerp.osv import orm from openerp.tools import (DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT) class sale_order_line(orm.Model): """Adds two exception functions to be called by the sale_exceptions module. The first one will ensure that an order ...
# -*- coding: utf-8 -*- """ *************************************************************************** SelectByExpression.py --------------------- Date : July 2014 Copyright : (C) 2014 by Michaël Douchin ***********************************************************************...
""" .. dialect:: postgresql+pg8000 :name: pg8000 :dbapi: pg8000 :connectstring: postgresql+pg8000://user:password@host:port/dbname[?key=value&key=value...] :url: http://pybrary.net/pg8000/ Unicode ------- pg8000 requires that the postgresql client encoding be configured in the postgresql.conf file in ...
from Exscript.parselib.Exception import LexerException, \ CompileError, \ ExecuteError class Lexer(object): def __init__(self, parser_cls, *args, **kwargs): """ The given args are passed to the parser_cls constructor. ...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os from ansible.errors.yaml_strings import * class AnsibleError(Exception): ''' This is the base class for all errors raised from Ansible code, and can be instantiated with two optional parameters beyond the ...
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, ...
from kivy.app import App from kivy.factory import Factory from kivy.properties import ObjectProperty from kivy.lang import Builder from kivy.uix.checkbox import CheckBox from kivy.uix.label import Label from kivy.uix.widget import Widget from electrum.gui.kivy.i18n import _ Builder.load_string(''' <Question@Popup> ...
from django.conf import settings TRANSTOOL_DL_URL = getattr(settings, 'TRANSTOOL_DL_URL', None) # http://example.com/localemessages/export/ TRANSTOOL_DL_KEY = getattr(settings, 'TRANSTOOL_DL_KEY', None) # for import translates from remote server TRANSTOOL_EXPORT_KEY = getattr(settings, 'TRANSTOOL_EXPORT_KEY', None)...
class GENIDatapath(): def __init__ (self, dom): super(GENIDatapath, self).__init__() self.component_id = None if dom.tag == u'{%s}datapath' % (OFNSv3): self.__parse_openflowv3_datapath(dom) def __parse_openflowv3_datapath (self, dom): self.component_id = dom.get("component_id") cmid = d...
# coding: utf-8 """Base app views""" import os import logging import datetime import re from urlparse import urlparse, urljoin from flask import abort, current_app, jsonify, redirect, render_template, session, url_for, request, views from flask.ext.babel import lazy_gettext as _ import cla_public.apps.base.filters ...
"""Unittests for mysql.connector.abstracts """ from decimal import Decimal from operator import attrgetter import unittest import tests from tests import PY2, foreach_cnx from mysql.connector.connection import MySQLConnection from mysql.connector.constants import RefreshOption from mysql.connector import errors try...
""" Tests for student enrollment. """ from mock import patch, Mock import ddt from nose.tools import raises import unittest from django.test.utils import override_settings from django.conf import settings from course_modes.models import CourseMode from enrollment import api from enrollment.errors import EnrollmentApi...
""" Compressing GANs using Knowledge Distillation. Teacher GAN: ESRGAN (https://github.com/captain-pool/E2_ESRGAN) Citation: @article{DBLP:journals/corr/abs-1902-00159, author = {Angeline Aguinaldo and Ping{-}Yeh Chiang and Alexander Gain and Ameya Patil and Kolten Pearson and Soheil F...
#!/usr/bin/env python import os import shutil import subprocess import sys import tempfile import warnings from django import contrib # databrowse is deprecated, but we still want to run its tests warnings.filterwarnings('ignore', "The Databrowse contrib app is deprecated", PendingDeprecationW...
# -*- coding: utf-8 -*- import pytest from ..fixtures import parametrize from korona.html.tags import Col from korona.templates.html.tags import col from korona.exceptions import TagAttributeError @parametrize('attributes', [ ({'align': 'char'}), ({'align': 'char', 'char': '.'}), ({'align': 'char', 'ch...
#!/usr/bin/env python import sys import subprocess from setuptools import setup, Extension from runspade import __version__ try: import bdist_mpkg except: # This is not a mac pass if sys.platform == "win32": ext = Extension("tlslite.utils.win32prng", sources=["tlslite/utils/win...
import os import sys from itertools import takewhile from django.apps import apps from django.core.management.base import BaseCommand, CommandError from django.db.migrations import Migration from django.db.migrations.autodetector import MigrationAutodetector from django.db.migrations.loader import MigrationLoader from...
import pytest from webdriver import MoveTargetOutOfBoundsException from tests.perform_actions.support.mouse import get_inview_center, get_viewport_rect from tests.support.inline import inline def origin_doc(inner_style, outer_style=""): return inline(""" <div id="outer" style="{1}" onmousemove=...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 列表生成式 # 例1:使用列表生成式,将列表list1中的元素转小写,并过滤list1中的非字符串元素 # isinstance是Python内置函数,用于判断给定对象是否是给定的类型 list1 = ['Hello', 'World', 18, 'Apple', None] list2 = [s.lower() for s in list1 if isinstance(s, str)] print(list2) if list2 == ['hello', 'world', 'apple']: print('测试通过!'...
'''Define SearchEngine for search dialogs.''' import re from tkinter import StringVar, BooleanVar, TclError import tkinter.messagebox as tkMessageBox def get(root): '''Return the singleton SearchEngine instance for the process. The single SearchEngine saves settings between dialog instances. If there is n...
# coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function import unittest import sys import os from asn1crypto import csr, util from ._unittest_compat import patch patch() if sys.version_info < (3,): byte_cls = str num_cls = long # noqa else: byte_cls = bytes ...
"""Tests for sync_replicas_optimizer.py.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import time from tensorflow.python.framework import constant_op from tensorflow.python.framework import ops from tensorflow.python.framework.test_util import create...
try: import shade HAS_SHADE = True except ImportError: HAS_SHADE = False def _needs_update(module, secgroup): """Check for differences in the updatable values. NOTE: We don't currently allow name updates. """ if secgroup['description'] != module.params['description']: return True ...
# encoding=utf-8 ################################# # Link: http://www.ideawu.net/ ################################# import sys, os, shutil, datetime import antlr3 import antlr3.tree from ExprLexer import ExprLexer from ExprParser import ExprParser class CpyEngine: found_files = set() def find_imports(self, srcfile...
""" Unit Tests for remote procedure calls using queue """ import ddt import mock from oslo_config import cfg from manila import context from manila import db from manila import exception from manila import manager from manila import service from manila import test from manila import utils from manila import wsgi tes...
import sys def create_display(opts, tests, total_tests, workers): if opts.quiet: return NopDisplay() of_total = (' of %d' % total_tests) if (tests != total_tests) else '' header = '-- Testing: %d%s tests, %d workers --' % (tests, of_total, workers) progress_bar = None if opts.succinct an...
from __future__ import print_function import shutil from difflib import unified_diff import matplotlib import os import sys from matplotlib import pyplot as plt if os.name == "posix" and 'DISPLAY' not in os.environ: print("MATPLOTLIB: No Display found, using non-interactive svg backend", file=sys.stderr) m...
import datetime from sleepypuppy import db from BeautifulSoup import BeautifulSoup as bs class Capture(db.Model): """ Capture model contains the following parameters: assessment = assessment name(s) assocaited with capture url = url where cross-site scripting was triggered referrer = referrer str...
D = 512 from vocab import Vocabulary input_sentence = 'the dog ran'.split() rules = [ ('S', ['NP', 'VP']), ('VP', ['V']), ('NP', ['DET', 'N']), ] words = { 'N': 'man dog'.split(), 'DET': 'a the'.split(), 'V': 'ran saw'.split(), } def label_word(s): best = None for w in wo...
import logging import subprocess import signal from lnst.Common.Parameters import Param, StrParam, IntParam, FloatParam from lnst.Common.Parameters import IpParam, DeviceOrIpParam from lnst.Tests.BaseTestModule import BaseTestModule, TestModuleError class TestPMD(BaseTestModule): coremask = StrParam(mandatory=True...
# coding: utf8 { '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"Uaktualnij" jest dodatkowym wyrażeniem postaci "pole1=\'nowawartość\'". Nie możesz uaktualnić lub usunąć wyników z JOIN:', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%...
""" Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. """ __author__ = 'Danyang' class Solution: def minPathSum(self, grid): """ ...