content
string
""" Template file used by the OPF Experiment Generator to generate the actual description.py file by replacing $XXXXXXXX tokens with desired values. This description.py file was generated by: '~/nupic/eng/lib/python2.6/site-packages/nupic/frameworks/opf/expGenerator/ExpGenerator.py' """ from nupic.frameworks.opf.expd...
from unittest import TestCase from test_utils import Mock, patch from os.path import normcase as nc from pybuilder.core import Project from pybuilder.errors import BuildFailedException from pybuilder.plugins.python.sonarqube_plugin import (SonarCommandBuilder, bu...
import json from collections import namedtuple from django.core.urlresolvers import reverse from django.contrib.auth.models import Group, User from rest_framework import serializers from hs_core.hydroshare import utils from hs_core import hydroshare from .utils import validate_json, validate_user, validate_group from ...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.network.netv...
#!/usr/bin/python -u import sys import libxml2 # Memory debug specific libxml2.debugMemory(1) # # Testing XML Node comparison and Node hash-value # doc = libxml2.parseDoc("""<root><foo/></root>""") root = doc.getRootElement() # Create two different objects which point to foo foonode1 = root.children foonode2 = root....
# -*- coding: utf-8 -*- """ Models used to implement SAML SSO support in third_party_auth (inlcuding Shibboleth support) """ from config_models.models import ConfigurationModel, cache from django.conf import settings from django.core.exceptions import ValidationError from django.db import models from django.utils impor...
import numpy as np from bokeh.layouts import row from bokeh.models import ColumnDataSource, CustomJS, Rect from bokeh.plotting import figure, output_file, show output_file('range_update_callback.html') N = 4000 x = np.random.random(size=N) * 100 y = np.random.random(size=N) * 100 radii = np.random.random(size=N) * ...
"""HTML utilities suitable for global use.""" from __future__ import unicode_literals import re import string try: from urllib.parse import quote, unquote, urlsplit, urlunsplit except ImportError: # Python 2 from urllib import quote, unquote from urlparse import urlsplit, urlunsplit from django.utils...
# -*- coding: utf-8 -*- """ jinja2.testsuite.ext ~~~~~~~~~~~~~~~~~~~~ Tests for the extensions. :copyright: (c) 2010 by the Jinja Team. :license: BSD, see LICENSE for more details. """ import re import unittest from jinja2.testsuite import JinjaTestCase from jinja2 import Environment, DictLoader...
# A solution to the British Informatics Olympiad 2011 Question 3 # Scores 24/24 from __future__ import print_function try: input = raw_input except: pass def number_with_n_digits(n): return 9**(n//2) def nth_with_n_digits(number_of_digits, n): if number_of_digits == 0: return "" if number_of_digits % 2 == 1: ...
# event_analyzing_sample.py: general event handler in python # # Current perf report is already very powerful with the annotation integrated, # and this script is not trying to be as powerful as perf report, but # providing end user/developer a flexible way to analyze the events other # than trace points. # # The 2 dat...
# -*- coding: utf-8 -*- # Django test settings for cms project. import os PROJECT_DIR = os.path.dirname(__file__) TEST_PROJ = 'pages.testproj' DEBUG = True USE_TZ = True ADMINS = ( # ('Your Name', '<EMAIL>'), ) CACHE_BACKEND = 'locmem:///' MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'dj...
"""Tests for tensorflow.ops.clip_ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf class ClipTest(tf.test.TestCase): # ClipByValue test def testClipByValue(self): with self.test_session(): x = tf.constant([-5.0...
import collections import os import polib from optparse import OptionParser parser = OptionParser() parser.add_option("-o", "--output", dest="output", help="Directory for localized output", default="../Shared/installer/nightly_localized.nsi") parser.add_option("-p", "--podir", dest="podir", ...
from django.conf.urls import include, url from rest_framework.routers import SimpleRouter from rest_framework_nested.routers import NestedSimpleRouter from olympia.bandwagon.views import CollectionAddonViewSet, CollectionViewSet from . import views accounts = SimpleRouter() accounts.register(r'account', views.Acco...
from django.contrib.syndication import views from django.core.exceptions import ObjectDoesNotExist import warnings # This is part of the deprecated API from django.contrib.syndication.views import FeedDoesNotExist, add_domain class Feed(views.Feed): """Provided for backwards compatibility.""" def __init__(sel...
"""Tests for tensorflow.python.framework.importer.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf from tensorflow.core.framework import types_pb2 from tensorflow.python.framework import dtypes from tensorflow.py...
DEPS = [ 'file', 'recipe_engine/path', 'recipe_engine/platform', 'recipe_engine/properties', 'recipe_engine/step', 'cipd', ] def RunSteps(api): # First, you need a cipd client. api.cipd.install_client('install cipd') api.cipd.install_client('install cipd', version='deadbeaf') assert api.cipd.get_ex...
from unittest import mock from airflow.providers.google.ads.transfers.ads_to_gcs import GoogleAdsToGcsOperator from tests.providers.google.ads.operators.test_ads import ( BUCKET, CLIENT_IDS, FIELDS_TO_EXTRACT, GCS_OBJ_PATH, IMPERSONATION_CHAIN, QUERY, api_version, gcp_conn_id, googl...
categories = ["move", "move_non_temporal", "move_mask"] microcode = ''' # 128 bit multimedia and scientific data transfer instructions ''' for category in categories: exec "import %s as cat" % category microcode += cat.microcode
""" An example of Multiclass to Binary Reduction with One Vs Rest, using Logistic Regression as the base classifier. Run with: bin/spark-submit examples/src/main/python/ml/one_vs_rest_example.py """ from __future__ import print_function # $example on$ from pyspark.ml.classification import LogisticRegression, OneVsRe...
"""Config flow for National Weather Service (NWS) integration.""" import logging import aiohttp from pynws import SimpleNWS import voluptuous as vol from homeassistant import config_entries, core, exceptions from homeassistant.const import CONF_API_KEY, CONF_LATITUDE, CONF_LONGITUDE from homeassistant.helpers import ...
""" Test the pulp.server.db.model.criteria module. """ import unittest from pulp.server import exceptions from pulp.server.db.model import criteria FIELDS = set(('sort', 'skip', 'limit', 'filters', 'fields')) class TestAsDict(unittest.TestCase): def test_empty(self): c = criteria.Criteria() re...
"""End to end test for Puppet funcionality :Requirement: Puppet :CaseAutomation: Automated :CaseLevel: Acceptance :CaseComponent: Puppet :TestType: Functional :CaseImportance: High :Upstream: No """ import pytest from robottelo.config import settings from robottelo.decorators import run_in_one_thread from robot...
{ 'name': 'Brazilian - Accounting', 'category': 'Localization/Account Charts', 'description': """ Base module for the Brazilian localization ========================================== This module consists in: - Generic Brazilian chart of accounts - Brazilian taxes such as: - IPI - ICMS ...
""" This checks that all files in the repository have correct filenames and permissions """ import os import re import sys from subprocess import check_output from typing import Optional, NoReturn CMD_ALL_FILES = "git ls-files -z --full-name" CMD_SOURCE_FILES = 'git ls-files -z --full-name -- "*.[cC][pP][pP]" "*.[hH]...
from __future__ import absolute_import, division, print_function import sys PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 # flake8: noqa if PY3: string_types = str, else: string_types = basestring, def with_metaclass(meta, *bases): """ Create a base class with a metaclass. """...
import unittest, sys from ctypes.test import need_symbol class SimpleTypesTestCase(unittest.TestCase): def setUp(self): import ctypes try: from _ctypes import set_conversion_mode except ImportError: pass else: self.prev_conv_mode = set_conversion...
from __future__ import unicode_literals from django.db import connection from django.test import TestCase from .models import A01, A02, B01, B02, C01, C02, Unmanaged2, Managed1 class SimpleTests(TestCase): def test_simple(self): """ The main test here is that the all the models can be created w...
""" SWF (Macromedia/Adobe Flash) file parser. Documentation: - Alexis' SWF Reference: http://www.m2osw.com/swf_alexref.html - http://www.half-serious.com/swf/format/ - http://www.anotherbigidea.com/javaswf/ - http://www.gnu.org/software/gnash/ Author: Victor Stinner Creation date: 29 october 2006 """ from li...
import hashlib from django.db import models from opencontext_py.apps.ldata.linkentities.models import LinkEntityGeneration # This class stores linked data annotations made on the data contributed to open context class LinkAnnotation(models.Model): # predicates indicating that a subject has an object that is a bro...
from tornado.web import * import tornado.ioloop import tornado.process import tornado.netutil import tornado.httpserver import os from . import place from . import office from . import memory as historial navigation = [ (r"/", place.CentralSquare), # (r"/classes/(.*).htm", ClassesPlace), This will be avalia...
# coding: utf-8 from __future__ import unicode_literals import re import socket from .common import InfoExtractor from ..compat import ( compat_etree_fromstring, compat_http_client, compat_urllib_error, compat_urllib_parse_unquote, compat_urllib_parse_unquote_plus, ) from ..utils import ( clea...
from __future__ import unicode_literals import frappe, json from frappe.model.document import Document from frappe import _ from frappe.utils import date_diff, add_days, flt class HotelRoomUnavailableError(frappe.ValidationError): pass class HotelRoomPricingNotSetError(frappe.ValidationError): pass class HotelRoomRes...
# Caltech SURF 2013 # FILE: grid.py # 07.17.13 ''' do stuff with grid diagrams to prepare for CFK^\infty ''' # winding matrix done by rows (consistent with gridlink) # TODO bottom row first??? # TODO only knots no links... from fractions import Fraction import itertools # list(itertools.permutations([1,2,3])) # TOD...
import os import stat import posixpath import re from mako import exceptions, util from mako.template import Template try: import threading except: import dummy_threading as threading class TemplateCollection(object): """Represent a collection of :class:`.Template` objects, identifiable via URI. ...
#!/usr/bin/env python import sys import os import argparse import json from netaddr import IPNetwork labtainer_dir = os.getenv('LABTAINER_DIR') if labtainer_dir is None: print('Must define LABTAINER_DIR environment variable') exit(1) sys.path.append(os.path.join(labtainer_dir, 'scripts', 'labtainer-student','bi...
import numpy as np from scipy import ndimage, misc from matplotlib import pyplot as plt import glob from MyViola import MyViolaClassifier from Svm import Svm import funcs def find_face(img, shape, mv): res_i = (0, 0) res_j = (0, 0) res_scl = 1 max_ = 0 scales = np.arange(.2, .35, .025) m, n = ...
"""Manifest structure used to store paths that should be included in a test run. The manifest is represented by a tree of IncludeManifest objects, the root representing the file and each subnode representing a subdirectory that should be included or excluded. """ import glob import os import urlparse from wptmanifest...
# Request finder import time from mediamonkey import MediaMonkey from what import WhatCD from whatdao import WhatDAO from whatconfig import WhatConfigParser from whatparser import Parser class RequestFinder(): def dump_page(self, filename, page): f = open(filename, 'w') f.write(page) f.close() def find_req...
from test import CollectorTestCase from test import get_collector_config from mock import call, Mock, patch from unittest import TestCase from diamond.collector import Collector from portstat import get_port_stats, PortStatCollector class PortStatCollectorTestCase(CollectorTestCase): TEST_CONFIG = { '...
import gdb class CachedType: def __init__(self, name): self._type = None self._name = name def _new_objfile_handler(self, event): self._type = None gdb.events.new_objfile.disconnect(self._new_objfile_handler) def get_type(self): if self._type is None: ...
"""Tests for the private `FunctionBufferingResource` used in prefetching.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import threading from tensorflow.core.protobuf import config_pb2 from tensorflow.python.data.experimental.ops import prefetching_ops...
"""JSON token scanner """ import re try: from _json import make_scanner as c_make_scanner except ImportError: c_make_scanner = None __all__ = ['make_scanner'] NUMBER_RE = re.compile( r'(-?(?:0|[1-9]\d*))(\.\d+)?([eE][-+]?\d+)?', (re.VERBOSE | re.MULTILINE | re.DOTALL)) def py_make_scanner(context): ...
__title__ = "main generator for molex connector models" __author__ = "scripts: maurice and hyOzd; models: see cq_model files" __Comment__ = '''This generator loads cadquery model scripts and generates step/wrl files for the official kicad library.''' ___ver___ = "1.2 03/12/2017" save_memory = True #reducing memory c...
# -*- coding: utf-8 -*- ''' Created on Oct 16, 2015 @author: nlp ''' import sys import traceback from store_model import Single_weibo_store import datetime from datetime import timedelta import pprint import jieba reload(sys) sys.setdefaultencoding('utf8') from sklearn import svm X = [[0, 0], [1, 1]] y = [...
# # create symlinks for picons # usage: create_picon_sats lamedb # run in picon directory. # It will read the servicenames from the lamedb and create symlinks # for the servicereference names. # # by pieterg, 2008 import os, sys f = open(sys.argv[1]).readlines() f = f[f.index("services\n")+1:-3] while len(f) > 2:...
import webob.exc from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova.api.openstack import xmlutil from nova import db from nova import exception from nova.openstack.common.gettextutils import _ ALIAS = "os-agents" authorize = extensions.extension_authorizer('compute', 'v3:' + ALIA...
""" This is for debugging purposes only and you shouldn't load this it unless a Supybot developer requests you to debug some issue. """ import supybot.plugins as plugins import gc import os import sys try: import exceptions except ImportError: # Python 3 import builtins class exceptions: """Pseudo...
from collections import defaultdict from django.core.exceptions import ImproperlyConfigured from django.template import TemplateSyntaxError, Variable from django.template.loader import get_template from django.utils.translation import gettext_lazy as _ from mezzanine import template from mezzanine.pages.models import...
import types from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render_to_response from django import template from django.db.models.query import QuerySet import re from django.core import serializers class ViewHandler(object): def __init__(self, func, param_validator=None): ...
""" Class for manipulating groups configuration on a course object. """ import json import logging from util.db import generate_int_id, MYSQL_MAX_INT from django.utils.translation import ugettext as _ from contentstore.utils import reverse_usage_url from xmodule.partitions.partitions import UserPartition from xmodule...
# coding=utf-8 from __future__ import absolute_import, division, print_function __author__ = "Gina Häußge <<EMAIL>>" __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import un...
""" Django's support for templates. The django.template namespace contains two independent subsystems: 1. Multiple Template Engines: support for pluggable template backends, built-in backends and backend-independent APIs 2. Django Template Language: Django's own template engine, including its built-in loaders, ...
""" :mod: GFAL2_XROOTStorage ================= .. module: python :synopsis: XROOT module based on the GFAL2_StorageBase class. """ # from DIRAC from DIRAC import gLogger from DIRAC.Resources.Storage.GFAL2_StorageBase import GFAL2_StorageBase class GFAL2_XROOTStorage( GFAL2_StorageBase ): """ .. class:...
"""Internal support module for sre""" # update when constants are added or removed MAGIC = 20031017 #MAXREPEAT = 2147483648 #from _sre import MAXREPEAT # SRE standard exception (access as sre.error) # should this really be here? class error(Exception): pass # operators FAILURE = "failure" SUCCESS = "success"...
from unittest import TestCase from chess_py.core.algebraic import notation_const from chess_py.core import Board from chess_py.core.algebraic import Location, Move from chess_py.pieces import Queen, Rook, Bishop, Knight, Pawn from chess_py import color class TestPawn(TestCase): def setUp(self): self.posi...
import json from airflow.contrib.hooks.sagemaker_hook import SageMakerHook from airflow.models import BaseOperator from airflow.utils.decorators import apply_defaults class SageMakerBaseOperator(BaseOperator): """ This is the base operator for all SageMaker operators. :param config: The configuration ne...
"""This tests sympy/core/basic.py with (ideally) no reference to subclasses of Basic or Atom.""" from sympy.core.basic import Basic, Atom, preorder_traversal from sympy.core.singleton import S, Singleton from sympy.core.symbol import symbols from sympy.core.compatibility import default_sort_key, with_metaclass from s...
# coding: utf-8 from __future__ import unicode_literals from .common import InfoExtractor from ..compat import ( compat_str, compat_urllib_parse_unquote, ) from ..utils import ( determine_ext, float_or_none, get_element_by_id, int_or_none, parse_iso8601, str_to_int, ) class IzleseneIE...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} import time import json from ansible.module_utils.azure_rm_common import AzureRMModuleBase ...
"""Generates validator-generated.js. This script reads validator.protoascii and reflects over its contents to generate Javascript. This Javascript consists of Closure-style classes and enums, as well as a createRules function which instantiates the data structures specified in validator.protoascii - the validator rule...
"""OpenSSL/M2Crypto 3DES implementation.""" from cryptomath import * from TripleDES import * if m2cryptoLoaded: def new(key, mode, IV): return OpenSSL_TripleDES(key, mode, IV) class OpenSSL_TripleDES(TripleDES): def __init__(self, key, mode, IV): TripleDES.__init__(self, key, mo...
#!/usr/bin/python # -*- coding: utf-8 -*- ''' PyChess blunder finder script. This scripts allows you to analyze a played pgn file for blunders, using the engine of your choice. PYTHONPATH=lib/ python blunders.py game.pgn ''' ############################################################################...
# -*- coding: utf-8 -*- from pyqtgraph.Qt import QtCore, QtGui if not hasattr(QtCore, 'Signal'): QtCore.Signal = QtCore.pyqtSignal import weakref class CanvasManager(QtCore.QObject): SINGLETON = None sigCanvasListChanged = QtCore.Signal() def __init__(self): if CanvasManager.SINGLETON...
import logging import os from lib.symbol import FUNCTION_SYMBOLS, SOURCEFILE_SYMBOLS, TYPEINFO_SYMBOLS LOGGER = logging.getLogger('dmprof') class Bucket(object): """Represents a bucket, which is a unit of memory block classification.""" def __init__(self, stacktrace, allocator_type, typeinfo, typeinfo_name): ...
import os import math from constants import * from Dialog import Dialog from DirChooser import DirChooser from FileSelectPad import FileSelectPad from Progress import Progress from TextBox import TextBox from Label import Label from Button import Button class FileSelector(Dialog): """ """ def __i...
#!/usr/bin/python import os, sys, string, pdb import re, fileinput import ctypes import struct import json import sys def main(): # arguments, print an example of correct usage. if len(sys.argv) - 1 != 1: print("********************") print("Usage suggestion:") print("python " + sys.a...
from winui import ui from page import Page import logging log = logging.getLogger("WinuiInstallationFinishPage") class UninstallationFinishPage(Page): def on_init(self): Page.on_init(self) self.set_background_color(255,255,255) self.insert_vertical_image("%s-vertical.bmp" % self.info.prev...
import urllib import hashlib from django import template from django.conf import settings from django.utils.safestring import mark_safe from django.utils.encoding import force_bytes, force_text from readthedocs.builds.models import Version from readthedocs.projects.models import Project register = template.Library()...
import os.path as op import pytest as pytest import numpy as np from numpy.testing import assert_allclose from mne.datasets.testing import data_path from mne.io import read_raw_nirx, BaseRaw from mne.preprocessing.nirs import optical_density from mne.utils import _validate_type from mne.datasets import testing fname...
""" Dummy database backend for Django. Django uses this if the database ENGINE setting is empty (None or empty string). Each of these API functions, except connection.close(), raises ImproperlyConfigured. """ from django.core.exceptions import ImproperlyConfigured from django.db.backends.base.base import BaseDatabas...
# -*- coding: UTF-8 -*- import basic from functions import prettyItemBonus, formatTextareaInput import re from sets import Set from misc import miscController import time class creationCenterController(basic.defaultController): DIR = './ugc/' RE_CHECK_NAME = re.compile('^[a-zA-Z0-9\s\-\+\']+$', re.U+re...
#!/usr/bin/env python3 # -*- coding: ascii -*- from __future__ import unicode_literals, division, with_statement Node = r"""(function(program, execJS) { execJS(program) })(function() { #{source} }, function(program) { var output; var print = function(string) { process.stdout.write('' + string + '\n'); }; ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """.. currentmodule:: migrate.versioning.util""" import warnings import logging from decorator import decorator from pkg_resources import EntryPoint import six from sqlalchemy import create_engine from sqlalchemy.engine import Engine from sqlalchemy.pool import StaticPool...
"""Verifies that Google Test correctly parses environment variables.""" __author__ = '<EMAIL> (Zhanyong Wan)' import os import gtest_test_utils IS_WINDOWS = os.name == 'nt' IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux' COMMAND = gtest_test_utils.GetTestExecutablePath('gtest_env_var_test_') environ = ...
from django.db import models from django.core.urlresolvers import reverse import datetime # Create your models here. class Team(models.Model): short_name = models.CharField(max_length=25) name = models.CharField(max_length=50, null=True, blank=True) my_team = models.BooleanField(default = False) city ...
"""Upgrade script for removing WorkflowsTaskResult class to use a dict.""" import os import cPickle import base64 from invenio.legacy.dbquery import run_sql depends_on = ["workflows_2014_08_12_initial"] def info(): """Display info.""" return "Will convert all task results to dict instead of object" def d...
import copy import logging import os.path import unittest import mock import okaara from pulp.bindings.bindings import Bindings from pulp.bindings.server import PulpConnection from pulp.client.extensions.core import PulpPrompt, ClientContext, PulpCli from pulp.client.extensions.exceptions import ExceptionHandler from...
LOCK_SERVO_PIN = 18 # Pulse width value (in microseconds) for the servo at the unlocked and locked # position. Center should be a value of 1500, max left a value of 1000, and # max right a value of 2000. LOCK_SERVO_UNLOCKED = 2000 LOCK_SERVO_LOCKED = 1100 # Pi GPIO port which is connected to the button. BUTTON_PIN...
"""Simple text browser for IDLE """ from Tkinter import * import tkMessageBox class TextViewer(Toplevel): """ simple text viewer dialog for idle """ def __init__(self, parent, title, fileName, data=None): """If data exists, load it into viewer, otherwise try to load file. fileName - ...
class SQLParseError(Exception): pass class UnclosedQuoteError(SQLParseError): pass # maps a type of identifier to the maximum number of dot levels that are # allowed to specify that identifier. For example, a database column can be # specified by up to 4 levels: database.schema.table.column _PG_IDENTIFIER_TO...
# -*- coding: utf-8 -*- """ Tests for auth manager Password access to postgres. This is an integration test for QGIS Desktop Auth Manager postgres provider that checks if QGIS can use a stored auth manager auth configuration to access a Password protected postgres. It uses a docker container as postgres/postgis serve...
import unittest import StringIO from cerbero import hacks from cerbero.build import recipe from cerbero.config import Platform from cerbero.packages import package from cerbero.packages.wix import MergeModule from cerbero.utils import etree from test.test_build_common import create_cookbook from test.test_packages_com...
from ConfigParser import ConfigParser from offlineimap.localeval import LocalEval import os class CustomConfigParser(ConfigParser): def getdefault(self, section, option, default, *args, **kwargs): """Same as config.get, but returns the "default" option if there is no such option specified.""" ...
import unittest from hieroglyph.nodes import Node, Arg, Raises, Except, Returns, Warning, Note __author__ = 'Robert Smallshire' class NodeTests(unittest.TestCase): def test_create_default_node(self): node = Node() self.assertEqual(node.indent, 0) self.assertEqual(node.lines, [])...
VERSION = '2.5' import sys if sys.platform == 'cli': from serialcli import * else: import os # chose an implementation, depending on os if os.name == 'nt': #sys.platform == 'win32': from serialwin32 import * elif os.name == 'posix': from serialposix import * elif os.name == 'ja...
from django.conf import settings from django.db import models from django.db.models.fields import FieldDoesNotExist class CurrentSiteManager(models.Manager): "Use this to limit objects to those associated with the current site." def __init__(self, field_name=None): super(CurrentSiteManager, self).__ini...
"""The tests for the openalpr cloud platform.""" import asyncio from unittest.mock import patch, PropertyMock from homeassistant.core import callback from homeassistant.setup import setup_component from homeassistant.components import camera, image_processing as ip from homeassistant.components.image_processing.openal...
#<<EOS_COMMON_MODULE_START>> import syslog import collections from ansible.module_utils.basic import * try: import pyeapi PYEAPI_AVAILABLE = True except ImportError: PYEAPI_AVAILABLE = False DEFAULT_SYSLOG_PRIORITY = syslog.LOG_NOTICE DEFAULT_CONNECTION = 'localhost' TRANSPORTS = ['socket', 'http', 'htt...
from random import randint from sympy import Matrix, zeros, ones, Integer from sympy.physics.quantum.matrixutils import ( to_sympy, to_numpy, to_scipy_sparse, matrix_tensor_product, matrix_to_zero, matrix_zeros, numpy_ndarray, scipy_sparse_matrix ) from sympy.core.compatibility import range from sympy.extern...
from networking_cisco.apps.saf.common import dfa_logger as logging from networking_cisco.apps.saf.server.services.firewall.native import ( fabric_setup_base as FP) from networking_cisco.apps.saf.server.services.firewall.native.drivers import ( asa_rest as asa) from networking_cisco.apps.saf.server.services.fire...
def query_log_status(module, le_path, path, state="present"): """ Returns whether a log is followed or not. """ if state == "present": rc, out, err = module.run_command("%s followed %s" % (le_path, path)) if rc == 0: return True return False def follow_log(module, le_path,...
import unittest from typing import List import utils # O(n) time. O(1) space. Floyd's tortoise and hare cycle detection algorithm. class Solution: def circularArrayLoop(self, nums: List[int]) -> bool: n = len(nums) for start, move in enumerate(nums): if move == 0: con...
""" Caching utilities for robotic browsers. Credit to https://github.com/Lukasa/httpcache """ import logging import datetime from requests.adapters import HTTPAdapter from robobrowser.compat import OrderedDict, iteritems logger = logging.getLogger(__name__) # Modified from https://github.com/Lukasa/httpcache/blob/m...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os from ansible.module_utils.facts.collector import BaseFactCollector class ApparmorFactCollector(BaseFactCollector): name = 'apparmor' _fact_ids = set() def collect(self, module=None, collected_facts=None): ...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type try: from lxml.etree import tostring except ImportError: from xml.etree.ElementTree import tostring from ansible.compat.tests.mock import patch from ansible.modules.network.junos import junos_rpc from .junos_module import ...
import requests from flask import current_app from requests.auth import AuthBase class Auth(AuthBase): """ Handles the authorization method. If there is no available token for us, it logs-in and stores the token. Appends the token to the header accordingly. """ def __init__(self, domain: str, em...
from __future__ import unicode_literals __all__ = ( 'InputMode', 'CharacterFind', 'ViState', ) class InputMode(object): INSERT = 'vi-insert' INSERT_MULTIPLE = 'vi-insert-multiple' NAVIGATION = 'vi-navigation' REPLACE = 'vi-replace' class CharacterFind(object): def __init__(self, cha...
from django.conf import settings from django.core.management.base import BaseCommand from django.db import connection import silk.models class Command(BaseCommand): help = "Clears silk's log of requests." @staticmethod def delete_model(model): engine = settings.DATABASES['default']['ENGINE'] ...