content
string
# -*- coding: utf-8 -*- from django.conf import settings from django.core.exceptions import ValidationError from django.db import models from django.test import TestCase from django.utils.translation import ugettext_lazy from django.core.urlresolvers import resolve, reverse, NoReverseMatch from seoutils.models import ...
""" Control an alsaplayer instance. This is really a wrapper for the apcontrol module. apcontrol API: add_and_play(str) -> None add_path(str) -> None add_playlist(str) -> None clear_playlist() -> None get_album() -> str get_artist() -> str get_comment() -> str get_file_path() -> str get_file_path_for_track(int) -> st...
#!/usr/bin/python # -*- coding: utf-8 -*- import traceback from core import dbmysql from core.err_code import OCT_SYSTEM_ERR from core.log import ERROR from modules.api.api_web import web_add_apiresult def web_get_env(session): env = { "USERNAME": session.get("user"), "SESSIONID": session.get("id"), } if (s...
from oslo_config import cfg watcher_applier = cfg.OptGroup(name='watcher_applier', title='Options for the Applier messaging ' 'core') APPLIER_MANAGER_OPTS = [ cfg.IntOpt('workers', default=1, min=1, required...
from testing.test_interpreter import BaseTestInterpreter import uuid class TestFunctionCache(BaseTestInterpreter): def test_declare_function_call(self): output = self.run(''' function myf2197123($a, $b) { return $a + $b; } echo myf2197123(10, 20); ''') assert self.space.in...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Class for managing first arrival travel time inversions""" import os import numpy as np import matplotlib.pyplot as plt from matplotlib.collections import LineCollection import pygimli as pg from pygimli.frameworks import MeshMethodManager from pygimli.utils import g...
# coding=utf-8 import os import unittest from xlscsv import XlsCSV, Format import tempfile __author__ = 'alex' tempdir = tempfile.gettempdir() print 'Save files to [%s]' % tempdir class TestFileTypes(unittest.TestCase): def setUp(self): self.header = ["fruit", "tree"] self.items = ( ...
"""Check RPC argument consistency.""" from collections import defaultdict import os import re import sys # Source files (relative to root) to scan for dispatch tables SOURCES = [ "src/rpc/server.cpp", "src/rpc/blockchain.cpp", "src/rpc/mining.cpp", "src/rpc/misc.cpp", "src/rpc/net.cpp", "src/r...
class RedBlackInsertTestCase(unittest.TestCase): def testInsertBaseCase(self): tree = RedBlackTree(10) self.assertEqual(str(tree), 'black:10') def testInsertBlackParent(self): tree = RedBlackTree(10) tree.insert(15) self.assertEqual(str(tree), 'black:10 -> [None | red:...
""" Unit tests for :class:`iris.analysis.trajectory.Trajectory`. """ from __future__ import (absolute_import, division, print_function) from six.moves import (filter, input, map, range, zip) # noqa # Import iris.tests first so that some things can be initialised before # importing anything else. import iris.tests a...
""" :Authors: - Iason """ import re import time import argparse import logging import sys import math from reader import load_grammar from collections import Counter, defaultdict from symbol import make_nonterminal from earley import Earley from nederhof import Nederhof from topsort import top_sort from sentence impor...
# -*- coding: utf-8 -*- """ /*************************************************************************** SearchPlus - A QGIS plugin Toponomastic searcher ------------------- begin : 2015-06-19 git sha : $Format:%H$ copyright :...
# -*- coding: UTF-8 -*- ''' magento API :copyright: (c) 2010 by Sharoon Thomas. :copyright: (c) 2010-2013 by Openlabs Technologies & Consulting (P) LTD :license: AGPLv3, see LICENSE for more details ''' __all__ = [ 'API', 'Store', 'Magento', 'Customer', 'CustomerGroup', 'Custome...
#!/usr/bin/env python ##################################### # Imports ##################################### # Python native imports import rospy from time import time, sleep import serial.rs485 import minimalmodbus from std_msgs.msg import UInt8, UInt16 # Custom Imports from rover_control.msg import TowerPanTiltCon...
import gi.repository gi.require_version('Budgie', '1.0') from gi.repository import Budgie, GObject, Gtk, Gio import os """ RotationLock Author: David Mohammed Copyright © 2017-2021 Ubuntu Budgie Developers Website=https://ubuntubudgie.org This program is free software: you can redistribute it and/or modify it under t...
import unittest import langapp import redis import flask import json class LangAppPostingMessages(unittest.TestCase): def setUp(self): red = redis.StrictRedis('localhost', 6379, db=0) red.delete('messages') red.delete('messageid') self.app = langapp.app.test_client() def tearDown(self): pass ...
import cv2 import numpy as np from model import Model class Drawer: def __init__(self): self.mouse_pressed = False self.img = np.zeros(shape=(1024, 1024, 3), dtype=np.uint8) self.char_color = (255, 255, 255) def draw(self): """ Method to draw continuous multiple circl...
from openstack.tests.unit import base from openstack.workflow import version IDENTIFIER = 'IDENTIFIER' EXAMPLE = { 'id': IDENTIFIER, 'links': '2', 'status': '3', } class TestVersion(base.TestCase): def test_basic(self): sot = version.Version() self.assertEqual('version', sot.resourc...
import numpy as np #Extrapolates from a given seed sequence def generate_from_seed(model, seed, sequence_length, data_variance, data_mean): seedSeq = seed.copy() output = [] #The generation algorithm is simple: #Step 1 - Given A = [X_0, X_1, ... X_n], generate X_n + 1 #Step 2 - Concatenate X_n + 1 onto A #Step ...
from __future__ import print_function import os def report_memory(i): pid = os.getpid() a2 = os.popen('ps -p %d -o rss,sz' % pid).readlines() print(i, ' ', a2[1], end=' ') return int(a2[1].split()[0]) # This test is disabled -- it uses old API. -ADS 2009-09-07 ## def test_memleak(): ## """Test a...
#!/usr/bin/env python from __future__ import absolute_import, print_function import os import os.path import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit() NAME = "futur...
# -*- coding: utf-8 -*- import json import io from unittest import mock from urllib.parse import urlencode from django.db import connection from django.test.utils import override_settings from services import theme_update from olympia import amo from olympia.addons.models import MigratedLWT from olympia.amo.templat...
#!/usr/bin/env python """This module contains tests for reflection API handlers.""" from absl import app from grr_response_server.gui import api_call_router from grr_response_server.gui import api_test_lib from grr_response_server.gui.api_plugins import reflection as reflection_plugin from grr.test_lib import test_...
import json import os import mock import six import testtools from openstack.baremetal import configdrive class TestPopulateDirectory(testtools.TestCase): def _check(self, metadata, user_data=None, network_data=None): with configdrive.populate_directory(metadata, ...
import datetime from django.test.testcases import TestCase from casexml.apps.stock.models import DocDomainMapping from casexml.apps.stock.models import StockReport, StockTransaction from couchdbkit.exceptions import ResourceNotFound from couchforms.models import XFormInstance from corehq.apps.accounting.tests import...
import sigrokdecode as srd # ... RX = 0 TX = 1 class Decoder(srd.Decoder): api_version = 3 id = 'pan1321' name = 'PAN1321' longname = 'Panasonic PAN1321' desc = 'Bluetooth RF module with Serial Port Profile (SPP).' license = 'gplv2+' inputs = ['uart'] outputs = ['pan1321'] annotati...
#!/usr/bin/env python # encoding: utf-8 import sys import os from glob import glob from metacram import * target_directory = sys.argv[1] out = 'out' d = get_outdir(os.path.join(target_directory, out)) ohai('output: %s' % d('')) ohai('ILLUMINA PIPELINE: %s' % target_directory) left_mates = glob('data/left*') right...
from __future__ import absolute_import from __future__ import print_function import sys import lucene import json from lucene import (SimpleFSDirectory, System, File, Document, Field, StandardAnalyzer, IndexWriter, IndexSearcher, QueryParser) if __name__ == "__main__": lucene.initVM() fullIndexDir = r"c:...
import os import sys import unittest from astroid.manager import AstroidManager, _silent_no_wrap from astroid.bases import BUILTINS from astroid.exceptions import AstroidBuildingException from astroid.tests import resources class AstroidManagerTest(resources.SysPathSetup, resources.AstroidC...
from flask import Blueprint, render_template, redirect, url_for, request, flash from flask_login import login_required from ...models import Category, db_save from ...forms.admin.category import CategoryForm admin_category = Blueprint('admin_category', __name__) @admin_category.route('/') @login_required def index(...
from ANNarchy import * # Compulsory to allow structural plasticity setup(structural_plasticity=True) # Simple neuron type LeakyIntegratorNeuron = Neuron( parameters=""" tau = 10.0 : population baseline = 0.0 """, equations = """ tau * dr/dt + r = baseline + sum(exc) : min=0.0 ...
from __future__ import absolute_import __version__ = '0.7' __author__ = 'Pablo Castellano <<EMAIL>>' __license__ = 'GPLv3+' __all__ = ['libcnml'] import logging logger = logging.getLogger(__name__) # To change the logging level of libcnml use this code in your program: # import libcnml # import logging # libcnml....
""" .. dialect:: mysql+mysqldb :name: MySQL-Python :dbapi: mysqldb :connectstring: mysql+mysqldb://<user>:<password>@<host>[:<port>]/<dbname> :url: http://sourceforge.net/projects/mysql-python .. _mysqldb_unicode: Unicode ------- Please see :ref:`mysql_unicode` for current recommendations on unicode...
''' Optimal result for pebble solitaire state Status: Accepted ''' PRECOMPUTED = {} for _i in range(12): PRECOMPUTED['-' * _i + 'o' + '-' * (11 - _i)] = 1 ############################################################################### def dfs(state): """Depth First Search for best possible score""" glo...
''' To generate a standalone PNG file for a Bokeh application from a single Python script, pass the script name to ``bokeh png`` on the command line: .. code-block:: sh bokeh png app_script.py The generated PNG will be saved in the current working directory with the name ``app_script.png``. It is also possible ...
#! /usr/bin/python # Joe Deller 2014 # Level : Beginner # Uses : Libraries, variables # We can change the Minecraft camera from the normal player view # to a fixed view, which we can move around without moving the player import mcpi.minecraft as minecraft import time mc = minecraft.Minecraft.create() mc.postToChat...
# pylint: disable=no-self-use,invalid-name import numpy from deep_qa.tensors.backend import hardmax from deep_qa.testing.test_case import DeepQaTestCase from keras import backend as K class TestBackendTensorFunctions(DeepQaTestCase): def test_hardmax(self): batch_size = 3 knowledge_length = 5 ...
from PyQt5 import QtCore from picard.config import ( BoolOption, IntOption, ListOption, get_config, ) from picard.const.sys import IS_MACOS from picard.script import ScriptParser from picard.ui import ( PicardDialog, SingletonDialog, ) from picard.ui.moveable_list_view import MoveableListView ...
"""Test the handling of various mapping tasks.""" import cartopy.crs as ccrs import pytest from metpy.plots.mapping import CFProjection def test_cfprojection_arg_mapping(): """Test the projection mapping arguments.""" source = {'source': 'a', 'longitude_of_projection_origin': -100} # 'dest' should be t...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # name: website.py # email: <EMAIL> # # pylint: disable=line-too-long """ ww.website ~~~~~~~~~~ A class to manage websites """ from __future__ import absolute_import, print_function from subprocess import check_output, CalledProcessErr...
import time import logging import datetime import unittest import threading from StringIO import StringIO from .. import jsonrpc from .util import make_http_message logger = logging.getLogger(__name__) def _timeit(f, pargs, iterations=1000): t1 = time.time() for i in xrange(iterations): response = f(...
import sqlite3 from FileTools import * class FileServerDatabase: _databaseFile = ":memory" _connection = None _cursor = None def __init__(self): self._databaseFile = "fileStore.db" self._connection = sqlite3.connect(self._databaseFile) c = self._connection.cursor() c.e...
from nbxmpp.protocol import Iq from nbxmpp.protocol import NodeProcessed from nbxmpp.namespaces import Namespace from nbxmpp.structs import StanzaHandler from nbxmpp.task import iq_request_task from nbxmpp.modules.base import BaseModule from nbxmpp.modules.util import process_response class Ping(BaseModule): def ...
import logging from rdmo.conditions.models import Condition from rdmo.core.imports import (fetch_parents, get_foreign_field, get_m2m_instances, set_common_fields, set_lang_field, validate_instance) from .models import Option, OptionSet from .validators imp...
""" Image signing and management. """ from . import version as versmod from . import boot_record as br import hashlib import struct IMAGE_MAGIC = 0x96f3b83d IMAGE_HEADER_SIZE = 32 TLV_HEADER_SIZE = 4 PAYLOAD_DIGEST_SIZE = 32 # SHA256 hash KEYHASH_SIZE = 32 DEP_IMAGES_KEY = "images" DEP_VERSIONS_KEY = "versions" # I...
import numpy as np import h5py import pylab as pl import glob t2d = [] E2d = [] for f in sorted(glob.glob("2d/flatdensity*.hdf5")): file = h5py.File(f, "r") t2d.append(file["/Header"].attrs["Time"]) u = np.array(file["/PartType0/InternalEnergy"]) E2d.append(np.mean(u)) t3d = [] E3d = [] for f in sorted(glob.g...
"""Integration tests for auth views.""" from django.urls import reverse import pytest @pytest.mark.parametrize( 'name, status_code', [('account_login', 200), ('account_logout', 302), # gets redirected to '/' ]) def test_authentication_pages(db, client, name, status_code): # noqa: D103 # GIVEN...
# -*- coding: utf-8 -*- ''' Genesis Add-on Copyright (C) 2015 lambda This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any ...
{ 'name': 'Purchase Ref Editable', 'version': '8.0.0.0.0', 'category': 'Sales & Purchases', 'sequence': 14, 'summary': '', 'description': """ Purchase Ref Editable ===================== The "Partner Reference" field editable always. Remove the "readonly=True" states """, 'author': 'ADHO...
"""Regularized iterated regression for estimating AR parameters in ARMA models.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from statsmodels.regression.linear_model import OLS from statsmodels.tools.tools import add_constant from s...
""" prepare-yelp.py description: prepare the Yelp data for training in DNNs """ import cPickle as pickle import logging import numpy as np from nlpdatahandlers import YelpDataHandler from textclf.wordvectors.glove import GloVeBox from sklearn.feature_extraction.text import HashingVectorizer LOGGER_PREFIX = ' %s' lo...
from __future__ import unicode_literals import hashlib import logging from collections import OrderedDict, defaultdict from urllib import urlencode from urllib2 import quote from urlparse import parse_qs, urljoin, urlsplit, urlunsplit from mopidy import httpclient, models import requests import mopidy_emby from mop...
# vi:si:et:sw=4:sts=4:ts=4 from yq.util import command from yq.util import config class Init(command.Command): summary = "initialize the yq data" description = """This command will create the files and directories needed by yq.""" def addOptions(self): self.parser.add_option('-f', '--force', acti...
import string from htmllib import HTMLParser from cgi import escape from urlparse import urlparse from formatter import AbstractFormatter from htmlentitydefs import entitydefs from xml.sax.saxutils import quoteattr import re ALPHABET = string.ascii_uppercase + string.ascii_lowercase + \ string.digits + '-_'...
''' Created on 24.05.2014 @author: alex ''' import threading import platform import os from common import listtype, locked, ListParser, ListCompare class ListCompareModel: view = None reload_lock = None compare_lock = None lists = {} def __init__(self, view_): self.view = view_ ...
""" This module defines functions for masking BAL absorption. This module provides two functions: - read_bal - add_bal_rest_frame See the respective docstrings for more details """ import fitsio import numpy as np from picca import constants def read_bal(filename): ##Based on read_dla from picca/py/picca/i...
import pytest from plenum.common.startable import Mode def test_can_send_3pc_batch_by_primary_only(primary_orderer): assert primary_orderer.can_send_3pc_batch() primary_orderer._data.primary_name = "SomeNode:0" assert not primary_orderer.can_send_3pc_batch() def test_can_send_3pc_batch_not_participatin...
import ckan.lib.helpers as h from ckan.common import _ import ckan.controllers.admin as base_admin class AdminController(base_admin.AdminController): def _get_config_form_items(self): # Styles for use in the form.select() macro. styles = [{'text': 'Default', 'value': '/base/css/main.css'}, ...
""" Infinite caching memcached class. Caches forever when passed a timeout of 0. For Django >= 1.3, this module also provides ``MemcachedCache`` and ``PyLibMCCache``, which use the backends of their respective analogs in django's default backend modules. """ import logging import django from django.core.cache.backe...
#!/usr/bin/env python # -*- coding:utf-8 -*- """ author: kakaxi version: 0.1 create_time: 2015/05/13 """ import requests import threading url="http://dldir1.qq.com/qqfile/qq/QQ7.1/14522/QQ7.1.exe" n = 8 filename="QQ7.exe" fd = file(filename, "wb+") def getLength(url): head = requests.head(url) return head.hea...
import ops_piggybacker as oink import openpathsampling as paths from .tools import * from . import common_test_data as common from openpathsampling.tests.test_helpers import make_1d_traj import os.path import sys try: import mdtraj as md except ImportError: HAS_MDTRAJ = False else: HAS_MDTRAJ = True clas...
""" Django Rest Framework view mixins. """ from django.core.exceptions import ValidationError from django.http import Http404 from rest_framework import status from rest_framework.mixins import CreateModelMixin from rest_framework.response import Response class PutAsCreateMixin(CreateModelMixin): """ Backwar...
""" The "Runtime", the top of the organization. Sets up object_store, specializer, compilers in to orchestrate materialization of Externs and initialization of Externs/libraries. """ from builtins import object import logging import ctypes from pych.types import PychArray from pych.object_store import...
import os # Import global settings to make it easier to extend settings. from django.conf.global_settings import * # Import the project module to calculate directories relative to the module # location. PROJECT_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), '../..') # List all Django apps here. Not...
#!/usr/bin/python NWID="a" CONTROLLER_IP='127.0.0.1' """ Start up a Simple topology """ from mininet.net import Mininet from mininet.node import Controller, RemoteController from mininet.log import setLogLevel, info, error, warn, debug from mininet.cli import CLI from mininet.topo import Topo from mininet.util import...
#!/usr/bin/env python """ matisse_config.py, module definition of MatisseConfig class. """ from __future__ import print_function import logging from dirsync import sync import os from shutil import copyfile, copytree, rmtree import sys class MatisseConfig(object): """ MaTiSSe.py configuration. Attributes ---...
#-*- coding:utf-8 -*- """ This file is part of openexp. openexp is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. openexp is distributed in ...
from fontParts.base.base import BaseDict, dynamicProperty, reference from fontParts.base import normalizers from fontParts.base.deprecated import DeprecatedGroups, RemovedGroups class BaseGroups(BaseDict, DeprecatedGroups, RemovedGroups): """ A Groups object. This object normally created as part of a :cl...
import uuid from .servicebase import ServiceBase # Define service and characteristic UUIDs. COLOR_SERVICE_UUID = uuid.UUID('00001802-0000-1000-8000-00805f9b34fb') COLOR_CHAR_UUID = uuid.UUID('00002a06-0000-1000-8000-00805f9b34fb') class Colorific(ServiceBase): """Smart Bulb Colorific! service object.""" ...
import os import re import json import logging import datetime import decimal import binascii from pycoin import encoding from lib import config D = decimal.Decimal decimal.getcontext().prec = 8 def round_out(num): #round out to 8 decimal places return float(D(num)) def normalize_quantity(quantity,...
""" Multiple traveling salesmen (mTSP) problem solver. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import numpy as np import gurobipy def mtsp_solver(cost, salesmen=1, min_cities=None, max_cities=None, **kwargs): """ Multiple traveling salesmen MILP solver using ...
""" This test tests that i18n extraction (`paver i18n_extract -v`) works properly. """ from __future__ import absolute_import import os import random import re import string import subprocess import sys from datetime import datetime, timedelta from unittest import TestCase from i18n import config, dummy, extract, gen...
# -*- coding: utf-8 -*- ######################################################################### ## This scaffolding model makes your app work on Google App Engine too ## File is released under public domain and you can use without limitations ######################################################################### ...
from __future__ import (nested_scopes, generators, division, absolute_import, with_statement, print_function, unicode_literals) import pytest from pants_test.pants_run_integration_test import PantsRunIntegrationTest class PythonRunIntegrationTest(PantsRunIntegrationTest): def test_run_26(...
import mock from nose.tools import eq_ from configman.dotdict import DotDict from socorro.processor.processor_app import ProcessorApp from socorro.external.crashstorage_base import CrashIDNotFound from socorro.unittest.testbase import TestCase def sequencer(*args): def foo(*fargs, **fkwargs): for x in a...
"""Test RPCs related to blockchainstate. Test the following RPCs: - getblockchaininfo - gettxoutsetinfo - getdifficulty - getbestblockhash - getblockhash - getblockheader - getchaintxstats - getnetworkhashps - verifychain Tests correspond to code in rpc/blockchain.cpp. """ from de...
# -*- coding: utf-8 -*- """Parser for NTFS metadata files.""" import uuid import pyfsntfs # pylint: disable=wrong-import-order from dfdatetime import filetime as dfdatetime_filetime from dfdatetime import semantic_time as dfdatetime_semantic_time from dfdatetime import uuid_time as dfdatetime_uuid_time from plaso....
from django.http import HttpResponse from django.template.loader import render_to_string from django.urls import reverse from django.views.generic.edit import FormView from twilio.twiml.voice_response import Gather, VoiceResponse from emojiweather.mixins import CsrfExemptMixin from .forms import VoiceWeatherForm cl...
import pytest from cirq import quirk_url_to_circuit def test_non_physical_operations(): with pytest.raises(NotImplementedError, match="unphysical operation"): _ = quirk_url_to_circuit('https://algassert.com/quirk#circuit={"cols":[["__error__"]]}') with pytest.raises(NotImplementedError, match="unphys...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sqlite3 import os, os.path import sys if __name__ == "__main__": tem_arquivos_csv = False for filename in os.listdir('%s/dados' % os.getcwd()): if filename.endswith('.csv'): tem_arquivos_csv = True break if not tem_arquiv...
import atexit from distutils.version import StrictVersion from os import environ as env import os import subprocess import sys import seesaw from seesaw.externalprocess import WgetDownload, RsyncUpload from seesaw.item import ItemInterpolation, ItemValue from seesaw.pipeline import Pipeline from seesaw.project import ...
import Gaffer import GafferUI QtGui = GafferUI._qtImport( "QtGui" ) QtCore = GafferUI._qtImport( "QtCore" ) class Button( GafferUI.Widget ) : __palette = None def __init__( self, text="", image=None, hasFrame=True, highlightOnOver=True, **kw ) : GafferUI.Widget.__init__( self, QtGui.QPushButton(), **kw ) ...
from __future__ import with_statement import pytest from django.core import mail from django.db import connection from pytest_django_test.app.models import Item # It doesn't matter which order all the _again methods are run, we just need # to check the environment remains constant. # This is possible with some of t...
import sys, stat, traceback, pickle, argparse import time, datetime import os.path from . import environment, interpreter, mesonlib from . import build import platform from . import mlog, coredata from .mesonlib import MesonException parser = argparse.ArgumentParser() default_warning = '1' def add_builtin_argument(...
""":mod:`asuka.services.wsgi` --- WSGI server ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It supports the following servers through `Green Unicorn`_: ``sync`` (default) It should handle most 'normal' types of workloads. You'll want to read http://gunicorn.org/design.html for information on when you might w...
""" Nyaa.si (Anime Bittorrent tracker) @website http://www.nyaa.si/ @provide-api no @using-api no @results HTML @stable no (HTML can change) @parse url, title, content, seed, leech, torrentfile """ from lxml import html from searx.engines.xpath import extract_text from searx.url_util...
"""Package contenant la commande 'decrire'""" from primaires.interpreteur.masque.parametre import Parametre class PrmLister(Parametre): """Commande 'valider voir'. """ def __init__(self): """Constructeur du paramètre""" Parametre.__init__(self, "lister", "list") self.schema = ""...
from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from selene.support.conditions import have from selene.support.shared import browser from tests.acceptance.mixed_driver_management import todomvc def setup_module(): browser.config.driver = webdriver.Chrome(ChromeDriverManage...
import os import platform import pytest from in_place import InPlace from test_in_place_util import TEXT, pylistdir def test_move_first_nobackup(tmpdir): assert pylistdir(tmpdir) == [] p = tmpdir.join("file.txt") p.write(TEXT) with InPlace(str(p), move_first=True) as fp: assert not fp.closed ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # 地址:https://www.liaoxuefeng.com/wiki/1016959663602400/1017063413904832 # Python基础 print('包含中文的str') # Python提供了ord()函数获取字符的整数表示,chr()函数把编码转换为对应的字符 print(ord('A')) print(chr(66)) print(chr(25191)) # 编码 print('ABC'.encode('ascii')) print('中文'.encode('utf-8')) print(b'ABC...
import collections from io import open import os.path from builtins import str import configparser import six class ConfigReaderWriter(object): def __init__(self, **options): pass def store_exists(self, store): return os.path.exists(os.path.expanduser(store)) def dump_config_to_file(sel...
def donuts(count): # +++your code here+++ if count >= 10: count = 'many' else: count = count return 'Number of donuts: '+str(count) # B. both_ends # Given a string s, return a string made of the first 2 # and the last 2 chars of the original string, # so 'spring' yields 'spng'. However...
"""Library of TPU helper functions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import numpy as np from six.moves import xrange # pylint: disable=redefined-builtin from tensorflow.python.platform import tf_logging as logging from tensor...
import time import pymongo import urllib2 import simplejson import praw import pytumblr import twython from songkick import * #setting up mongodb connection def connect_to_mongo(): client = pymongo.MongoClient() db = client.newonspotify global collection collection = db.albums #calling spotify API def get_api_da...
from bitarray import bitarray import copy import logging logger = logging.getLogger(__name__) from bigsi.utils import DEFAULT_LOGGING_LEVEL logger.setLevel(DEFAULT_LOGGING_LEVEL) import numpy as np logger = logging.getLogger(__name__) def transpose_low_mem(bitarrays): logger.info("Using slow, low memory transp...
from lib.alerttask import AlertTask from mozdef_util.query_models import SearchQuery, PhraseMatch class AlertDuoFailOpen(AlertTask): def main(self): search_query = SearchQuery(minutes=15) search_query.add_must(PhraseMatch('summary', 'Failsafe Duo login')) self.filtersManual(search_query)...
# -*- coding:utf-8 -*- import re import scrapy from report_crawler.spiders.__Global_function import get_localtime from report_crawler.spiders.__Global_variable import now_time, end_time class SHU001_Spider(scrapy.Spider): name = 'SHU001' start_urls = ['http://cs.shu.edu.cn/Default.aspx?tabid=556'] domain = 'http://...
#--------------------- # Name: VCF parse v3 :: works with AD - Allele Depth # Purpose: Takes and calls genotypes # v3: Pools [CA, CB, S] vs. [TA, TB] # This is a small modification of the script VCF parse v2 written by John Kelly at KU #--------------------- import sys import math import random if len(sys.argv) != 3:...
from __future__ import absolute_import, unicode_literals import unittest from mopidy.config import validators class ValidateChoiceTest(unittest.TestCase): def test_no_choices_passes(self): validators.validate_choice('foo', None) def test_valid_value_passes(self): validators.validate_choice(...
from odoo import _, api, models from odoo.exceptions import ValidationError class ResPartner(models.Model): _inherit = "res.partner" @api.multi @api.constrains('ref', 'is_company', 'company_id') def _check_ref(self): for partner in self: mode = partner.company_id.partner_ref_uniqu...