code
stringlengths
1
199k
""" Shows the functionality of exec using a Busybox container. """ import time from kubernetes import config from kubernetes.client import Configuration from kubernetes.client.api import core_v1_api from kubernetes.client.rest import ApiException from kubernetes.stream import stream def exec_commands(api_instance): ...
import datetime from nova import compute from nova.compute import instance_types from nova import context from nova import db from nova.db.sqlalchemy import api as sqa_api from nova.db.sqlalchemy import models as sqa_models from nova import exception from nova import flags from nova.openstack.common import rpc from nov...
import unittest import StringIO import platform from mailtoplus import Mailtoplus, WrongSchemeException, MalformedUriException, ConfigManager class TestParser(unittest.TestCase): def setUp(self): self.mtp = Mailtoplus() def test_wrong_scheme(self): self.assertRaises(WrongSchemeException, self.mt...
import unittest from gpspixtrax import ddict class Test_ddict(unittest.TestCase): def test_ddict_empty(self): d = ddict.ddict() self.assertEqual(not d, True) d = ddict.ddict({}) self.assertEqual(not d, True) def test_ddict_attribute(self): d = ddict.ddict({'a':1}) ...
import os from pprint import pformat from django import http from django.core import signals from django.core.handlers.base import BaseHandler from django.core.urlresolvers import set_script_prefix from django.utils import datastructures from django.utils.encoding import force_unicode, smart_str, iri_to_uri class ModPy...
from evoflow.utils import slices2array from evoflow.engine import OP from evoflow import backend as B class SingleCrossover(OP): O_AUTOGRAPH = False O_XLA = False def __init__(self, population_fraction, max_crossover_probability, **kwargs): """Perform single crossovers on a given po...
class Solution(object): def smallestGoodBase(self, n): """ :type n: str :rtype: str """ # Solution 1: works n = int(n) for k in xrange(int(math.log(n, 2)), 1, -1): a = int(n ** k ** -1) if (1 - a**(k+1)) // (1-a) == n: r...
"""Tests for the Mailgun API wrapper.""" from __future__ import absolute_import # pylint: disable=import-only-modules from __future__ import unicode_literals # pylint: disable=import-only-modules from core.platform.email import mailgun_email_services from core.tests import test_utils import feconf import python_utils...
from unittest import TestCase from nose_parameterized import parameterized from collections import OrderedDict import os import gzip from pandas import ( Series, DataFrame, date_range, Timestamp, read_csv ) from pandas.util.testing import assert_frame_equal from numpy import ( arange, zeros_...
__author__ = 'lamter'
"""Punctuator models hyper-parameters.""" import lingvo.tasks.punctuator.params.codelab
from insights.tests import context_wrap from insights.parsers.cobbler_settings import CobblerSettings setting_content = """ --- allow_duplicate_hostnames: 0 allow_duplicate_ips: 0 allow_duplicate_macs: 0 anamon_enabled: 0 build_reporting_enabled: 1 build_reporting_sender: "cobbler" build_reporting_email: [ 'test@foo.ex...
import logging import sys from kmip.core import enums from kmip.demos import utils from kmip.pie import client from kmip.pie import objects if __name__ == '__main__': logger = utils.build_console_logger(logging.INFO) parser = utils.build_cli_parser() opts, args = parser.parse_args(sys.argv[1:]) config =...
"""Nova common internal object model""" import collections import copy import functools import six from nova import context from nova import exception from nova.objects import fields from nova.openstack.common.gettextutils import _ from nova.openstack.common import log as logging from nova.openstack.common.rpc import c...
"""Flax implementation of the transformer encoder. """ from functools import partial from . import util import flax from flax.deprecated import nn import jax import jax.numpy as jnp import jax.random class TransformerEncoderLayer(nn.Module): def apply(self, inputs, mask, activation...
import os def list_local(local_path): n = len(local_path) for dirpath, dirnames, filenames in os.walk(local_path): for filename in filenames: if filename.startswith('.'): continue local_key = os.path.join(dirpath, filename)[n:].lstrip('/') local_filena...
import re import collections from enum import Enum from ydk._core._dm_meta_info import _MetaInfoClassMember, _MetaInfoClass, _MetaInfoEnum from ydk.types import Empty, YList, YLeafList, DELETE, Decimal64, FixedBitsDict from ydk._core._dm_meta_info import ATTRIBUTE, REFERENCE_CLASS, REFERENCE_LIST, REFERENCE_LEAFLIST, ...
import sys from .driver import get_valid_actions def return_choices(choices): print('\n'.join(choices)) sys.exit(0) def return_no_choices(): sys.exit(0) def complete(cmdline, point): service_names = ('iaas', 'qs') service_name = None words = cmdline[0:point].split() if not words: ret...
import itertools from doublecheck import gen class TestCase(object): ''' A result is the Certain/Falsified/Undecided status of a property along with any debugging info. ''' Falsified = "Falsified" Certain = "Certain" Undecided = "Undecided" def __init__(self, status, arguments = []): ...
"""Tests for 1-Wire devices connected on OWServer.""" from unittest.mock import MagicMock, patch import pytest from homeassistant.components.binary_sensor import DOMAIN as BINARY_SENSOR_DOMAIN from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from . import ( check_and...
""" Query capability built on skew metamodel tags_spec -> s3, elb, rds detail_spec - aws.route53.healthcheck -> health check info - aws.cloudformation.stack -> stack resources - aws.dymanodb.table -> """ import jmespath from botocore.client import ClientError from skew.resources import find_resource_class from...
import mock from neutron.tests import base from networking_nec.nwa.l2.rpc import nwa_agent_api class TestNECNWAAgentApi(base.BaseTestCase): @mock.patch('neutron.common.rpc.get_client') def setUp(self, f1): super(TestNECNWAAgentApi, self).setUp() self.proxy = nwa_agent_api.NECNWAAgentApi("dummy-t...
from django.contrib import admin from invite_only.models import InviteCode admin.site.register(InviteCode)
""" -------------- theia.storeapi -------------- Event Store API Defines classes, methods and exceptions to be used when implementing an Event Store. """ from abc import abstractmethod class EventStore: """EventStore is the basic interface for interaction with the events. Main uses of this store are CRUD intera...
'''Test that all public modules are accessible after importing just 'pyglet'. This _must_ be the first test run. ''' import imp import unittest import pyglet modules = [ 'app', 'clock', 'event', 'font', 'font.base', 'gl', 'gl.gl_info', 'gl.glu_info', 'graphics', 'graphics.allocat...
from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS DEFAULT_BETA = 2 DEFAULT_SCALER_ALGO = 'normcdf' DEFAULT_D3_AXIS_VALUE_FORMAT = '.3f' DEFAULT_PMI_THRESHOLD_COEFFICIENT = 8 DEFAULT_MINIMUM_TERM_FREQUENCY = 3 DEFAULT_DIV_ID = 'd3-div-1' DEFAULT_HTML_VIZ_FILE_NAME = 'scattertext.html' AUTOCOMPLETE_CSS_FILE_...
import pexpect import sys import re from getpass import getpass def main(): ip = '184.105.247.71' username = 'pyclass' password = getpass() ssh_conn = pexpect.spawn('ssh -l {} {}'.format(username, ip)) ssh_conn.logfile = sys.stdout ssh_conn.timeout = 3 ssh_conn.expect('ssword:') ssh_conn...
import time import signal import threading from webiopi.utils import logger RUNNING = False TASKS = [] class Task(threading.Thread): def __init__(self, func, loop=False): threading.Thread.__init__(self) self.func = func self.loop = loop self.running = True self.start() de...
from direct.actor import Actor from direct.directnotify import DirectNotifyGlobal from direct.fsm import State from direct.interval.IntervalGlobal import * from pandac.PandaModules import * import random from BattleBase import * import DistributedBattleBase import MovieUtil import SuitBattleGlobals from otp.avatar impo...
"""Python wrapper for prefetching_ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import warnings from tensorflow.python.data.ops import dataset_ops from tensorflow.python.data.ops import iterator_ops from tensorflow.python.data.util import nest from ...
"""Power safety layer to prevent balloon from running out of power.""" import datetime as dt from balloon_learning_environment.env.balloon import control from balloon_learning_environment.env.balloon import solar from balloon_learning_environment.utils import units import s2sphere as s2 class PowerSafetyLayer(): """A...
from __future__ import absolute_import from __future__ import division import json import logging import socket from werkzeug import routing from werkzeug import serving from werkzeug.exceptions import HTTPException, NotFound from werkzeug.middleware.shared_data import SharedDataMiddleware from werkzeug.wrappers import...
""" Tests For Compute w/ Cells """ import functools import inspect import mock from oslo.config import cfg from oslo.utils import timeutils from nova.cells import manager from nova.compute import api as compute_api from nova.compute import cells_api as compute_cells_api from nova.compute import delete_types from nova.c...
import os import re def walk_dir(path): file_path_list = [] for root, dirs, files in os.walk(path): for f in files: if f.lower().endswith('txt'): file_path_list.append(os.path.join(root, f)) return file_path_list def find_key_word(txt_file_path): word_dic = {} fil...
import re from math import sin, cos, atan2, sqrt class UnitsError(Exception): """Exception raised when unrecognized units are used.""" pass FRACTION_RE = re.compile(r"^((?P<int>\d+)\s*)?(?P<num>\d)/(?P<den>\d+)$") class temperature(object): """A class representing a temperature value.""" legal_units = [ "F", "C...
""" Copyright 2011 Xavier Stevens <xstevens@mozilla.com> This file is provided to you 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 l...
""" A set of tests for each class/function. These are meant to be run using the run_unit_tests.py in the test_data folder. Note that some of these rely on previous tests having been run in order to have the necessary files setup and available. """ import os import sys import pprint import copy os.system("rm -rf working...
import os import sys import time import datetime import random from mininet.net import Mininet from mininet.node import RemoteController, OVSKernelSwitch, UserSwitch from mininet.link import TCLink from mininet.cli import CLI from mininet.log import setLogLevel from mininet.term import makeTerm """ Handorver example (b...
"""Tests for tfgan.examples.esrgan.utils.""" import collections import tensorflow as tf from tensorflow_gan.examples.esrgan import networks from tensorflow_gan.examples.esrgan import utils HParams = collections.namedtuple( 'HParams', ['hr_dimension', 'scale', 'trunk_size', 'path']) class UtilsTest(tf.test.TestCase)...
""" A connection to a hypervisor through libvirt. Supports KVM, LXC, QEMU, UML, and XEN. **Related Flags** :libvirt_type: Libvirt domain type. Can be kvm, qemu, uml, xen (default: kvm). :libvirt_uri: Override for the default libvirt URI (depends on libvirt_type). :libvirt_xml_template: Libvirt XML T...
"""Logic to update a TensorFlow model graph with quantization operations.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import re from tensorflow.contrib import graph_editor from tensorflow.contrib.quantize.python import common from tensorflow.contrib.qu...
import json import unittest import flask from elasticsearch.exceptions import RequestError, ConnectionError from mock import patch, MagicMock from data_catalog.search import DataSetSearch, InvalidQueryError, IndexConnectionError from tests.base_test import DataCatalogTestCase class SearchTests(DataCatalogTestCase): ...
def foo(x,y, **kwargs): return x + y + kwargs['a'] def bar(): return (2, 3) if __name__ == '__main__': result = bar() map = {'a':23, 'b':0.4} print foo(*result, **map)
from __future__ import unicode_literals, print_function from builtins import object, str from collections import OrderedDict from . import config class ZeilenFeld(object): def __init__(self, titel, weite, fontsize, text='', style='', align='', linie=False, font=config.FONT): self.titel = titel self....
""" Support for the IKEA Tradfri platform. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/light.tradfri/ """ import logging from homeassistant.core import callback from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_...
import collections import numpy, pandas, humanize def open(filename): with pandas.HDFStore(filename) as store: return Collection(store["events"], store["metadata"]) def empty(): def empty_array(dtype): return numpy.array([], dtype=dtype) events_df = pandas.DataFrame({ 'when': empty_a...
from abjad import * from PySide import QtGui import tools import watchman import performer import conductor show_piano_righthand = True show_piano_lefthand = True show_bass = True show_stabs = True score = Score([]) piano_staff = scoretools.PianoStaff([]) upper_staff = Staff([]) lower_staff = Staff([]) bass_staff = Sta...
import importlib def _class_by_name( module, className ): """ Helper function to extract a class from module """ # Import module mod = importlib.import_module(module) # Get class return getattr(mod, className) def parserFactory( specs, context, metrics ): """ Create a parser from the specs dict """ # Extract...
""" Tool to subroutinize a CFF OpenType font. Backed by a C++ binary. This file is a bootstrap for the C++ edition of the FontTools compreffor. It prepares the input data for the extension and reads back in the results, applying them to the input font. Usage (command line): >> ./cxxCompressor.py /path/to/font.otf Usage...
from JumpScale import j class SerializerBase: def dump(self, filepath, obj): data = self.dumps(obj) j.sal.fs.writeFile(filepath, data) def load(self, filepath): b = j.sal.fs.fileGetContents(filepath) return self.loads(b)
from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from django.utils.decorators import method_decorator from django.contrib.auth.decorators import login_required from django.views.generic import TemplateView from course_grader.dao.term import t...
import proto # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v8.enums", marshal="google.ads.googleads.v8", manifest={"DistanceBucketEnum",}, ) class DistanceBucketEnum(proto.Message): r"""Container for distance buckets of a user’s distance from an advertiser’s location ext...
from .mcmc_sampler import AffineInvariantEnsembleSampler, McmcSampler # noqa: F401
import functools import sqlalchemy from JumpScale import j class SqlDb(object): """ SQL connection """ def __init__(self, lazyConfig): self._lazyConfig = lazyConfig self._sqldb = None def _getSqlDb(self): if not self._sqldb: host, database, user, password = self._...
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # @param p, a tree node # @param q, a tree node # @return a boolean def isSameTree(self, p, q): if None == p and None == q: return True if None =...
import grpc import logging from .proto import interface_pb2_grpc from .proto import interface_pb2 from .proto import graph_pb2 from .proto import computation_pb2 from .proto.computation_pb2 import SessionId from .computation import Computation from .column import AbstractNode __all__ = ['Session', 'session'] logger = l...
import sys import tensorflow as tf from model import ModelW2T from tfx.bricks import embedding, dense_to_one_hot, linear, conv2d, multicolumn_embedding, \ glorot_mul, reduce_max, dropout, conv2d_bn, batch_norm_lin, pow_1 class Model(ModelW2T): def __init__(self, data, FLAGS): super(Model, self).__init__...
from .browser import Browser from .page import Page from .webelement import WebElement
from JumpScale import j import gevent import gevent.monkey from gevent.pywsgi import WSGIServer from flask import Flask, request, Response, render_template app = Flask(__name__) app.debug = True class PMWSServer(): def __init__(self): self.http_server = WSGIServer(('127.0.0.1', 8001), app) def start(sel...
import threading import time import datetime as dt import fileparse as fp historyLock = threading.Lock() day = 24 * 60 * 60 with historyLock, open('days/lastupdate.txt') as f: last_update = int(f.readline()) def statusChange(upd): global last_update with historyLock: d = dt.datetime.now(dt.timezone(...
__doc__ = 'A Python library for generating discounted cashflows.' __version__ = '0.4' __dev_status__ = '3 - Alpha' __date__ = 'Saturday, 10 October 2020' __author__ = 'sonntagsgesicht, based on a fork of Deutsche Postbank [pbrisk]' __email__ = 'sonntagsgesicht@icloud.com' __url__ = 'https://github.com/sonntagsgesicht/'...
import cherrypy import json from girder.api import access from girder.api.describe import Description from girder.api.docs import addModel from girder.constants import AccessType from girder.api.rest import RestException from .base import BaseResource class Script(BaseResource): def __init__(self): super(Sc...
import os import math import numpy from appionlib import apDisplay from appionlib.apImage import imagestat class ImproveIEEEfit(object): def __init__(self, k, xdata, ydata): """ xdata is linear from the CTF ydata is the normalized CTF with range 0 -> 1 and mean 0.5 k is the shift as published in: Park et al...
import codecs from jolokia_session import JolokiaSession class RemoteJmxQueue(object): def __init__(self, jolokia_session, broker_name, queue_name): self.jolokia_session = jolokia_session self.queue_bean = ( "org.apache.activemq:type=Broker,brokerName={}," "destinationType=Qu...
import mock from cassandra.cqlengine import columns from cassandra.cqlengine.connection import NOT_SET from cassandra.cqlengine.management import drop_table, sync_table from cassandra.cqlengine.models import Model from cassandra.cqlengine.query import BatchQuery, DMLQuery from tests.integration.cqlengine.base import Ba...
import proto # type: ignore from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( package="google.cloud.memcache.v1", manifest={ "MemcacheVersion", "Instance", "ListInstancesRequest", "Li...
import collections import pytest import re from unittest import mock from aiohttp.multidict import CIMultiDict from aiohttp.web import Request from aiohttp.protocol import RawRequestMessage, HttpVersion11 from aiohttp import signals, web @pytest.fixture def buf(): return bytearray() @pytest.fixture def request(buf)...
''' This file is an altered copy of yotta/lib/detect.py Our specific changes alter the default yotta target and change it to the x86-linux-native instead of the x86-platform-native target which doesn't exist in the kubos-cli context ''' import platform import sys from yotta.lib import settings def defaultTarget(ignore_...
"""Map Z-Wave nodes and values to Home Assistant entities.""" from __future__ import annotations from collections.abc import Generator from dataclasses import asdict, dataclass, field from typing import Any from awesomeversion import AwesomeVersion from zwave_js_server.const import THERMOSTAT_CURRENT_TEMP_PROPERTY, Com...
from oslo_log import log as logging import sqlalchemy as sa from neutron.api.v2 import attributes as attrs from neutron.db import model_base from neutron.db import models_v2 LOG = logging.getLogger(__name__) class QosPolicy(model_base.BASEV2, models_v2.HasId, models_v2.HasTenant): __tablename__ = 'qos_policies' ...
""" Helper for Optical Flow visualization """ import numpy as np class Flow(object): """ based on https://github.com/cgtuebingen/learning-blind-motion-deblurring/blob/master/synthblur/src/flow.cpp#L44 """ def __init__(self): super(Flow, self).__init__() self.wheel = None self._co...
"""Schemas for simple BSON types.""" import uuid from datetime import datetime, date, time import six import pytz import bson from .base import Validator, Invalid class Scalar(Validator): _msgs = dict(Validator._msgs) class ObjectId(Scalar): _msgs = dict(Scalar._msgs, not_oid="Value must be an ObjectId") de...
""" Copyright 2015 herd contributors 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 writi...
import numpy as np import tensorflow as tf import os.path from tic_tac_toe.Board import Board, BOARD_SIZE, EMPTY, WIN, DRAW, LOSE LEARNING_RATE = 0.01 MODEL_NAME = 'tic-tac-toe-model-nna' MODEL_PATH = './saved_models/' WIN_VALUE = 1.0 DRAW_VALUE = 0.6 LOSS_VALUE = 0.0 TRAINING = True class QNetwork: def __init__(se...
class Vector2D(object): ''' Yet another vector class. ''' def __init__(self, vector_factory, x, y): self.vector_factory = vector_factory.that_must_make('Vector2D', 'vector_factory, x, y') self.x = x self.y = y def translate(self, other_vector): self.must_return(None) ...
from .agent import Agent, GradientAgent, BetaAgent from .bandit import GaussianBandit, BinomialBandit, BernoulliBandit from .environment import Environment from .policy import (EpsilonGreedyPolicy, GreedyPolicy, RandomPolicy, UCBPolicy, SoftmaxPolicy)
"""Constants for the ontology validator application.""" from os import path _USE_ABSOLUTE_PATH = False if _USE_ABSOLUTE_PATH: REPO_ROOT = path.join('third_party', 'digitalbuildings') else: REPO_ROOT = path.join( path.dirname(path.realpath(__file__)), path.join('..', '..', '..', '..')) APPLICATION_ROOT = path....
from sys import * from subprocess import * import os import os.path force = False clean = False print(argv) for currArg in argv: if(currArg[0:2] == "--"): if(currArg[2:] == "force"): force = True if(currArg[2:] == "clean"): clean = True proc = Popen(["mkdir", "tmp"]) proc.wai...
import os import sys sys.path.insert(0, os.path.abspath('../..')) extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.viewcode', 'sphinx.ext.githubpages', ] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index'...
""" Thread to perform creation of a service """ import os import traceback from agent.lib.utils import islink from agent.lib.utils import readlink from agent.lib.errors import Errors from agent.lib.errors import AgentException from agent.lib.agent_thread.manifest_control import ManifestControl from agent.lib import man...
"""Library for parsing and analyzing Java hprof files """ from .parsers import HProfParser, HeapDumpParser
from datetime import datetime, timedelta from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ from django.utils.log import getLogger from TeaScrum import STATUS_CHOICES from TeaScrum.product.models import Product logger = getLogger('TeaScrum') ...
""" Signals relating to comments. """ from django.dispatch import Signal comment_will_be_removed = Signal(providing_args=["comment", "request"])
"""Tests for grr_response_server.flows.general.filetypes.""" import os from absl import app from grr_response_client.client_actions import plist from grr_response_core.lib.rdfvalues import paths as rdf_paths from grr_response_core.lib.rdfvalues import plist as rdf_plist from grr_response_server.flows.general import fil...
"""Get a single product from a specified Google Merchant Center account and a product ID""" import argparse import sys from apiclient import sample_tools from oauth2client import client argparser = argparse.ArgumentParser(add_help=False) argparser.add_argument( 'merchant_id', help='The ID of the merchant center...
from oslo_config import cfg database_opts = [ cfg.BoolOpt('sqlite_synchronous', deprecated_group='DEFAULT', default=True, help='If True, SQLite uses synchronous mode.'), cfg.StrOpt('backend', default='sqlalchemy', deprecated_name='db_...
import sys import re import os import shutil import commands """Copy Special exercise """ print os def main(): # This basic command line argument parsing code is provided. # Add code to call your functions below. # Make a list of command line arguments, omitting the [0] element # which is the script itself. a...
from driver_pete_python_sandbox.download import S3 import os from matplotlib.dates import date2num, num2date import dateutil import datetime from driver_pete_python_sandbox.trajectory_reader import read_compressed_trajectory,\ write_compressed_trajectory, date_str_to_num_converter,\ num_to_date_str_converter de...
""" Common clustering functions and utilities. Created on Fri Dec 16 14:14:30 2016 @author: mkonrad """ import itertools import numpy as np from scipy.stats import chisquare from pdftabextract import logger from pdftabextract.common import (fill_array_a_with_values_from_b, sorted_by_attr, flatten_list, update_text_dict...
from __future__ import print_function from awsshell.fuzzy import fuzzy_search from awsshell.substring import substring_search class AWSCLIModelCompleter(object): """Autocompletion based on the JSON models for AWS services. This class consumes indexed data based on the JSON models from AWS service (which we ...
import urllib2 import sys sys.path.insert(1, "..") import h2o from tests import utils """ Here is some testing infrastructure for running the pyunit tests in conjunction with run.py. run.py issues an ip and port as a string: "<ip>:<port>". The expected value of sys_args[1] is "<ip>:<port>" All tests MUST have the foll...
import json import os import time from graphite_api._vendor import whisper from . import TestCase, WHISPER_DIR try: from flask.ext.cache import Cache except ImportError: Cache = None class RenderTest(TestCase): db = os.path.join(WHISPER_DIR, 'test.wsp') url = '/render' def create_db(self): w...
import logging import re from django.apps import apps from django.conf import settings from elasticsearch import helpers from elasticsearch import Elasticsearch from share.models import Agent from share.models import CreativeWork from share.models import Subject from share.models import Tag from share.tasks import Prov...
""" Support for Fibaro cover - curtains, rollershutters etc. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/cover.fibaro/ """ import logging from homeassistant.components.cover import ( CoverDevice, ENTITY_ID_FORMAT, ATTR_POSITION, ATTR_TILT_POSITION)...
from Tkinter import * class Application(Frame): def say_hi(self): print "hi there, everyone!" def createWidgets(self): self.Label = Label(self, text='|---- LibRadar Tagging System -----|\n| Version: 2.0.1.dev1 |') self.Label.pack() self.QUIT = Button(self) se...
"""FogLAMP Sensor Readings Ingest API""" import asyncio import datetime import time from typing import List, Union import json from foglamp.common import logger from foglamp.common import statistics from foglamp.common.storage_client.exceptions import StorageServerError __author__ = "Terris Linenbach, Amarendra K Sinha...
"""Tests for the FileFinder flow.""" import os from grr.client import vfs from grr.lib import action_mocks from grr.lib import aff4 from grr.lib import flags from grr.lib import flow from grr.lib import rdfvalue from grr.lib import test_lib class FileFinderActionMock(action_mocks.ActionMock): def __init__(self): ...
from sicpythontask.PythonTaskInfo import PythonTaskInfo from sicpythontask.PythonTask import PythonTask from sicpythontask.SicParameter import SicParameter from sicpythontask.InputPort import InputPort from sicpythontask.OutputPort import OutputPort from sicpythontask.data.Int32 import Int32 @PythonTaskInfo @SicParamet...
import sys import json import hashlib import click import time import re from google.cloud import pubsub_v1 def obfuscate_project_id(project_id): m = hashlib.sha256() m.update(project_id.encode('utf-8')) hashed = m.hexdigest() return hashed def get_telemetry_msg(session, project_id, event, version): ...
import redis import json import time import sys conn = redis.Redis() while 1: keys = conn.keys() if len(keys) == 0 : continue values = conn.mget(keys) try: deltas = [float(v) for v in values] except TypeError: print keys continue if len(deltas): rate = sum...