prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
taddr = None else: class mac_linux(netaddr.mac_unix): pass mac_linux.word_fmt = '%.2x' from ansible import errors # ---- IP address and network query helpers ---- def _empty_ipaddr_query(v, vtype): # We don't have any query to process, so just check what type the user # expects, and return th...
nd next_ip <= last_usable: return str(netaddr.IPAddress(int(v.ip) + 1)) def _prefix_query(v): return int(v.prefixlen) def _previous_usable_query(v, vtype): if vtype == 'address': "Does it make sense to raise an error" raise errors.AnsibleFilterError('Not a network address') ...
ble, last_usable = _first_last(v) previous_ip = int(netaddr.IPAddress(int(v.ip) - 1)) if previous_ip >= first_usable and previous_ip <= last_usable: return str(netaddr.IPAddress(int(v.ip) - 1)) def _private_query(v, value): if v.is_private(): return value def _pub...
#!/usr/bin/env python # Copyright (C) 2011 Aaron Lindsay <aaron@aclindsay.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your op...
mplied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import os import sys from time impo...
d_file = "" #holds the name of file holding our pid def daemonize(pid_filename, daemon_fn): """Daemonize the current process, store the new pid in pid_filename, and call daemon_fn() to continue execution.""" global pid_file pid_file = pid_filename try: #fork off a process, kill the parent ...
import os import codecs try: from setuptools import (setup, find_packages) except ImportError: from distutils.core import (setup, find_packages) VERSION = (0, 2, 0) __version__ = '.'.join(map(str, VERSION[:3])) + "".join(VERSION[3:]) __package_name__ = 'pelican-readtime' __description__ = 'Plugin for Pelica...
name=__package_name__, version=__versi
on__, description=__description__, long_description=long_description, url=__repository_url__, download_url=__download_url__, license='MIT', author=__contact_names__, author_email=__contact_emails__, maintainer=__contact_names__, maintainer_email=__contact_emails__, classifiers=[ ...
# -*- coding: utf-8 -*- from django.core.exceptions import ValidationError from django.forms.util import flatatt, ErrorDict, ErrorList from django.test import TestCase from django.utils.s
afestring import mark_safe from django.utils.translation import ugettext_lazy class FormsUtilTestCase(TestCase): # Tests for forms/util.py module. def test_flatatt(self): ########### # flatatt # ########### self.assertEqual(flatatt({'id': "header"}), u' id="header"') ...
validation_error(self): ################### # ValidationError # ################### # Can take a string. self.assertHTMLEqual(str(ErrorList(ValidationError("There was an error.").messages)), '<ul class="errorlist"><li>There was an error.</li></ul>') ...
from django.contrib.auth import logout from django.contrib.auth.decorators import login_required from django.contrib.auth.signals import user_logged_out from django.dispatch import receiver from django.http import HttpResponseRedirect from django.urls import reverse from django.views.decorators.cache import never_cache...
ier.auth_backend import RepanierAuthBackend @login_required() @csrf_protect @never_cache def logout_view(request): """ Logs out the user and displays 'You are logged out' message. """ logout(request) # pages-root is the django cms root page. # pages-root may be replaced by login_form to go to ...
verse("pages-root")) @receiver(user_logged_out) def receiver_user_logged_out(sender, request, user, **kwargs): RepanierAuthBackend.remove_staff_right(user=user)
#!/usr/bin/env python #------------------------------------------------------------ # Script which demonstrates how to find the best-fit # parameters of a Voigt line-shape model # # Vog, 26 Mar 2012 #------------------------------------------------------------ import numpy from matplotlib.pyplot import figure, show, r...
====") print("Initial params:", fitter.params0) print("Params: ", fitter.params) print("Iterations: ", fitter.niter) print("Function ev: ", fitter.nfev) print("Uncertainties: ", fitter.xerror) print("dof: ", fitter.dof) prin
t("chi^2, rchi2: ", fitter.chi2_min, fitter.rchi2_min) print("stderr: ", fitter.stderr) print("Status: ", fitter.status) alphaD, alphaL, nu_0, I, a_back, b_back = fitter.params c1 = 1.0692 c2 = 0.86639 hwhm = 0.5*(c1*alphaL+numpy.sqrt(c2*alphaL**2+4*alphaD**2)) print("\nFWHM Voigt profile: ", 2*h...
from django.core import cache from django.core.exceptions import MiddlewareNotUsed from versionedcache.debug import CacheClass class CacheDebugMiddleware(object): def __init__(self): if not isinstance(cache
.cache, CacheClass): raise MiddlewareNotUsed() def process_request(self, request): if request.user.is_superuser and 'cache_debug' in request.GET: action
= request.GET['cache_debug'] # only two actions allowed if action not in ('turn_off', 'write_only'): return # implement action getattr(cache.cache, action)()
) == 'extended': return None separator = '' if 'cciss' in self.name or 'loop' in self.name: separator = 'p' return '%s%s%s' % (self.name, separator, self.next_count()) class Partition(object): def __init__(self, name, count, device, begin, end, partition_type, ...
) return pv def add_vg(self, **kwargs): vg = Vg(**kwargs) self.vgs.append(vg) return vg def add_lv(self, **kwargs): lv = Lv(**kwargs) self.lvs.append(lv) return lv def add_fs(self, **kwargs): fs = Fs(**kwargs) sel
f.fss.append(fs) return fs def add_md(self, **kwargs): mdkwargs = {} mdkwargs['name'] = kwargs.get('name') or self.md_next_name() mdkwargs['level'] = kwargs.get('level') or 'mirror' md = Md(**mdkwargs) self.mds.append(md) return md def md_by_name(self, n...
# -*- coding: utf-8 -*- from sqlalchemy.ext.declarative import declarative_base from zope.sqlalchemy import ZopeTransactionExtension from sqlalch
emy.orm import scoped_session, sessionmaker DeclarativeBase = declarative_base() maker = sessionmaker(autoflush=True, autocommit=False, extension=ZopeTransactionExtension()) DBSession = scoped_session(maker) metadata = DeclarativeBase.metadata def init_model(engine1 ): """Call me before ...
gine1 from .logsurvey import LogSurvey
se() sock = None continue if sock is None: raise Retry return sock familystr = {socket.AF_INET: "IPv4", socket.AF_INET6: "IPv6", socket.AF_UNSPEC: "Unspecified-IPv4/6"} opmsg = "Connecting over %s to %s:...
ansport = paramiko.Transport((hostip, 22)) transport.connect(username=username, password=password) with tempfile.NamedTemporaryFile() as ftmp: sftp = parami
ko.SFTPClient.from_transport(transport) sftp.get(remotepath, ftmp.name) sftp.close() transport.close() self.info("Comparing file contents") remote_content = base64.b64encode(ftmp.read()) self.assertEq...
context): "usage: latest" self._init_source() if not utils.wait4dc("transition", not options.batch): return False self._set_source("live") crm_report().refresh_source() f = self._get_pe_byidx(-1) if not f: return False crm_report()...
ile for index %d not found" % (idx+1)) return None
return l[idx] def _get_pe_bynum(self, n): l = crm_report().pelist([n]) if len(l) == 0: common_err("PE file %d not found" % n) return None elif len(l) > 1: common_err("PE file %d ambiguous" % n) return None return l[0] def _get_pe...
nd seat['price'] and seat['sku']: price = Decimal(seat.get('price')) return price, seat.get('sku') return None, None def get_unenrolled_courses(courses, user_enrollments): """ Given a list of courses and a list of user enrollments, return the courses in which the user is n...
user, dashboard_enrollment,
user_enrollments) for dashboard_enrollment in dashboard_enrollments } return course_info # TODO: clean up as part of REVEM-199 (END) def get_experiment_user_metadata_context(course, user): """ Return a context dictionary with the keys used by the user_metadata.html. """ enrollm...
#-*- coding: utf-8 -*- import urllib2 import json import CommonFunctions common = CommonFunctions from xml.dom import minidom from resources.lib import utils from resources.lib import globalvar title=['ARTE'] img=['arte'] readyForUse=True def fix_text(text): return text.replace('&amp;','&').encode('utf-...
video_id=tmpTab[0][28:28+10] + "_PLUS7-F" else: start=tmpTab[0].find("%2Fplayer%2FF%2F") end=tmpTab[0].find("%2F", start+16) video_id=tmpTab[0][start+16:end] if video_id.find("EXTRAIT")>0 : ...
picTab=common.parseDOM(url[i], "video:thumbnail_loc") if len(picTab)>0: image_url=picTab[0] infoLabels={ "Title": name,"Plot":desc,"Aired":date,"Duration": duration, "Year":date[:4]} if not(globalvar.ADDON.getSetting('arteFull')=='true' and videoTag!='ARTE+7...
"""Test cases for the switcher_kis component.""" from datetime import timedelta from typing import TYPE_CHECKING, Any, Generator from pytest import raises from homeassistant.components.switcher_kis import ( CONF_AUTO_OFF, DATA_DEVICE, DOMAIN, SERVICE_SET_AUTO_OFF_NAME, SERVICE_SET_AUTO_OFF_SCHEMA...
hass, DOMAIN, MANDATORY_CONFIGURATION) await hass.async_block_till_done() device = hass.data[DOMAIN].get(DATA_DEVICE) assert device.device_id == DUMMY_DEVICE_ID
assert device.ip_addr == DUMMY_IP_ADDRESS assert device.mac_addr == DUMMY_MAC_ADDRESS assert device.name == DUMMY_DEVICE_NAME assert device.state == DUMMY_DEVICE_STATE assert device.remaining_time == DUMMY_REMAINING_TIME assert device.auto_off_set == DUMMY_AUTO_OFF_SET assert device.power_con...
#
!/usr/bin/env python from setuptools import setup, find_packages setup( name='bloom', version='0.4.4', packages=find_packages(exclude=['test']), package_data={ 'bloom.generators.debian': [ 'bloom/generators/debian/templates/*', 'bloom/generators/debian/templates/so
urce/*' ] }, include_package_data=True, install_requires=[ 'argparse', 'catkin-pkg >= 0.1.14', 'distribute', 'empy', 'python-dateutil', 'PyYAML', 'rosdep >= 0.10.3', 'rosdistro >= 0.2.12', 'vcstools >= 0.1.22', ], author...
#!/usr/bin/env python # Copyright (c) 2009 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # TODO: remove this script when GYP has for loops from __future__ import print_function import sys import optparse def main(argv...
default=False, help='map "en-US" to "en" and "-" to "_" in locales') (options, arglist) = parser.parse_args(argv) if len(arglist) < 3: print('ERROR: need string and list of locales') return 1 str_template = arglist[1] locales = arglist[2:] results = [] for locale in locales:...
bug.com/19165, http://crbug.com/25578). if options.dash_to_underscore: if locale == 'en-US': locale = 'en' locale = locale.replace('-', '_') results.append(str_template.replace('ZZLOCALE', locale)) # Quote each element so filename spaces don't mess up GYP's attempt to parse # it into a ...
############################################################################### # # Copyright 2010 Locomatix, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.or...
port search_region from query_search_region import query_search_region from search_nearby import search_nearby from query_search_nearby import query_search_nearby from get_location_history import get_location_history from query_location_history import query_location_history from get_space_activity import get_space_acti...
y from get_histogram import get_histogram from query_histogram import query_histogram
real tarfile module try to open the fake paths. """ config = PluginCallConfiguration({}, {constants.CONFIG_INSTALL_PATH: self.puppet_dir}) report = self.distributor.publish_repo(self.repo, self.conduit, config)
self.assertFalse(report.success_flag) self.assertTrue(isinstance(report.summary, basestring)) self.assertEqual(len(report.details['errors']), 2) self.assertTrue(report.details['errors'][0][0] in [self.uk1, self.uk2]) self.assertTrue(report.details['errors'][1][0] in [self.uk1, self.uk2...
unit_keys']), 0) @mock.patch('tarfile.open', autospec=True) @mock.patch.object(installdistributor.PuppetModuleInstallDistributor, '_check_for_unsafe_archive_paths', return_value=None) @mock.patch.object(installdistributor.PuppetModuleInstallDistributor, ...
"""Redo the `...` (representation) but with limits on most sizes.""" __all__ = ["Repr","repr"] class Repr: def __init__(self): self.maxlevel = 6 self.maxtuple = 6 self.maxlist = 6 self.maxdict = 4 self.maxstring = 30 self.maxlong = 40 self.maxother = 20 ...
f.maxstring: i = max(0, (self.maxstring-3)//2) j = max(0, self
.maxstring-3-i) s = s[:i] + '...' + s[len(s)-j:] return s aRepr = Repr() repr = aRepr.repr
://www1.skysports.com/watch/video/sports/football/teams/liverpool',176,art+'/skysports.png') main.addDir('Manchester City','http://www1.skysports.com/watch/video/sports/football/teams/manchester-city',176,art+'/skysports.png') main.addDir('Manchester United','http://www1.skysports.com/wa...
ers','http://www1.skysports.com/watch/video/sports/football/teams/bolton-wanderers',176,art+'/skysports.png')
main.addDir('Brighton','http://www1.skysports.com/watch/video/sports/football/teams/brighton',176,art+'/skysports.png') main.addDir('Bristol City','http://www1.skysports.com/watch/video/sports/football/teams/bristol-city',176,art+'/skysports.png') main.addDir('Burnley','http://www...
ame=u'Alice', age=1)] >>> from pyspark.sql import Row >>> Person = Row('name', 'age') >>> person = rdd.map(lambda r: Person(*r)) >>> df2 = sqlContext.createDataFrame(person) >>> df2.collect() [Row(name=u'Alice', age=1)] >>> from pyspark.sql.types import * ...
aches the specified table in-memory.""" self._ssql_ctx.cacheTable(tableName) @since(1.0) def uncacheTable(self, tableName): """Removes the specified table from the in-memory cache.""" self._ssql_ctx.uncacheTable(tableNa
me) @since(1.3) def clearCache(self): """Removes all cached tables from the in-memory cache. """ self._ssql_ctx.clearCache() @property @since(1.4) def read(self): """ Returns a :class:`DataFrameReader` that can be used to read data in as a :class:`DataFrame`...
# Copyright 2011 Google Inc. All Rights Reserved. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # unless required by applicable law or agr...
b."""
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals __author__ = 'watson@google.com (Tony Watson)' from string import Template from lib import iptables class Error(Exception): pass class Term(iptables.Term): """Ge...
# Copyright 2013 NEC Corporation. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required...
utils.Element("aggregate", name=name) resp, body = self.post('os-aggregates', str(xml_utils.Document(post_body))) aggregate = self._format_aggregate(etree.fromstring(body)) return resp, aggregate def update_aggregate(self, aggregate_id, name, availability_zone...
ity_zone is not None: put_body = xml_utils.Element("aggregate", name=name, availability_zone=availability_zone) else: put_body = xml_utils.Element("aggregate", name=name) resp, body = self.put('os-aggregates/%s' % str(aggregate_id), ...
"""luigi target for writing data into an HP Vertica database""" import logging import luigi logger = logging.getLogger('luigi-interface') # pylint: disable-msg=C0103 try: import vertica_python except ImportError: logger.warning("Attempted to load Vertica interface tools without the vertica_python package; w...
221 if connection is None: connection = self.connect() connection.autocommit = True cursor = connection.cursor()
try: cursor.execute("""SELECT 1 FROM {marker_schema}.{marker_table} WHERE update_id = %s LIMIT 1""".format(marker_schema=self.marker_schema, marker_table=self.marker_table), (self.update_id,) ) row = cursor.fe...
from django import forms from django.contrib.auth.forms import AuthenticationForm, PasswordChangeForm from crispy_forms.bootstrap import FormActions, AppendedText, StrictButton, InlineField from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Submit, Button, Field, Hidden, HTML, Div clas...
.helper.layout = Layout( 'username', Field('password'), FormActions(Submit('login', 'Login', css_class='btn btn_success')), ) class MyPasswordChangeForm(PasswordChangeForm): def __init__(self, *args, **kwargs): s
uper(MyPasswordChangeForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'form-horizontal' self.helper.form_method = 'post' self.helper.form_action = '' self.helper.label_class = 'col-lg-3' self.helper.field_class = 'col-lg-6' self.helper.layout = Layout( 'old_pass...
""" WSGI config for PythonAnywhere test project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_AP...
oduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks # if running multiple s...
n process, or use # os.environ["DJANGO_SETTINGS_MODULE"] = "config.settings.production" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.production") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # ...
interface = {} mode = 'unknown' try: body = run_commands(module, [command])[0] except IndexError: return None if intf_type in ['ethernet', 'portchannel']: interface_table = body['TABLE_interface']['ROW_interface'] mode = str(interface_table.get('eth_mode', 'layer3')) ...
version 1' commands.insert(0, command) commands.insert(0, 'interface {0}'.format(interface)) if comman
ds: if not commands[0].startswith('interface'): commands.insert(0, 'interface {0}'.format(interface)) return commands def is_default(interface, module): command = 'show run interface {0}'.format(interface) try: body = run_commands(module, [command], check_rc=False)[0] ...
from elasticsearch import helpers from c2corg_api.scripts.migration.batch import Batch from elasticsearch.helpers import BulkIndexError import logging log = logging.getLogger(__name__) class ElasticBatch(Batch): """A batch implementation to do bulk inserts for ElasticSearch. Example usage: batch =...
rn len(self.actions) > self.batch_size def flush(self): if self.actions: try: helpers.bulk(self.client, self.actions) except BulkIndexError: # when trying to delete a document that does not exist, an # error is raised, and other docume...
log.warning( 'error sending bulk update to ElasticSearch', exc_info=True) self.actions = []
from importlib import import_module from django.apps import A
ppConfig as BaseAppConfig class AppConfig(BaseAppConfig): name = "ge
stioneide" def ready(self): import_module("gestioneide.receivers")
from timeit import timeit import pytest from cfme import test_requirements from cfme.base.ui import navigate_to from cfme.services.myservice import MyService from cfme.tests.test_db_migrate import download_and_migrate_db from cfme.utils.conf import cfme_data @pytest
.fixture def appliance_with_performance_db(temp_appliance_extended_db): app = temp_appliance_extended_db try: db_backups = cfme_data['db_backups'] performance_db = db_backups['performance_510'] except KeyError as e: pytest.skip(f"Couldn't find the performance DB in the cfme_data: {e}...
rate_db(app, performance_db.url) yield app @test_requirements.service @pytest.mark.meta(automates=[1688937, 1686433]) def test_services_performance(appliance_with_performance_db): """ Polarion: assignee: jhenner initialEstimate: 1/4h casecomponent: Services Bugzilla: 1...
import pandas as pd class Status: Instance = None @classmethod def add(cls, message, red = False, verbosity = 1): cls.get().add_message(message, red, verbosity) @classmethod def initialize_status(cls, status_method, verbosity = 1): # Note: verbosity must be pa...
erbosity: if isinstance(message, pd.DataFrame) or isinstance(message, pd.core.frame
.DataFrame): text = str(message.head()) else: text = str(message) lines = text.split("\n") for line in lines: self.status_method(line, red) def status_method(self, message, red): print message
############################################################################## # # OSIS
stands for Open Student Information System. It's an application # designed to manage the core business of higher education institutions, # such as universities, faculties, institutes and professional schools. # The core business involves the administration of students, teachers, # courses, programs and so o...
Copyright (C) 2015-2018 Université catholique de Louvain (http://www.uclouvain.be) # # 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...
fr
om server import app app.run()
"""An event loop. This event loop should handle both asynchronous App Engine RPC objects (specifically urlfetch, memcache and datastore RPC objects) and arbitrary callback functions with an optional time delay. Normally, event loops are singleton objects, though there is no enforcement of this requirement. The API h...
*args, **kwds) # See add_idle() for the meaning of the callback return value. if res is not None: if res: self.inactive = 0 else: self.inactive += 1 self.idlers.append(idler) else:
logging_debug('idler %s removed', callback.__name__) return True def run0(self): """Run one item (a callback or an RPC wait_any). Returns: A time to sleep if something happened (may be 0); None if all queues are empty. """ if self.current: self.inactive = 0 callback, ar...
# See http://www.python.org/dev/peps/pep-0386/ for version
numbering, especially NormalizedVersion from distutils import version version =
version.LooseVersion('0.7.1-dev')
from stage import * import os use_gpu = os.environ.get('GNUMPY_USE_GPU', 'yes') == 'yes' if use_gpu: import gnumpy as gpu import gnumpy as gnp class Map(Stage): def __init__(self, outputDim, activeFn, inputNames=None, initRange...
initType='zeroMean', learningRate=0.0, learningRateAnnealConst=0.0, momentum=0.0, deltaMomentum=0.0,
weightClip=0.0, gradientClip=0.0, weightRegConst=0.0, outputdEdX=True, defaultValue=0.0, gpu=use_gpu, name=None): Stage.__init__(self, name=name, inputNames=inpu...
ok=None): """ The standard query interface. TODO: rename use_cache to use_qcache Checks a big cache for qaid2_cm. If cache miss, tries to load each cm individually. On an individual cache miss, it preforms the query. Args: ibs (ibeis.IBEISController) : ibeis control object q...
bs) # Try loading as many cached results as possible qaid2_cm_hit = {} external_qaids = qreq_.qaids fpath_list = qreq_.get_chipmatch_fpaths(external_qaids) exists_flags = [exists(fpath) for fpath in fpath_list] qaids_hit = ut.compress(external_qaids, exists_flags) ...
fpath_iter = ut.ProgressIter( fpaths_hit, nTotal=len(fpaths_hit), enabled=len(fpaths_hit) > 1, lbl='loading cache hits', adjust=True, freq=1) try: cm_hit_list = [ chip_match.ChipMatch.load_from_fpath(fpath, verbose=False) for fpath in fpath_it...
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-05-12 11:51 from __future__ import unicode_literals from django.db import migrations class Migration(mig
rations.Migration): dependencies = [ ('ossuo', '0021_merge'), ('ossuo', '0022_signupformpage_signupformpagebullet_signupformpagelo
go_signupformpagequote_signupformpageresponse'), ] operations = [ ]
ors(self, initiator_group_type, host_os_type, initiator_list): """Creates igroup and adds initiators.""" igroup_name = na_utils.OPENSTACK_PREFIX + six.text_type(uuid.uuid4()) self.zapi_client.create_igroup(igroup_name, initiator_group_type, ...
lumeBackendAPIException(data=msg % (seg[-1])) else: if st_nw_mv is None: self.zapi_client.move_lun(tmp_path, path) msg = _("Failure moving new cloned LUN to %s.") rai
se exception.VolumeBackendAPIException( data=msg % (seg[-1])) elif st_del_old is None: LOG.error(_LE("Failure deleting staged tmp LUN %s."), tmp_lun) else: LOG.error(_LE("Unknown exception in" ...
from datetime import datetime # pokemon lottery global_lotto_last_run = datetime(1969, 12, 31, 23, 59, 59, 999999) lotto_new_run = None print_speed_base = 0.03 # delay between printed characters """ Graphics Notes: The screen is 15x11 squares in dimension. Each square is 16x16 pixels. Total screen is 240x176. Sinc...
fly away Trainer works is because enemy trainers face south for one frame before turning back and starting the fight sequence. Obviously, the trick does not work with trainers that are already facing south. Three Steps: After a battle, wild or T
rainer, a wild battle cannot be triggered until the third step from their original location. """
"""Support for ESPHome binary sensors.""" import logging from typing import TYPE_CHECKING, Optional from homeassistant.components.binary_sensor import BinarySensorDevice from . import EsphomeEntity, platform_async_setup_entry if TYPE_CHECKING: # pylint: disable=unused-import from aioesphomeapi import BinaryS...
ntry, async_add_entities): """Set up ESPHome binary sensors based on a config entry.""" # pylint: disable=redefined-outer-name from aioesphomeapi import BinarySensorInfo, BinarySensorState # noqa
await platform_async_setup_entry( hass, entry, async_add_entities, component_key='binary_sensor', info_type=BinarySensorInfo, entity_type=EsphomeBinarySensor, state_type=BinarySensorState ) class EsphomeBinarySensor(EsphomeEntity, BinarySensorDevice): """A binary sensor imp...
# -*- coding: utf-8 -*- import json import pytest from keyard_client import KeyardClient, testutils @pytest.mark.skipif(not testutils.keyard_is_available(), reason="keyard is missing") class TestKeyardClient(object): def setup_method(self, method): self.client = KeyardClient('http://127.0.0.1:8000')
def test_re
gister(self): response = self.client.register('app', '0.1', 'localhost:8002') assert response is True def test_health_check(self): response = self.client.health_check('app', '0.1', 'localhost:8002') assert response is True def test_unregister(self): response = self.clie...
# -*- mode: python; fill-column: 100; comment-column: 100; -*- import unittest import sys import os sys.path.append( os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))) import base_test class ForwardTest(base_test.WebDriverB
aseTest): # Get a static page that must be the same upon refresh def test_forward(self): self.driver.get( self.webserver.where_is('navigat
ion/res/forwardStart.html')) self.driver.get( self.webserver.where_is('navigation/res/forwardNext.html')) nextbody = self.driver.find_element_by_css("body").get_text() self.driver.go_back() currbody = self.driver.find_element_by_css("body").get_text() self.assertNotEq...
import os from cpenv import api, paths from cpenv.cli import core from cpenv.module import parse_module_path class Create(core.CLI): '''Create a new Module.''' def setup_parser(self, parser): parser.add_argument( 'where', help='Path to new module', ) def run(self...
core.echo() core.echo(' ' + module.path) core.echo() core.echo('Steps you might take before publishing...') core.echo() core.echo(' - Include binaries your module depends on') core.echo(' - Edit the module.yml file') core.echo(' - Add variables to th...
post_activate') core.echo()
limit: str = '', season_id: Optional[Union[str, int]] = None) -> Sequence[Person]: person_query = query.person_query() season_join = query.season_join() if season_id else '' season_query = query.season_query(season_id, 'season.id') sql = f""" SELECT p.id, ...
iscord_id, person_id]) def is_allowed_to_retire(deck_id: Optional[int], discord_id: Optional[int]) -> bool: if not deck_id: return False if not discord_id: return True person = maybe_load_person_by_discord_id(discord_id) if person is None: return True return any(int(
deck_id) == deck.id for deck in person.decks) def get_or_insert_person_id(mtgo_username: Optional[str], tappedout_username: Optional[str], mtggoldfish_username: Optional[str]) -> int: sql = 'SELECT id FROM person WHERE LOWER(mtgo_username) = LOWER(%s) OR LOWER(tappedout_username) = LOWER(%s) OR LOWER(mtggoldfish_u...
#!/usr/bin/python # (c) 2018 Jim Hawkins. MIT licensed, see https://opensource.org/licenses/MIT # Part of Blender Driver, see https://github.com/sjjhsjjh/blender-driver """Python module for Blender Driver demonstration application. Abstract base class for demonstration applications. This module can only be used from ...
ion module ', __name__, '.'))) class Application(blender_driver.application.thread.Application): _instructions = "Press ESC to crash BGE, or any other key to terminate." _bannerName = 'banner' _bannerObject = No
ne @property def bannerObject(self): return self._bannerObject # Overriden. def data_initialise(self): # # Do common initialisation for subclasses. self._bannerObject = self.data_add_banner() self.dontDeletes.append(self._bannerName) # # ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.Create...
fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('activation_key', models.CharField(max_length=40, null=True, blank=True)), ('key_expires', models.DateTimeField(null=True, blank=True)), ('user',...
n the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this progra...
e=8, debris_min=6, debris_max=20, draw_planet=False, name=""): self.p2 = is_player2_present self.p1_ai = is_player1_ai
self.p2_ai = is_player2_ai self.p1_team = player1_team self.p2_team = player2_team mingreen = int(self.p1_team == "Green") + int(self.p2_team == "Green" and self.p2) minred = int(self.p1_team == "Red") + int(self.p2_team == "Red" and self.p2) self.green = max(ming...
# Copyright 2015 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in complian
ce with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIO
NS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # class ImageBuilderException(Exception): pass class ImageRateLimitedException(Exception): """Rate Limited request""" class ImageSpecificationException(Exce...
sig) async def terminate(self, force=False): '''This forces a child process to terminate. It starts nicely with SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This returns True if the child was terminated. This returns False if the child could not be terminated. ''' ...
nt'
: websocket.terminal.kill() # Immediately call the pty reader to process # the eof and free up space self.pty_read(websocket.terminal.ptyproc.fd) return websocket.terminal.killpg(signal.SIGHUP) class NamedTermManager(TermManag...
from django.utils.encoding import smart_unicode def ssn_check_digit(value): "Calculate Italian social security number check digit." ssn_even_chars = { '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, ...
V': 10, 'W': 22, 'X': 25, 'Y': 24, 'Z': 23 } # Chars from 'A' to 'Z' ssn_check_digits = [chr(x) for x in range(65, 91)] ssn = val
ue.upper() total = 0 for i in range(0, 15): try: if i % 2 == 0: total += ssn_odd_chars[ssn[i]] else: total += ssn_even_chars[ssn[i]] except KeyError: msg = "Character '%(char)s' is not allowed." % {'char': ssn[i]} ra...
print "You enter a dark room with two doors. Do you go through door #1 or door #2?" door = raw_input("> ") if door == "1": print "There`s a giant bear here eating a chees cake. What do you do?" print "1. Take the cake." print "2. Scream at the bear." bear = raw_input("> ") if bear == "1": print "The bear e...
ood job!" else: print "The insanity rots your eyes into a pool of muck. G
ood job!" else: print "You stumble around and fall on a knife and die. Good job!"
# Copyright 2013 Virantha Ekanayake All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
tgt_folder = self._get_matching_folder(filename) tgt_file = self.filer.move_to_matching_folder(filename, tgt_folder) return tgt_file if __name__ == '__main__': p = PyPdfFiler(PyFilerDirs()) for page_text in p.iter_pdf_page
_text("scan_ocr.pdf"): print (page_text)
# -*- coding: utf-8 -*- # Copyright (c) 2018 Ericsson AB # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
self): # Can always write after init, meaning changed is no longer None return self._changed is not None def write(self, value): def error(e): _log.warning("Error during write: {}".format(e)) done() # Call done to wake scheduler, not sure this is a good idea ...
e # Let can_read know there may be something new to read self.scheduler_wakeup() self._pushed_values += len(value) try: value = json.dumps(value) # Convert to string for sqlite except TypeError: _log.error("Value is not json serializable") else: ...
"""Treadmill app configurator daemon, subscribes to eventmgr events. """ import click from .. import appcfgmgr def init(): """Top level command handler.""" @click.command() @click.option('--approot', type=click.Path(exists=True), envvar='TREADMILL_APPROOT', required=True) def top(...
"Starts appcfgmgr process."""
mgr = appcfgmgr.AppCfgMgr(root=approot) mgr.run() return top
"""Gets the specified peering for the express route circuit. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param circuit_name: The name of the express route circuit. :type circuit_name: str :param peering_name: The name of the pee...
in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: deser
ialized = self._deserialize('ExpressRouteCircuitPeering', pipeline_response) if response.status_code == 201: deserialized = self._deserialize('ExpressRouteCircuitPeering', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized ...
#!/usr/bin/env python import time import json import random import re from bottle import route, hook, response, run, static_file @route('/') def index(): return static_file('index.html', root = '.') @route('/maptweets.
js') def index_css(): return static_file('maptweets.js', root = '.') @rou
te('/cross.jpg') def index_css(): return static_file('cross.jpg', root = '.') @route('/light.png') def index_css(): return static_file('light.png', root = '.') @route('/event.png') def index_css(): return static_file('event.png', root = '.') run(host = '0.0.0.0', port = 80, server = 'tornado', debug = Tr...
from __future__ import print_function, division from sympy.core.numbers import nan from .function import Function class Mod(Function): """Represents a modulo operation on symbolic expressions. Receives two arguments, dividend p and divisor q. The convention used is the same as Python's: the remainder a...
teger and q == 1): return S.Zero if q.is_Nu
mber: if p.is_Number: return (p % q) if q == 2: if p.is_even: return S.Zero elif p.is_odd: return S.One # by ratio r = p/q try: ...
#!/usr/bin/env python # # Copyright 2013, Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can # be found in the LICENSE file. """Re-runs initial_sharding.py with a varbinary keyspace_id.""" from vtdb import keyrange_const
ants import base_sharding import initial_sharding import utils # this test is just re-running an entire initial_sharding.py with a
# varbinary keyspace_id if __name__ == '__main__': base_sharding.keyspace_id_type = keyrange_constants.KIT_BYTES utils.main(initial_sharding)
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under th...
ngine) as session: try: workflow: Workflow = session.query(Workflow).filte
r_by( id=self._workflow_id).one() # TODO: This is a hack!!! Templatelly use this method # cc @hangweiqiang: Transaction State Refactor state = workflow.get_state_for_frontend() if state in ('COMPLETED', 'FAILED', 'READY', 'STOPPED', 'NE...
"""Helper stuff for things""" import gc gc.disable() print 'Disabled
GC' def timeit(func, iter = 1000, *args, **kwargs): """timeit(func, iter = 1000 *args, **kwargs) -> elapsed time calls func iter times with args and kwargs, returns time elapsed """ import time r = range(iter) t = time.time(
) for i in r: func(*args, **kwargs) return time.time() - t
class Excel
(object): def __init__(self, H, W): """
:type H: int :type W: str """ self.table = [[{'v': 0, 'sum': None} for _ in range(ord(W) - 64)] for __ in range(H)] def set(self, r, c, v): """ :type r: int :type c: str :type v: int :rtype: void """ self.table[r - 1][ord(c) - 65] ...
# -*- coding: utf-8 -*- # Authors: Y. Jia <ytjia.zju@gmail.com> """ Given a collection of intervals, merge all overlapping intervals. https://leetcode.com/problems/merge-intervals/description/ """ # Definition for an interval. class Interval(object): def __init__(self, s=0, e=0): self.start = s ...
terval] :rtype: List[Interval] """ lens = len(intervals) if lens <=
1: return intervals merged_intervals = list() intervals.sort(key=lambda interval: interval.start) i = 0 j = i + 1 while j < lens: if intervals[i].end >= intervals[j].start: intervals[i].end = max(intervals[i].end, intervals[j].end) ...
client of the current session does not support one or more Profiles that are necessary for the subscription."'), 0x80BF0000: ('BadStateNotActive', '"The sub-state machine is not currently active."'), 0x81150000: ('BadAlreadyExists', '"An equivalent rule already exists."'), 0x807D0000: ('BadTcpServerTooBusy...
lly overwritten."'), 0x40920000: ('UncertainInitialValue', '"The value is an initial value for a variable that normally receives its value from another variable."'), 0x40930000: ('UncertainSen
sorNotAccurate', '"The value is at one of the sensor limits."'), 0x40940000: ('UncertainEngineeringUnitsExceeded', '"The value is outside of the range of values defined for this parameter."'), 0x40950000: ('UncertainSubNormal', '"The value is derived from multiple sources and has less than the required number o...
# Copyright Kevin Deldycke <kevin@deldycke.com> and contributors. # All Rights Reserved. # # 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 2 # of the License, or (at your option) ...
MA 02111-1307, USA. import pytest from click_extra.tests.conftest import destructive from ..pool import ALL_MANAGER_IDS from .test_cli import CLISubCommandTests @pytest.fixture def subcmd(): return "install", "arrow" class TestInstall(CLISubCommandTests): strict_selection_match = False """ Install ...
ager until it find one providing the package we seek to install, after which the process stop. This mean not all managers will be called, so we allow the CLI output checks to partially match. """ def test_no_package_id(self, invoke): result = invoke("install") assert result.exit_code ==...
tring. No metadata or positional metadata will be included. See Also -------- sequence Examples -------- >>> from skbio import Sequence >>> s = Sequence('GGUCGUAAAGGA', metadata={'id':'hello'}) >>> str(s) 'GGUCGUAAAGGA' """ ...
it is an understood type whose representation is too long, just the type will be displayed * positional metadata: column names and column dtypes will be displayed in the order they appear in the positional metadata ``pd.DataFrame``. Column names (i.e., keys) follow the
same display rules as metadata keys * sequence stats (e.g., length) * up to five lines of chunked sequence data. Each line of chunked sequence data displays the current position in the sequence Returns ------- str String representation of the bio...
from JumpSc
ale import j import JumpScale.baselib.redis import JumpScale.grid.jumpscripts class CmdRouter(object): def __init__(self, path=None): j.core.jumpscripts.load(path) def route(self,organization,actor,name,**args):
pass
im
port pandas as pd adv = pd.read_csv('Advertising.csv') tv_budget_x = adv.TV.to
list() print(tv_budget_x)
from .actions import * from .ac
tions_re impor
t * from .expectations import *
# Remove event listener if no forwarding targets present self.hass.bus.remove_listener(ha.MATCH_ALL, self._event_listener) return did_remove def _event_listener(self, event): """Listen and forward all events.""" with self._l...
I.""" set_state(self._api, entity_id, new_state, attributes) def mirror(self): """Discard current data and mirrors the remote state machine.""" self._states = {state.entity_id: state for state in get_states(self._api)} def _state_cha
nged_listener(self, event): """Listen for state changed events and applies them.""" if event.data['new_state'] is None: self._states.pop(event.data['entity_id'], None) else: self._states[event.data['entity_id']] = event.data['new_state'] class JSONEncoder(json.JSONEncod...
#!/usr/bin/env python #-*- coding:utf-8 -*- from miasm2.expression.expression import ExprId from miasm2.core.cpu import gen_reg, gen_regs gen_reg('PC', globals()) gen_reg('PC_FETCH', globals()) gen_reg('R_LO', globals()) gen_reg('R_HI', globals()) exception_flags = ExprId('exception_flags', 32) PC_init = ExprId("...
in xrange(0x100)] cpr0_str[0] = "INDEX" cpr0_str[16] = "ENTRYLO0" cpr0_str[24] = "ENTRYLO1" cpr0_str[40] = "PAGEMASK" cpr0_str[72] = "COUNT" cpr0_str[80] = "ENTRYHI" cpr0_str[104] = "CAUSE" cpr0_str[112] = "EPC" cpr0_str[128] = "CONFIG" cpr0_str[152] = "WAT
CHHI" regs_cpr0_expr, regs_cpr0_init, regs_cpr0_info = gen_regs(cpr0_str, globals()) gpregs_expr, gpregs_init, gpregs = gen_regs(regs32_str, globals()) regs_flt_expr, regs_flt_init, fltregs = gen_regs(regs_flt_str, globals(), sz=64) regs_fcc_expr, regs_fcc_init, fccregs = gen_regs(regs_fcc_str, globals()) all_regs_...
ements for a dataset. Parameters ---------- dataset : sima.ImagingDataset Returns ------- displacements : list of ndarray of int """ shifts = self._estimate(dataset) assert np.any(np.all(x is not np.ma.masked for x in shift) ...
in.from_iterable(shifts)) shifts = self._make_nonnegative(shifts) assert np.any(np.all(x is not np.ma.masked for x in shift) for shift in it.chain.
from_iterable(shifts)) assert np.all( np.all(x is np.ma.masked for x in shift) or not np.any(x is np.ma.masked for x in shift) for shift in it.chain.from_iterable(shifts)) return shifts def correct(self, dataset, savedir, channel_names=None, info=None, ...
# Mantid Repository : https://github.com/mantidproject/mantid # # Copyright &copy; 2018 ISIS Rutherford Appleton Laboratory UKRI, # NScD Oak Ridge National Laboratory, European Spallation Source # & Institut Laue - Langevin # SPDX - License - Identifier: GPL - 3.0 + import sys from Muon.GUI.Common.muon_load_dat...
t FileFinder import copy if sys.version_info.major < 2: from unittest import mock else: import mock class MuonDataContextTest(unittest.TestCase): def setUp(self): self.loaded_data = MuonLoadData() self.context = MuonDataContext(self.loaded_data) self.frequency_context = Frequenc...
ck.MagicMock() self.context.gui_variables_notifier.add_subscriber(self.gui_variable_observer) self.context.instrument = 'CHRONUS' self.gui_variable_observer = Observer() self.gui_variable_observer.update = mock.MagicMock() self.context.gui_variables_notifier.add_subscriber(self.g...
from distutils.core impo
rt setup setup(name='robotframework-wiremo
ck', packages=['WireMockLibrary'], package_dir={'': 'src'}, version='development', description='Robot framework library for WireMock', author='Timo Yrjola', author_email='timo.yrjola@gmail.com', classifiers=[])
PageToken = _messages.StringField(3) class ListInstancesResponse(_messages.Message): """Response message for BigtableInstanceAdmin.ListInstances. Fields: failedLocations: Locations from which Instance information could not be retrieved, due to an outage or some other transient condition. Instances ...
peration is completed, and either `error` or `response` is available. error: The error result of the operation in case of failure or cancellation. metadata: Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as cr...
rvices might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. name: The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should...
import os path = os.path.dirname(os.path.realpath(__file__)) sbmlFilePath = os.path.join(path, 'MODEL1006230013.xml') with open(sbm
lFilePath,'r') as f: sbmlString = f.read() def module_exists(module_name): try: __import__(module_name) except ImportError: return False else: return True if module_exists('libsbml'): import libsbml sbml = libsbml.readSBMLFromString(sbml
String)
from django.apps import AppConfig class TagsConfig(AppConfig):
name = "
hav.apps.tags"
################################################## # MODIFIED FROM ORIGINAL VERSION # # This file is not the same as in pypi. It includes a pull request to fix py3 # incompabilities that never ended up getting merged. ############################################################################### import os from ctypes...
if not result_p: break result = result_p.contents result.chip = self.chip result.parent = self yield result @property def label(self): # # TODO Maybe this is a memory leak! # return _get_label(byref(self.chip), by...
O Is the first always the correct one for all feature types? # return next(iter(self)).get_value() FEATURE_P = POINTER(Feature) class Bus(Structure): TYPE_ANY = -1 NR_ANY = -1 _fields_ = [ ('type', c_short), ('nr', c_short), ] def __str__(self): return ( ...
t__(converter, provider, py_type, attr=None): if attr is not None: throw(TypeError, 'Attribute %s has invalid type NoneType' % attr) Converter.__init__(converter, provider, py_type) def get_sql_type(converter, attr=None): assert False def get_fk_type(converter, sql_type): a...
rip: val = val.strip() max_len = converter.max_len val_len = len(val) if max_len and val_len > max_len: throw(ValueError, 'Value for attribute %s is
too long. Max length is %d, value length is %d' % (converter.attr, max_len, val_len)) return val def sql_type(converter): if converter.max_len: return 'VARCHAR(%d)' % converter.max_len return 'TEXT' class IntConverter(Converter): signed...
#!/usr/bin/python3 # Copyright (C) 2015 Bitquant Research Laboratories (Asia) Limited # Released under the Simplified BSD License import my_path import time import zmq.green as zmq import pprint import algobroker import msgpack class Dispatcher(algobroker.Broker): def __init__(self): algobroker.Broker._...
= self.socket(zmq.PUSH) self.web_sender.connect(algobroker.ports['data']['broker_web']) def process_data(self, data): if (data['cmd'] == "log"): self.war
ning(pprint.pformat(data)) elif (data['cmd'] == 'alert' and data['type'] == 'sms'): self.debug("sending sms") self.debug(pprint.pformat(data)) self.sms_sender.send(msgpack.packb(data)) elif (data['cmd'] == 'alert' and data['type'] == 'web')...
om worker.crawler.china_telecom_tool import login_unity class Crawler(BaseCrawler): """ kwargs 包含 'tel': str, 'pin_pwd': str, 'id_card': str, 'full_name': unicode, 'sms_code': str, 'captcha_code': str 錯誤等級 0: 成功 1: 帳號密碼錯誤 2: 認證碼錯誤 ...
in tel_info_res.text: self.info_res = tel_info_res.text return 0, "success" else: pass else: sel
f.log('crawler', "request_error", tel_info_res) return 9, "website_busy_error" def send_verify_request(self, **kwargs): """ 請求發送短信,或是下載圖片,或是同時發送請求 return status_key: str, 狀態碼金鑰,參考status_code level: int, 錯誤等級 message: unicode, 詳細的錯誤信息 ...
# -*- coding: utf-8 -*- import sys import os from os.path import dirname
# Set the directory for using the modules in the same project such as eshop. PROJECT_PATH = dirname(os.path.abspath(os.path.dirname(__file__))) ESHOP_PATH = os.path.jo
in(PROJECT_PATH, 'eshop/') sys.path.append(PROJECT_PATH)
# -*- coding: utf-8 -*- import re from channels import renumbertools from channelselector import get_thumb from core import httptools from core import scrapertools from core import servertools from core import tmdb from core.item import Item from platformcode import config, logger from channels import autoplay IDIO...
.data data1 = re.sub(r"\n|\r|\t|\s{2}|&nbsp;", "", data) data_vid = scrapertools.find_single_match(data1, '<div class="videos">(.+?)<\/div><div .+?>') # name = scrapertools.find_single_match(data,'<span>Titulo.+?<\/span>([^<]+)<br>') scrapedplot = scrapertools.find_single_match(data, '<br><span>Descrip...
ch(data, '<div class="caracteristicas"><img src="([^<]+)">') itemla = scrapertools.find_multiple_matches(data_vid, '<div class="serv">.+?-(.+?)-(.+?)<\/div><.+? src="(.+?)"') for server, quality, url in itemla: if "Calidad Alta" in quality: quality = quality.replace("Calidad Alta", "HQ") ...
from django.core.exceptions import ValidationError from django.db import IntegrityError, models, transaction from django.test import SimpleTestCase, TestCase from .models import BooleanModel, FksToBooleans, NullBooleanModel class BooleanFieldTests(TestCase): def _test_get_prep_value(self, f): self.assert...
hoices_blank(self): """ BooleanField with choices and defaults doesn't
generate a formfield with the blank option (#9640, #10549). """ choices = [(1, 'Si'), (2, 'No')] f = models.BooleanField(choices=choices, default=1, null=False) self.assertEqual(f.formfield().choices, choices) def test_return_type(self): b = BooleanModel.objects.cre...
# -*- coding: utf-8 -*- """Defines mixing class. You can use it for inherit from Class Base Views, it was developed by Timothée Peignier https://gist.github.com/cyberdelia/1231560 """ from django.contrib.auth.decorators import login_required from django.utils.cache import patch_response_headers from django.utils.deco...
ache_timeout def dispatch(self, *args, **kwargs): response = super(CacheControlMixin, self).dispatch(*args, **kwargs) patch_response_head
ers(response, self.get_cache_timeout()) return response class JitterCacheMixin(CacheControlMixin): cache_range = [40, 80] def get_cache_range(self): return self.cache_range def get_cache_timeout(self): return random.randint(*self.get_cache_range())
fset(dateString): # format in form of 2015-04-24T08:00:00-04:00 converted to UTC timestamp if dateString is None: return None try: sign = int(dateString[19:20] + '1') (hour, minute) = [int(s) for s in dateString[20:].split(':')] offset = sign * (hour * 60 * 60 + minute * 60...
= RMOSPlatform.ANDROID: librt = ctypes.CDLL
('libc.so', use_errno=True) log.info("Initialised Android monotonic clock") elif RMOSPlatform().AUTODETECTED == RMOSPlatform.OPENWRT: lib
############################################################################### # # Copyright (C) 2001-2014 Micronaet SRL (<http://www.micronaet.it>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the ...
'category': '', 'description': """ Add extra information for manage BOM as a work BO
M """, 'author': 'Micronaet S.r.l. - Nicola Riolini', 'website': 'http://www.micronaet.it', 'license': 'AGPL-3', 'depends': [ 'base', 'mrp', ], 'init_xml': [], 'demo': [], 'data': [ 'security/ir.model.access.csv', 'bom_views.xml', ...
""" WSGI config for opendai_lleida_web project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APP...
have the standard Django WSGI application here, but it also might make se
nse to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "admin_web.settings-...
fr
om .data_asset import DataAsset from .file_data_asset import FileDat
aAsset
import co
nnect_tests import string_utils_tes
ts
#!/usr/bin/env python # encoding:utf-8 """ @software: PyCharm @file: video_db.py @time: 2016/8/4 16:56 """ import sqlite3 class Create_DB():
def __init__(self): self.conn = sqlite3.connect('video.db') self.cn = self.conn.cursor() def create_table(self, table): # 创建表格 table == 创建表命令 self.cn.execute(table) def insert_db(self): # 插入数据 pass def select_db(self): # 查询数据
pass if __name__ == '__main__': pass
foo isn't good enough to write it. self.assertRegexpMatches(err_out.getvalue(), 'Traceback') self.assertRegexpMatches(err_out.getvalue(), r'import bad\)syntax') self.assertRegexpMatches(err_out.getvalue(), 'SyntaxError') def test_addpackage_import_bad_exec(self): # Issue 1064...
"error for file paths containing null characters") def test_addpackage_import_bad_pth_file(self): # Issue 5258 pth_dir, pth_fn = self.make_pth("abc\x00def\n") with captured_output("stderr") as err_out: sit
e.addpackage(pth_dir, pth_fn, set()) self.assertRegexpMatches(err_out.getvalue(), "line 1") self.assertRegexpMatches(err_out.getvalue(), re.escape(os.path.join(pth_dir, pth_fn))) # XXX: ditto previous XXX comment. self.assertRegexpMatches(err_out.getvalue(), 'Traceback')...
############################################################################## # # OSIS stands for Open Student Information System. It's an application # designed to manage the core business of higher education institutions, # such as universities, faculties, institutes and professional schools. # The core ...
at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # A copy of this license...
Public License - is available # at the root of the source code of this program. If not, # see http://www.gnu.org/licenses/. # ############################################################################## import factory.fuzzy from education_group.ddd.domain._campus import Campus class CampusFactory(factory.Fa...
from setuptools import setup def readme(): with open('README.md') as f: return f.read() ## test with python setup.py develop setup( name='ipyreload', packages=['ipyreload'], version= 1.2, description='ipython productivity tools', long_description=readme(), url="https:/...
om', license='MIT', z
ip_safe=False)
#!/usr/bin/python3 # -*- coding: utf-8 -*- # url_read.py file is part of slpkg. # Copyright 2014-2021 Dimitris Zlatanidis <d.zlatanidis@gmail.com> # All rights reserved. # Slpkg is a user-friendly package manager for Slackware installations # https://gitlab.com/dslackw/slpkg # Slpkg is free software: you can redis...
lib3.ProxyManager(self.meta.http_proxy) else: self.http
= urllib3.PoolManager() def reading(self): """Open url and read """ try: f = self.http.request('GET', self.link) return f.data.decode("utf-8", "ignore") except urllib3.exceptions.NewConnectionError: print(f"\n{self.red}Can't read the file '{self....
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ This script is based on chromium/chromium/master/tools/clang/scripts/update.py. It is used on Windows platforms to copy the co...
ort os import shutil import stat import sys # Path constants. (All of these should be absolute paths.) THIS_DIR = os.path.abspath(os.path.dirname(__file__)) LLVM_BUILD_DIR = os.path.abspath(os.path.join(THIS_D
IR, '..', '..', 'third_party', 'llvm-build', 'Release+Asserts')) def GetDiaDll(): """Get the location of msdia*.dll for the platform.""" # Bump after VC updates. DIA_DLL = { '2013': 'msdia120.dll', '2015': 'msdia140.dll', '2017': 'msdia140.dll', '20...
""" Views to support exchange of authentication credentials. The following are currently implemented: 1. AccessTokenExchangeView: 3rd party (social-auth) OAuth 2.0 access token -> 1st party (open-edx) OAuth 2.0 access token 2. LoginWithAccessTokenView: 1st party (open-edx) OAuth 2.0 access token -...
e, self).dispatch(*args, **kwargs) def get(self, request, _backend): # pylint: disable=arguments-differ """ Pass through GET requests without the _backend """ return super(Acces
sTokenExchangeBase, self).get(request) def post(self, request, _backend): # pylint: disable=arguments-differ """ Handle POST requests to get a first-party access token. """ form = AccessTokenExchangeForm(request=request, oauth2_adapter=self.oauth2_adapter, data=request.POST) # pyl...
import
android class SMSPoolMember: def __init__(self, query): self.droid = android.Android() self.query = str(query).lstrip().rstrip() def wifiConnected(self): none = "<unknown ssid>" return not self.droid.wifiGetConnectionInfo().result["ssid"] == none def dataConnected(self): ...
().result["cid"] > -1 def sendResponse(self): if self.query == "connection": return "pool:" + str(self.wifiConnected() or self.dataConnected()) else: return "pool: None"
import caffe import numpy as np import pdb class MyLossLayer(caffe.Layer): """Layer of Efficient Siamese loss function.""" def setup(self, bottom, top): self.margin = 10 print '*********************** SETTING UP' pass def forward(self, bottom, top):
"""The parameters here have the same meaning as data_layer""" self.Num = 0 batch = 1 level = 5 dis = 9 SepSize = batch*level self.dis = [] # for the first for k in r
ange(dis): for i in range(SepSize*k,SepSize*(k+1)-batch): for j in range(SepSize*k + int((i-SepSize*k)/batch+1)*batch,SepSize*(k+1)): self.dis.append(bottom[0].data[i]-bottom[0].data[j]) self.Num +=1 self.dis = np.asarray(self.dis) ...
#!/usr/bin/env python3 import sys if len(sys.argv) != 2: raise SystemExit('Incor
rect usage. Use: ' + sys.argv[0] + ' <image.img>') image_filename = sys.argv[1] content = '' with open(image_filename, 'rb') as f: content = bytearray(f.read()) bytes_to_append = 512 - len(content) % 512 for i in range(bytes_to_append): content.append(0) with open(image_filename, 'wb') as f: ...
tent) print('Successfully aligned to sector')