code
stringlengths
1
199k
from __future__ import unicode_literals import uuid from django.core.exceptions import FieldDoesNotExist from django.db import migrations def set_uuid_field(apps, schema_editor): """ Set a random uuid value to all existing rows in all models containing an 'uuid' attribute in database. """ base = apps.ge...
""" Urls for idea app """ from django.conf.urls import url from openedx.features.idea.api_views import FavoriteAPIView from openedx.features.idea.views import ChallengeLandingView, IdeaCreateView, IdeaDetailView, IdeaListingView urlpatterns = [ url( r'^overview/$', ChallengeLandingView.as_view(), ...
import clv_medicament_template_wkf
from __future__ import unicode_literals from django.db import migrations import django.utils.timezone import model_utils.fields class Migration(migrations.Migration): dependencies = [ ('idea', '0002_idea_favorites'), ] operations = [ migrations.AddField( model_name='idea', ...
from spack import * class Numdiff(AutotoolsPackage): """Numdiff is a little program that can be used to compare putatively similar files line by line and field by field, ignoring small numeric differences or/and different numeric formats.""" homepage = 'https://www.nongnu.org/numdiff' url = '...
""" httpdatehelper ============== :Module: pyfileserver.httpdatehelper :Author: Ho Chun Wei, fuzzybr80(at)gmail.com :Project: PyFileServer, http://pyfilesync.berlios.de/ :Copyright: Lesser GNU Public License, see LICENSE file attached with package HTTP dates helper - an assorted library of helpful date functions: * get...
import SR import LVHDoHBASR import LVHDSR import SRCommand import sys import xs_errors import util CAPABILITIES = ["SR_PROBE", "SR_UPDATE", "SR_METADATA", "SR_TRIM", "VDI_CREATE", "VDI_DELETE", "VDI_ATTACH", "VDI_DETACH", "VDI_GENERATE_CONFIG", "VDI_SNAPSHOT", "VDI_CLONE", ...
from pysignfe.xml_sped import * from .ConsultarSituacaoLoteRps import ListaMensagemRetorno from .Rps import IdentificacaoPrestador, IdentificacaoRps from .Nfse import CompNfse import os DIRNAME = os.path.dirname(__file__) class ConsultarLoteRpsEnvio(XMLNFe): def __init__(self): super(ConsultarLoteRpsEnvio, ...
from spack import * class Fastqvalidator(MakefilePackage): """The fastQValidator validates the format of fastq files.""" homepage = "http://genome.sph.umich.edu/wiki/FastQValidator" url = "https://github.com/statgen/fastQValidator/archive/v0.1.1a.tar.gz" version('2017-01-10', commit='6d619a34749e9d...
""" PyGTK compatibility layer. This modules goes a little bit longer to maintain PyGTK compatibility than the normal overrides system. It is recommended to not depend on this layer, but only use it as an intermediate step when porting your application to PyGI. Compatibility might never be 100%, but the aim is to make i...
from spack import * class PyBsddb3(PythonPackage): """This module provides a nearly complete wrapping of the Oracle/Sleepycat C API for the Database Environment, Database, Cursor, Log Cursor, Sequence and Transaction objects, and each of these is exposed as a Python type in the bsddb3.db module...
from collections.abc import Sequence, Iterable from functools import total_ordering import fnmatch import linecache import os.path import pickle from _tracemalloc import * from _tracemalloc import _get_object_traceback, _get_traces def _format_size(size, sign): for unit in ('B', 'KiB', 'MiB', 'GiB', 'TiB'): ...
""" GstGengui: runner for non-installed package """ from gst_gtklaunch import gst_gtklaunch if __name__ == '__main__': gst_gtklaunch.main()
import pytest from forte.solvers import solver_factory, HF, ActiveSpaceSolver def test_detci_4(): """CASCI test of Forte DETCI using the SparseList algorithm to build the sigma vector""" ref_hf_energy = -99.977636678461636 ref_fci_energy = -100.113732484560970 xyz = """ F H 1 1.0 """ inp...
"""Glyph-specific queries on font-files""" from ttfquery import describe try: from OpenGLContext.debug.logs import text_log except ImportError: text_log = None def hasGlyph( font, char, encoding=None ): """Check to see if font appears to have explicit glyph for char""" glyfName = explicitGlyph( font, ch...
import attr import struct import math import re import copy from datablock import Datablock from record import Record from rowid import Rowid @attr.s class TableDatablock(Datablock): header = attr.ib(default=[]) records = attr.ib(default=[]) def get_data(self): """ Convert header and records...
""" Created on June 10, 2012 @author: peta15 """ from wtforms import fields from wtforms import Form from wtforms import validators from lib import utils from webapp2_extras.i18n import lazy_gettext as _ from webapp2_extras.i18n import ngettext, gettext FIELD_MAXLENGTH = 50 # intended to stop maliciously long input cla...
import pyblish.api import maya.cmds as cmds import pymel class ValidateDisplaylayer(pyblish.api.Validator): """ Ensure no construction history exists on the nodes in the instance """ families = ['scene'] optional = True label = 'Modeling - Display Layers' def process(self, instance): """Proc...
""" YANK, a package for alchemical free energy calculations using OpenMM """ __author__ = "John D. Chodera" __license__ = "GPL" __maintainer__ = "John D. Chodera" __email__ = "jchodera@gmail.com" __version__ = "1.0beta" from yank import Yank import analysis __all__ = ['Yank', 'analysis']
from __future__ import with_statement import sys import os import os.path def vs9to10(src, dest): for name in os.listdir(src): path, ext = os.path.splitext(name) if ext.lower() not in ('.vcxproj',): continue filename = os.path.normpath(os.path.join(src, name)) destname = ...
from pygame import * from pyganim import * from entity import Entity from bullet import Bullet class Player(Entity): def __init__(self, x, y, images): Entity.__init__(self, x, y, images) # Properties self.alive = True self.isHidden = True self.bullets = 6 # Directions variables self.goLeft = self.goRight...
class Page: def __init__(self, id, page): self.id = id self.page = page def set_href(self, href): self.page.attr("_href", href) def get_href(self): return self.page.attr("_href") class TabMenuItem: def __init__(self, id, title, url, data=None): self.id = id ...
from openerp import models, fields, api, tools, _ class odisea_representative(models.Model): """Representative""" _name = 'odisea.representative' _description = 'Representative' @api.multi def _has_image(self): return dict((p.id, bool(p.image)) for p in self) name = fields.Char(string='Name', required=Tr...
import re from untwisted.magic import sign from channel import not_quiet from runtime import later import message import util import limit import kakasi_lib link, install, uninstall = util.LinkSet().triple() ''' @link('MESSAGE') @not_quiet() def h_message(bot, id, target, msg): if limit.mark_activity(bot, id): retu...
""" This exercise shows some important concepts that you should be aware about: - using codecs module to write unicode files - using authentication with web APIs - using offset when accessing web APIs To run this code locally you have to register at the NYTimes developer site and get your own API key. You will be able ...
from datetime import datetime, timedelta
import os import apium.frameworks def test_basic_task_run___state_is_consistent(port_num, running_worker): os.environ['DJANGO_SETTINGS_MODULE'] = 'django_test_project.settings' apium.frameworks.setup()
default_app_config = 'jobs.apps.JobConfig'
from button import Button class SellButton(Button): def __init__(self, image, x, y, parent): super(SellButton, self).__init__(image, x, y, parent) def get_clicked(self): self.parent.sell_tower()
from __future__ import print_function import sys, os import parse_doxygen DOXYGEN_XML_DIR = 'doxygen/xml' API_GEN_DIR = 'generated_rst_files' SWIG_DIR = '../dolfin/swig/' SWIG_FILE = 'docstrings.i' MOCK_PY = 'mock_cpp_modules.py' def get_subdir(hpp_file_name): """ Return "subdir" for a path name like /p...
from .player import PlayerEntity from .base import MobEntity from .item import ItemEntity __all__ = [ 'PlayerEntity', 'MobEntity', 'ItemEntity', ]
import pygame from pygame.locals import * import time def init(): pygame.display.set_mode((800, 600)) def test_1(): def test(pressed, i): if i == 0: return if pressed[K_a]: print "K_a" if pressed[K_b]: print "K_b" test(pressed, i -1) pressed = pygame.key.get_pressed() for x in xrange(10000): # te...
import fileinput class NotValidIP(Exception): pass class NotValidIPLength(Exception): pass while True: try: ip_addr = input("Enter a network IP address: ") ip_addr_split = ip_addr.split('.') len1 = len(ip_addr_split) ip_addr_split = ip_addr_split[:3] ip_addr_split.app...
VERSION = (0, 1, 6, 'final') if VERSION[-1] != "final": # pragma: no cover __version__ = '.'.join(map(str, VERSION)) else: # pragma: no cover __version__ = '.'.join(map(str, VERSION[:-1]))
from pippi import dsp from pippi import tune def ping(maxlen=44100, freqs=None): out = '' if freqs is None: freqs = [ dsp.rand(20,10000) for i in range(4) ] tlen = dsp.randint(10, maxlen) tones = [ dsp.tone(length=tlen, freq=freq, amp=0.1, wavetype='random') for freq in freqs ] t...
import unittest import utils def remove_backspace(s): result = [] for ch in s: if ch == '#': if result: result.pop() else: result.append(ch) return result class Solution: def backspaceCompare(self, S: str, T: str) -> bool: return remove_bac...
__description__ = \ """ compareAncestor.py """ __author__ = "Michael J. Harms" __usage__ = "comapreAncestors.py ancestor_file1 ancestor_file2" __date__ = "100726" import sys, phyloBase class CompareAncestorError(Exception): """ General error class for this module. """ pass def readAncestorFile(ancestor_...
import difflib class Repository: def __init__(self, fname=None): if not fname: fname = '/usr/share/dict/words' with open(fname) as f: self.repository = [x.rstrip('\n') for x in f.readlines()] def find_close_matches(r, w, count=3): return difflib.get_close_matches(w, r.rep...
import wx import wx.lib.filebrowsebutton as filebrowse import os import numpy as N from osgeo import gdalnumeric from osgeo import gdal from osgeo import gdal_array from osgeo.gdalconst import * from wx import ImageFromStream, BitmapFromImage, EmptyIcon import cStringIO import images qc = '' output = '' NameMOD = ['250...
def estriangulo(a,b,c): print("el primer argumento es:",a) print("el segundo argumento es:",b) print("el tercer argumento es:",c) return a+b>c and a+c>b and c+b>a def espitagorico(a,b,c): return a**2+b**2==c**2 or a**2+c**2==b**2 or b**2+c**2==a**2 def esisosceles(a,b,c): return a==b or a==c or ...
import sys import collections as c from scipy import special, stats import numpy as n, pylab as p, networkx as x class NetworkDrawer: drawer_count=0 def __init__(self,metric="strength"): self.drawer_count+=1 metric_=self.standardizeName(metric) self.metric_=metric_ self.draw_coun...
"""Test the collector flows.""" import os from grr.client import vfs from grr.lib import action_mocks from grr.lib import aff4 from grr.lib import artifact from grr.lib import artifact_lib from grr.lib import artifact_test from grr.lib import flags from grr.lib import rdfvalue from grr.lib import test_lib from grr.lib ...
from ._base import Config class AppServiceConfig(Config): def read_config(self, config): self.app_service_config_files = config.get("app_service_config_files", []) def default_config(cls, **kwargs): return """\ # A list of application service config file to use app_service_config...
"""Implementation of RAFT.""" import tensorflow as tf def create_update_Conv2d(c_in, c_out, k_size): kernel_scale = 1.0 / 3.0 if isinstance(k_size, list) or isinstance(k_size, tuple): bias_scale = c_out / (3.0 * c_in * k_size[0] * k_size[1]) else: bias_scale = c_out / (3.0 * c_in * k_size * k_size) retu...
from __future__ import absolute_import import json import sys import time import unittest from fabric.api import local import nose from lib.noseplugin import OptionParser, parser_option from lib import base from lib.base import ( BGP_FSM_IDLE, BGP_FSM_ACTIVE, BGP_FSM_ESTABLISHED, BGP_ATTR_TYPE_MULTI_EXI...
from setuptools import find_packages from setuptools import setup setup( name='svs', version='1.0.0', description='The InAcademia Simple validation Service allows for the easy validation of affiliation (Student,' 'Faculty, Staff) of a user in Academia', license='Apache 2.0', classifi...
from google.cloud import resourcemanager_v3 def sample_update_folder(): # Create a client client = resourcemanager_v3.FoldersClient() # Initialize request argument(s) folder = resourcemanager_v3.Folder() folder.parent = "parent_value" request = resourcemanager_v3.UpdateFolderRequest( fol...
"""This module implements the Lovins stemming algorithm. Use the ``stem()`` function:: stemmed_word = stem(word) """ from whoosh.util.collections2 import defaultdict def A(base): # A No restrictions on stem return True def B(base): # B Minimum stem length = 3 return len(base) > 2 def C(base): ...
from optparse import OptionParser import re import os import sys import numpy as np from ..util import dirs from ..util import file_handling as fh from ..preprocessing import data_splitting as ds from ..feature_extractors.vocabulary_with_counts import VocabWithCounts def main(): usage = "%prog project" parser =...
""" Routines for configuring Heat """ import logging as sys_logging import os from eventlet.green import socket from oslo_concurrency import processutils from oslo_config import cfg from oslo_log import log as logging from heat.common import exception from heat.common.i18n import _ from heat.common.i18n import _LW from...
import os import tempfile import unittest import logging from pyidf import ValidationLevel import pyidf from pyidf.idf import IDF from pyidf.compliance_objects import ComplianceBuilding log = logging.getLogger(__name__) class TestComplianceBuilding(unittest.TestCase): def setUp(self): self.fd, self.path = t...
from .SlackIntegration import slackIntegration import logging from aiohttp import ClientSession import asyncio from time import perf_counter class LoadApp(): def __init__(self): self.logger = logging.getLogger('reliability') self.app_visit_succeeded = 0 self.app_visit_failed = 0 self...
import subprocess import sys, threading, Queue import os import string from time import gmtime, strftime import urllib2 import urllib import re, time import urlparse import os.path import logging import scan import executemechanize import extraction import mechanize from BeautifulSoup import BeautifulSoup def domaindow...
"""Load and save functions for zipped svg files.""" import faint.svg.parse_svg as parse_svg import faint.svg.write_svg as write_svg def load(filename, imageprops): """Load image from the zipped svg file.""" parse_svg.parse_svgz_file(filename, imageprops, "en") def save(filename, canvas): """Save the image t...
"""Data processing utility functions.""" from typing import Tuple, List, Sequence import attr import six from etcmodel.models import tokenization _WHITESPACE_DELIMITER = u" \t\r\n\u202f" # \u202f corresponds to "" @attr.s(auto_attribs=True) class TokenizedText: """Tokenized text with indices mappings.""" # The ori...
import pairing_heap as pheap from copy import deepcopy,copy import threading import Queue import requests from requests.auth import HTTPDigestAuth import json import sys import communication import config import time import L_sprit LIMIT_SELECTION = 0 SELECTON_RATE = 0 EXCHANGE_RATE = 0 MODE_CHANGE_THRESHOLD = 0.50 ALL...
from xml.etree import ElementTree from os.path import dirname, realpath directory_of_sources = dirname(realpath(__file__)) + "/sources/" d = {} d['AR'] = "Arabic" d['EN'] = "English" d['ES'] = "Spanish" d['FR'] = "French" d['RU'] = "Russian" d['ZH'] = "Mandarin" filepath = '/tmp/uncorpora_plain_20090831.tmx' count = 0 ...
""" module that specified how we choose paramaters based on current search database properties """ from __future__ import absolute_import, division, print_function import utool as ut print, print_, printDBG, rrr, profile = ut.inject(__name__, '[autoparams]') @profile def choose_vsmany_K(num_names, qaids, daids): ""...
import os from datetime import datetime import time import tempfile from stratuslab.CloudConnectorFactory import CloudConnectorFactory from stratuslab.Util import sshCmd from stratuslab.Util import sshCmdWithOutput from stratuslab.Util import waitUntilPingOrTimeout from stratuslab.Util import getHostnameFromUri import ...
"""Implicit-explicit time stepping routines for ODEs.""" import dataclasses from typing import Callable, Sequence, TypeVar import tree_math PyTreeState = TypeVar("PyTreeState") TimeStepFn = Callable[[PyTreeState], PyTreeState] class ImplicitExplicitODE: """Describes a set of ODEs with implicit & explicit terms. The...
import logging import pickle from typing import Dict, Optional, Union, List, Sequence from ray.tune.result import DEFAULT_METRIC from ray.tune.sample import Categorical, Domain, Float, Integer, LogUniform, \ Quantized from ray.tune.suggest.suggestion import UNRESOLVED_SEARCH_SPACE, \ UNDEFINED_METRIC_MODE, UNDE...
""" ou are given two integer arrays, A and B, each containing N integers. The size of the array is less than or equal to 1000. You are free to permute the order of the elements in the arrays. Now here's the real question: Is there an permutation A', B' possible of A and B, such that, A'i+B'i >= K for all i, where A'i d...
import boto3 import shutil import zipfile from zipfile import ZipFile, ZipInfo import os import tempfile import time import threading from os.path import join from botocore.client import Config class JobPoller: def __init__(self, action_type_id, builder): self._action_type_id = action_type_id self._...
from __future__ import annotations from edb.common import ordered from .. import common from . import base class Record(type): def __new__(mcls, name, fields, default=None): dct = {'_fields___': fields, '_default___': default} bases = (RecordBase, ) return super(Record, mcls).__new__(mcls, n...
"""Reacher domain.""" import collections from dm_control import mujoco from dm_control.rl import control from dm_control.suite import base from dm_control.suite import common from dm_control.suite.utils import randomizers from dm_control.utils import containers from dm_control.utils import rewards import numpy as np SU...
from heapq import * class Solution: def kthSmallest(self, matrix, k): """ :type matrix: List[List[int]] :type k: int :rtype: int """ # heapq.merge: Merge multiple sorted inputs into a single sorted output # (for example, merge timestamped entries from multiple...
raise DeprecationWarning("This file has been renamed to `fractional_gpus.py` " "in the same folder!")
from os.path import join, exists from itertools import product import re import numpy as np from PIL import Image import tensorflow as tf tf.compat.v1.enable_eager_execution() import xiuminglib as xm from util import logging as logutil, io as ioutil from .base import Dataset as BaseDataset logger = logutil.Logger(logge...
import numpy as np from ._utils import move_axis_to_end, suppress_warnings def brier_score(observations, forecasts): """ Calculate the Brier score (BS) The Brier score (BS) scores binary forecasts $k \in \{0, 1\}$, ..math: BS(p, k) = (p_1 - k)^2, where $p_1$ is the forecast probability of $k...
from oslo_serialization import jsonutils from nailgun import consts from nailgun import objects from nailgun.db.sqlalchemy.models import Node from nailgun.test.base import BaseIntegrationTest from nailgun.test.base import fake_tasks from nailgun.utils import reverse class TestHandlers(BaseIntegrationTest): def test...
try: import exceptions except ImportError: # Python 3 import builtins as exceptions class ObjectToReturn: def __init__(self, name): self.name = name def __str__(self): return self.name def exception(self, name, msg=""): exception = getattr(exceptions, name) raise exce...
''' Profile Formula Validation is an example of a plug-in to GUI menu that will profile formula execution. (c) Copyright 2012 Mark V Systems Limited, All rights reserved. ''' import os from tkinter import simpledialog, messagebox def profileFormulaMenuEntender(cntlr, menu): # Extend menu with an item for the profil...
__source__ = 'https://leetcode.com/problems/verify-preorder-sequence-in-binary-search-tree/description/' import unittest class Solution: # @param {integer[]} preorder # @return {boolean} def verifyPreorder(self, preorder): low = float("-inf") i = -1 for p in preorder: if ...
from django.contrib.auth import get_user_model from rest_framework.fields import CharField from rest_framework.serializers import ModelSerializer from grandchallenge.challenges.models import Challenge from grandchallenge.components.serializers import ( ComponentInterfaceValueSerializer, ) from grandchallenge.evalua...
import gzip import logging import os import shutil import uuid from PIL import Image from zipfile import ZipFile import pandas as pd import numpy as np import pyresample as pr from trollvalidation.validations import configuration as cfg LOG = logging.getLogger(__name__) class TmpFiles(object): """docstring for TmpF...
import logging import config import os class DummyMPLogHandler(logging.Handler): """DummyMP logging handler to allow multiprocess logging. This class is a custom logging handler to allow spawned processes (from :py:mod:`multiprocessing`) to log without any issues. This works by intercepting emitted log ...
"""Adds an ad customizer feed. Associates the feed with customer and adds an ad that uses the feed to populate dynamic data. """ from datetime import datetime from uuid import uuid4 from googleads import adwords from googleads import errors FEED_NAME = 'Interplanetary Feed Name %s' % uuid4() ADGROUPS = [ 'INSERT_AD...
import socket import threading bind_ip = "" bind_port = 60007 server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind((bind_ip, bind_port)) server.listen(5) print("[*] Listening on %s:%d" % (bind_ip, bind_port)) def handle_client(client_socket): request = client_socket.recv(1024).decode() print("...
""" command line application and sample code for granting access to a secret. """ import argparse def iam_grant_access(project_id, secret_id, member): """ Grant the given member access to a secret. """ # Import the Secret Manager client library. from google.cloud import secretmanager # Create th...
from akara.dist import setup setup(name="basic", version="1.0", akara_extensions=["blah.py"] )
""" *** Deprecated Model Builder functionality *** Supports functional algorithm calls found in the top-level h2o module. Current modeling is performed via estimator fitting (see estimators sub module for details) """ from connection import H2OConnection from frame import H2OFrame from job import H2OJob imp...
import os def run(cmd, decoding = None, clean = False): if cmd: result = [] output = os.popen(cmd).readlines() for line in output: if decoding: line = line.decode(decoding) if clean: line = line.strip() if line and line != '...
from __future__ import annotations import pytest from pants.core.util_rules import config_files, source_files from pants.core.util_rules.external_tool import rules as external_tool_rules from pants.engine.fs import FileDigest from pants.engine.internals.scheduler import ExecutionError from pants.jvm.resolve.coursier_fe...
""" Support for HomeMatic devices. For more details about this component, please refer to the documentation at https://home-assistant.io/components/homematic/ """ import asyncio from datetime import timedelta from functools import partial import logging import os import socket import voluptuous as vol from homeassistan...
from JumpScale import j class Specbase(j.tools.code.classGetBase()): def __init__(self, linenr): self.name = "" self.description = "" self.tags = "" self.comment = "" self.linenr = linenr def addDefaults(self): pass def getDefaultValue(self, type, value): ...
""" equip.analysis.dataflow.lattice ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The base lattice implementation (mostly used as semi-lattice). :copyright: (c) 2014 by Romain Gaucher (@rgaucher) :license: Apache 2, see LICENSE for more details. """ class Lattice(object): """ Interface for a lattice element. Practica...
""" Common Policy Engine Implementation Policies can be expressed in one of two forms: A list of lists, or a string written in the new policy language. In the list-of-lists representation, each check inside the innermost list is combined as with an "and" conjunction--for that check to pass, all the specified checks mus...
from model.group import Group def test_add_group(app): old_groups = app.group.get_group_list() group = Group(name="hjhj", header="jhjh", footer="jhjjhhj") app.group.create(group) new_groups = app.group.get_group_list() assert len(old_groups) + 1 == len(new_groups) old_groups.append(group) as...
import pytest import salt.states.openvswitch_port as openvswitch_port from tests.support.mock import MagicMock, patch @pytest.fixture def configure_loader_modules(): return {openvswitch_port: {"__opts__": {"test": False}}} def test_present(): """ Test to verify that the named port exists on bridge, eventual...
import urllib import urllib2 import json import sys import logging import datetime from datetime import datetime import time import re logger = logging.getLogger("sensei_components") PARAM_OFFSET = "start" PARAM_COUNT = "rows" PARAM_QUERY = "q" PARAM_QUERY_PARAM = "qparam" PARAM_SORT = "sort" PARAM_SORT_ASC = "asc" PAR...
from MenderAPI import * class Inventory(): auth = None def __init__(self, auth): self.reset() self.auth = auth def reset(self): # Reset all temporary values. pass def get_inv_base_path(self): return "https://%s/api/management/%s/inventory/" % (get_mender_gateway()...
from . import TestScaleBase class TestScaleCompute(TestScaleBase): def test_compute_scale_in_compute(self): expectations = self.deploy_app('scale4') expectations['compute']['new']['install'] = 3 self.deployment_assertions(expectations) expectations = self.scale(parameters={ ...
"""Test for the ee.__init__ file.""" import six import unittest import ee from ee import apitestcase class EETestCase(apitestcase.ApiTestCase): def setUp(self): ee.Reset() def testInitialization(self): """Verifies library initialization.""" def MockSend(path, params, unused_method=None, unused_raw=None)...
"""Tests for nitroml.automl.metalearning.metalearner.component.""" from absl.testing import absltest from nitroml.automl.metalearning import artifacts from nitroml.automl.metalearning.metalearner.component import MetaLearner from tfx.types import channel_utils from tfx.types import standard_artifacts class ComponentTes...
"""Run 'adb devices' and show results in friendly way. Runs 'adb devices' and integrates the results with environment variables DEVTAGS and ANDROID_SERIAL to show model numbers for connected devices. """ import getopt import os import re import sys import script_utils as u valid_dispositions = {"device": 1, ...
import os import json import logging _DEFAULT_CONFIG_DIR = "config" _DEFAULT_CONFIG_NAME = "config.json" _DEFAULT_LOG_CONFIG_NAME = "default_log.json" def load(path): json_content = _load_json(path) logging.info("loaded configuration from [ %s ]", path) config = Configuration(json_content) return config...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import functools import json import os import subprocess import shutil import sys import tempfile import time import numpy as np import tensorflow as tf from tensorflow.python.eager import def_fu...
"""Test config flow.""" from unittest.mock import Mock, patch from homeassistant.components.hassio.handler import HassioAPIError from homeassistant.const import EVENT_HOMEASSISTANT_START from homeassistant.setup import async_setup_component from tests.common import mock_coro async def test_hassio_discovery_startup(hass...
import sys import numpy as np class ChromStats(object): def __init__(self): self.n = 0 self.n_nan = 0 self.sum = 0 self.min = None self.max = None def mean(self): """Calculates mean of sites that are not nan on this chromsome""" n = self.n - self.n...
""" Routines to compute RMSD of all PROT_IND_ files These routines were developed by: Rodrigo Antonio Faccioli - rodrigo.faccioli@usp.br / rodrigo.faccioli@gmail.com Leandro Oliveira Bortot - leandro.bortot@usp.br / leandro.obt@gmail.com """ import os import sys from collections import OrderedDict nati...