filename
stringlengths
13
19
text
stringlengths
134
1.04M
the-stack_0_12945
# Copyright (c) OpenMMLab. All rights reserved. import torch.nn as nn from mmcls.models.builder import NECKS from mmcls.models.necks import GlobalAveragePooling as _GlobalAveragePooling @NECKS.register_module(force=True) class GlobalAveragePooling(_GlobalAveragePooling): """Global Average Pooling neck. Note ...
the-stack_0_12946
# Copyright 2019 Capital One Services, LLC # Copyright The Cloud Custodian Authors. # SPDX-License-Identifier: Apache-2.0 from gcp_common import BaseTest, event_data class MLModelTest(BaseTest): def test_models_query(self): project_id = "cloud-custodian" session_factory = self.replay_flight_dat...
the-stack_0_12949
""" Provides install path infomation. """ import os from esys.lsm.util.pathSearcher import PathSearcher installDir = "/home/daniel/Documents/fing/esys-particle/src/danielfrascarelli-git/esys-particle" binDir = os.path.join(installDir, "bin") libDir = os.path.join(installDir, "lib") pythonPkgDir = "/home...
the-stack_0_12950
from raptiformica.actions.slave import assimilate_machine from tests.testcase import TestCase class TestAssimilateMachine(TestCase): def setUp(self): self.log = self.set_up_patch('raptiformica.actions.slave.log') self.download_artifacts = self.set_up_patch('raptiformica.actions.slave.download_arti...
the-stack_0_12951
import unittest from six.moves import StringIO import time from robot import utils from robot.utils.asserts import * from robot.output.filelogger import FileLogger from robot.utils.robottime import TimestampCache class _FakeTimeCache(TimestampCache): def __init__(self): self.fake = time.mktime((2006, 6...
the-stack_0_12952
#!/usr/bin/env python3 _DEFAULT_DEPENDENCIES = [ "packages/data/**/*", "packages/common/**/*", "packages/course-landing/**/*", "packages/{{site}}/**/*", "yarn.lock", ] _COURSE_LANDING_DEPENDENCIES = [ "packages/data/training/sessions.yml", "packages/data/training/recommendations/**/*", ...
the-stack_0_12954
#!/usr/bin/env python3.4 """ kill_python.py, copyright (c) 2015 by Stefan Lehmann """ import os import psutil PROC = "python.exe" my_pid = os.getpid() i = 0 for p in psutil.process_iter(): if p.name() == PROC and p.pid != my_pid: i += 1 p.kill() print("Killed {} instances of process '{}'.".forma...
the-stack_0_12955
"""Common configure functions for vlan""" # Python import logging # Unicon from unicon.core.errors import SubCommandFailure # Genie from genie.metaparser.util.exceptions import SchemaEmptyParserError log = logging.getLogger(__name__) def config_vlan(device, vlanid): """ Configures a VLAN on Interface or Devic...
the-stack_0_12956
# Copyright 2016 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 a...
the-stack_0_12958
""" -*- coding: utf-8 -*- @github{ title = {KoSpeech: Open Source Project for Korean End-to-End Automatic Speech Recognition in PyTorch}, author = {Soohwan Kim, Seyoung Bae, Cheolhwang Won, Suwon Park}, link = {https://github.com/sooftware/KoSpeech}, year = {2020} } """ import sys import argparse import random...
the-stack_0_12959
#!/usr/bin/env python # -*- coding: iso-8859-15 -*- from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.api.urlfetch import DownloadError from library import login from boto.ec2.connection import * class AlleVolumesLoeschenDefinitiv(webapp.RequestHandler): def ge...
the-stack_0_12961
import json from collections import defaultdict from typing import List from sqlalchemy import desc from sqlalchemy.future import select from app.crud.test_case.ConstructorDao import ConstructorDao from app.crud.test_case.TestCaseAssertsDao import TestCaseAssertsDao from app.crud.test_case.TestCaseDirectory import Pi...
the-stack_0_12962
from django.conf.urls.defaults import * # Uncomment the next two lines to enable the admin: #from django.contrib import admin #admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^blog/', include('blog.foo.urls')), (r'^$', 'Account.views.index'), (r'^test/$', 'Account.views.test'), (r...
the-stack_0_12963
import pandas as pd import numpy as np import os import json from datetime import date def getFilename(subject_data): """ Given the subject_data field from a row of one of our SpaceFluff dataframes, extract the name of the object being classified by extracting the 'Filename'|'image'|'IMAGE' field". To...
the-stack_0_12964
from __future__ import absolute_import, print_function, unicode_literals import re import sys from django.conf import settings as django_settings from django.http import Http404, HttpResponseRedirect from django.utils.cache import add_never_cache_headers def redirect_request_processor(page, request): """ Re...
the-stack_0_12965
import requests from data import ui def consultar(token='25d800a8b8e8b99d77c809567aa291b8',self=0): Sair = False while(Sair == False): if self == 1: ip_input = '' else: ip_input = ui.input_dialog() if len(ip_input) < 1: ui.error_dialog('Insira ...
the-stack_0_12966
from typing import List, Tuple from chiabip158 import PyBIP158 from cryptodoge.types.blockchain_format.coin import Coin from cryptodoge.types.blockchain_format.sized_bytes import bytes32 from cryptodoge.types.full_block import FullBlock from cryptodoge.types.header_block import HeaderBlock from cryptodoge.types.name_p...
the-stack_0_12967
class A: def __init__(self, gpioPort): self.gpioPort = gpioPort def p(self): print(self.gpioPort) class B(A): pass B(12).p() C = type('C', (A,), dict({})) print(C) C(14).p() def value(value=None): if value == None: return 'get_value' else: ...
the-stack_0_12968
#!/usr/bin/python # -*- coding: utf-8 -*- """ Basic classes to contain rstWeb objects and methods to calculate their attributes Author: Amir Zeldes """ class NODE: def __init__(self, id, left, right, parent, depth, kind, text, relname, relkind): """Basic class to hold all nodes (EDU, span and multinuc) in structu...
the-stack_0_12972
import jax from jax import numpy as jnp # import numpy as np from tabcorr.tabcorr import * class JaxTabCorr(TabCorr): def predict(self, model, separate_gal_type=False, **occ_kwargs): """ Predicts the number density and correlation function for a certain model. Parameters -...
the-stack_0_12973
import datetime class Employee: raise_amount = 1.04 # Class variable num_of_employees = 0 def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = first + '.' + last + '@company.com' Employee.num_of_employees += 1 ...
the-stack_0_12975
# # Handler library for Linux IaaS # # Copyright 2014 Microsoft Corporation # # 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 requi...
the-stack_0_12976
""" Contains all the config for the Flask App """ import os class BaseConfig: """ Base configuration """ TESTING = False SQLALCHEMY_TRACK_MODIFICATIONS = False SECRET_KEY = os.environ.get('SECRET_KEY') DEBUG_TB_ENABLED = False DEBUG_TB_INTERCEPT_REDIRECTS = False BCRYPT_LOG_ROUNDS ...
the-stack_0_12977
from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.keras import backend as K from tensorflow.keras import initializers, regularizers, constraints from tensorflow.keras.layers import Layer, InputSpec from tensorflow.python.keras.utils import...
the-stack_0_12978
import numpy as np from keras_cn_parser_and_analyzer.library.classifiers.cnn_lstm import WordVecCnnLstm from keras_cn_parser_and_analyzer.library.utility.simple_data_loader import load_text_label_pairs from keras_cn_parser_and_analyzer.library.utility.text_fit import fit_text def main(): random_state = 42 np...
the-stack_0_12979
# https://www.hackerrank.com/challenges/xor-se/problem # An array, , is defined as follows: # A[0] = 0 # A[x] = A[x-1]^x # for , where is the symbol for XOR # You will be given a left and right index . You must determine the XOR sum of the segment of A as # A[l]^A[l+1]...^A[r]. # For example, A = [0,1,3,0,4,1,7,0,8] . ...
the-stack_0_12980
from . import DATABASE, log import os from flask import Blueprint, render_template, flash from flask_login import login_required, current_user views = Blueprint("views", __name__) @views.route("/") @views.route("/home") @login_required def home(): log.debug("Received a GET request at `/home`") return render_...
the-stack_0_12982
"""MLP Merge Model. A model composed only of a multi-layer perceptron (MLP), which maps real-valued inputs to real-valued outputs. This model is called an MLP Merge Model because it takes two inputs and concatenates the second input with the layer at a specified index. It can be merged with any layer from the input la...
the-stack_0_12983
"""A setuptools based setup module. See: https://packaging.python.org/en/latest/distributing.html https://github.com/pypa/sampleproject """ # Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path import os import ...
the-stack_0_12984
import random import pytest import numpy as np import os from ray import cloudpickle as pickle from ray import ray_constants from ray.actor import ActorClassInheritanceException try: import pytest_timeout except ImportError: pytest_timeout = None import sys import tempfile import datetime from ray._private.te...
the-stack_0_12985
#!/usr/bin/env python # --------------------------------------------------------------------------------------- # configure.py: Athena++ configuration script in python. Original version by CJW. # # When configure.py is run, it uses the command line options and default settings to # create custom versions of the files M...
the-stack_0_12988
import tensorflow as tf from tensorflow.python.ops.array_ops import fake_quant_with_min_max_vars a = tf.Variable([0.0, 0.1, 0.3, 0.49, 0.5, 0.8, 1.1, 1.23, 1.49, 1.5, 1.51, 2.0]) qa = fake_quant_with_min_max_vars(a, tf.reduce_min(a), tf.reduce_max(a), num_bits=3, narrow_range=False) sess = tf.Session() sess.run(tf.g...
the-stack_0_12992
from kapteyn import maputils from matplotlib import pyplot as plt from kapteyn import tabarray import numpy # Get a header and change some values f = maputils.FITSimage("m101.fits") header = f.hdr header['CDELT1'] = 0.1 header['CDELT2'] = 0.1 header['CRVAL1'] = 285 header['CRVAL2'] = 20 # Use the changed header as ex...
the-stack_0_12993
#Simple Linear Regression #import libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt #Read data dataset = pd.read_csv('Salary_Data.csv') x = dataset.iloc[:,:-1].values y = dataset.iloc[:,1].values #Splitting data from sklearn.model_selection import train_test_split X_train, X_test, Y_tr...
the-stack_0_12996
#!/usr/bin/env python """Strictly for loading agents to inspect. Based on `main.py`.""" import datetime import os import time import argparse import cv2 import pickle import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from os.path import join from ravens import Dataset, Environment, cameras, ag...
the-stack_0_12997
"""Test zipfile compat. """ import inspect import sys import zipfile import pytest import rarfile # dont fail on new python by default _VERS = [(3, 6), (3, 7), (3, 8)] _UNSUPPORTED = sys.version_info[:2] not in _VERS _ignore = set([ "detach", "peek", "read1", "readinto1", "seek", # no kw...
the-stack_0_12998
# ##### BEGIN GPL LICENSE BLOCK ##### # # 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) any later version. # # This program is distrib...
the-stack_0_12999
"""Redis cache backend.""" import random import re from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache from django.core.serializers.base import PickleSerializer from django.utils.functional import cached_property from django.utils.module_loading import import_string class RedisSerializer(PickleSe...
the-stack_0_13003
import datetime from functools import partial import numpy as np import regex as re import toolz from multipledispatch import Dispatcher import ibis import ibis.common.exceptions as com import ibis.expr.datatypes as dt import ibis.expr.lineage as lin import ibis.expr.operations as ops import ibis.expr.types as ir imp...
the-stack_0_13007
import re # io.open is needed for projects that support Python 2.7 # It ensures open() defaults to text mode with universal newlines, # and accepts an argument to specify the text encoding # Python 3 only projects can skip this import and use built-in open() from io import open as io_open from os import path from setu...
the-stack_0_13010
"""Support for OASA Telematics from telematics.oasa.gr.""" from datetime import timedelta import logging from operator import itemgetter import oasatelematics import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import ATTR_ATTRIBUTION, CONF_NAME,...
the-stack_0_13012
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import json import logging import os import torch import torch.nn as nn import torch.nn.functional as F import apex # pylint: disable=import-error from apex.parallel import DistributedDataParallel # pylint: disable=import-error from .mutator i...
the-stack_0_13013
import tensorflow as tf from tensorflow.keras import Model import tensorflow_addons as tfa from tensorflow.keras.layers import Dense, Dropout, LayerNormalization, Layer def create_padding_mask(input): """ Creates mask for input to Transformer based on the average of all elements = 0 :param input: input se...
the-stack_0_13016
import simplejson import string import time import traceback import logging import requests ID="api" #this is our command identifier, so with conventional commands, this is the command name permission=0 #Min permission required to run the command (needs to be 0 as our lowest command is 0) import collections def updat...
the-stack_0_13018
# -*- coding: utf-8 -*- #!/usr/bin/python import os import sys import json import argparse import re import requests import codecs from configparser import ConfigParser from distutils.version import LooseVersion # Hackety Hack. Puc mantenir el prestapyt com a submodul i buscar la lib dins d'aquest. # git submodule a...
the-stack_0_13019
import requests import urllib.request import time import urllib import re import csv import sys from bs4 import BeautifulSoup def uni_montreal(): url = "https://diro.umontreal.ca/english/departement-directory/professors/" r = requests.get(url) # request to url ...
the-stack_0_13020
# Friends again # # March 15, 2019 # By Robin Nash import sys def getCircle(friend, pairs, circle): circle.append(pairs[circle[-1]]) last = circle[-1] if last == circle[0]: return circle[:-1] if last in circle[:-1]: return circle[circle.index(last):-1] return get...
the-stack_0_13021
from rest_framework.permissions import BasePermission from environments.models import Environment from environments.permissions.constants import UPDATE_FEATURE_STATE from projects.models import Project ACTION_PERMISSIONS_MAP = { "retrieve": "VIEW_PROJECT", "destroy": "DELETE_FEATURE", "list": "VIEW_PROJEC...
the-stack_0_13023
import unittest import sys sys.path.append("../src/") from merge_sort_without_sentinel import merge_sort class TestMergeSortWithoutSentinel(unittest.TestCase): def test_merge_sort_already_sorted(self): A = [1, 2, 3, 4, 5, 6] merge_sort(A) self.assertEqual(A, [1, 2, 3, 4, 5, 6]) def te...
the-stack_0_13024
# -*- coding: utf-8 -*- import sys import warnings from pathlib import Path PROJECT_DIR = Path(__file__).resolve().parent if str(PROJECT_DIR.parent) not in sys.path: sys.path.insert(0, str(PROJECT_DIR.parent)) warnings.filterwarnings( "ignore", category=FutureWarning, module="sklearn.utils.deprecation" ) from...
the-stack_0_13025
import sys import pytest from dagster import file_relative_path, lambda_solid, pipeline, repository from dagster.core.definitions.repository_definition import RepositoryData from dagster.core.test_utils import instance_for_test from dagster.core.types.loadable_target_origin import LoadableTargetOrigin from dagster.co...
the-stack_0_13026
# coding=utf-8 # Copyright 2018 The TF-Agents Authors. # # 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...
the-stack_0_13028
""" Simple iOS tests, showing accessing elements and getting/setting text from them. """ import unittest import os from random import randint from appium import webdriver from time import sleep class SimpleIOSTests(unittest.TestCase): def setUp(self): # set up appium app = os.path.abspath('../../a...
the-stack_0_13029
# Copyright (c) 2015 Infoblox 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 require...
the-stack_0_13032
#!/usr/bin/python # # Copyright 2014 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 b...
the-stack_0_13034
import os import sys import argparse import logging from tqdm.notebook import tqdm import time import numpy as np import matplotlib.pyplot as plt import torch import shutil import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import transformers from config.configs import set_...
the-stack_0_13037
from purbeurre.models import Product from django.db.models import Q from collections import Counter class DatabaseSearch: """This class's job is to find categories concerned by the user research and return the best products (in terms of nutri-score) of each category.""" def get_substitutes_per_category(s...
the-stack_0_13038
import datetime from typing import Union, Optional import discord from discord.ext import commands async def trigger_role(member: discord.Member, role: Union[discord.Role, int, str], guild: Optional[discord.Guild] = None) -> bool: """ Triggers a role on a member. If member already has `role` then role i...
the-stack_0_13039
#! /usr/bin/python # -*- coding: utf-8 -*- """Server of Rock Paper Scissor game (2 players).""" from socketserver import BaseRequestHandler, TCPServer __author__ = 'fyabc' ADDRESS = 'localhost', 20000 MSG_SIZE = 8192 class RpsHandler(BaseRequestHandler): def handle(self): print('Get connection from', ...
the-stack_0_13040
#!/usr/bin/env python3 # coding=utf-8 # 导入相关系统包 import requests import base64 import zipfile import configparser import socket import ping3 import re import os from prettytable import PrettyTable from colorama import init, Fore, Back, Style class DrawTable(object): '''工具类,打印表格格式化''' def __init__(self): ...
the-stack_0_13041
#!/usr/bin/env python3 # # aiohttp documentation build configuration file, created by # sphinx-quickstart on Wed Mar 5 12:35:35 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # Al...
the-stack_0_13042
# Copyright (c) OpenMMLab. All rights reserved. import asyncio from argparse import ArgumentParser from mmdet.apis import (async_inference_detector, inference_detector, init_detector, show_result_pyplot) def parse_args(): parser = ArgumentParser() parser.add_argument('img', help='Imag...
the-stack_0_13044
# -*- coding: utf-8 -*- from model.group import Group import allure # def test_add_group(app, db, json_groups, check_ui): # group = json_groups # old_groups = db.get_group_list() # app.group_helper.creation(group) # new_groups = db.get_group_list() # old_groups.append(group) # if check_ui: # ...
the-stack_0_13045
class TreeNode(object): def __init__(self, val): self.val = val self.left = None self.right = None self.height = 1 class AVL_Tree(object): def insert(self, root, key): if not root: return TreeNode(key) elif key < root.val: root.left = se...
the-stack_0_13046
import sys sys.path.append('../../..') from fastNLP import cache_results from reproduction.sequence_labelling.cws.data.cws_shift_pipe import CWSShiftRelayPipe from reproduction.sequence_labelling.cws.model.bilstm_shift_relay import ShiftRelayCWSModel from fastNLP import Trainer from torch.optim import Adam from fastN...
the-stack_0_13047
from openpyxl import load_workbook from openpyxl.utils import get_column_letter from itertools import islice from datetime import datetime import pandas as pd import streamlit as st import logging import os files = os.listdir('./data') workbooks = [item for item in files if '.xlsx' in item] logging.basicConfig(filena...
the-stack_0_13048
try: from setuptools import setup from setuptools import find_packages packages = find_packages() except ImportError: from distutils.core import setup import os packages = [x.strip('./').replace('/','.') for x in os.popen('find -name "__init__.py" | xargs -n1 dirname').read().strip().split('\n')...
the-stack_0_13050
import os import csv from typing import Tuple, Union from pathlib import Path import torchaudio from torchaudio.datasets.utils import download_url, extract_archive from torch import Tensor from torch.utils.data import Dataset _RELEASE_CONFIGS = { "release1": { "folder_in_archive": "wavs", "url": "...
the-stack_0_13051
import random import string from dpaster import core from tests.fixtures import python_code def test_get_syntax_stdin(python_code): assert "python" in core.get_syntax("<stdin>", python_code) def test_get_syntax_java_file(): assert core.get_syntax("HelloWorld.java", "") == "java" def test_get_syntax_weird...
the-stack_0_13055
""" Some utilities and things for testing various bits of SMPP. """ from twisted.internet.defer import DeferredQueue from smpp.pdu_inspector import unpack_pdu from vumi.transports.smpp.clientserver.server import SmscServer class SmscTestServer(SmscServer): """ SMSC subclass that records inbound and outbound...
the-stack_0_13057
from __future__ import absolute_import from datetime import datetime import pytz from django.views.generic import View from sentry.models import ( Commit, CommitAuthor, GroupSubscriptionReason, Organization, Project, Release, Team ) from sentry.utils.http import absolute_uri from .mail import MailPreview ...
the-stack_0_13058
# Copyright 2016 The TensorFlow Authors. 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 applica...
the-stack_0_13059
# Copyright 2016 - Nokia # # 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, sof...
the-stack_0_13061
import argparse import os def parse_args(args) -> argparse.Namespace: parser = argparse.ArgumentParser(description='Make submission') parser.add_argument( '-i', '--input', help='path to input file', type=str, required=True ) parser.add_argument( '-o', '--output'...
the-stack_0_13062
import asyncio import traceback import os import logging import sys from pathlib import Path from typing import Any, Dict, Optional from chives.plotting.create_plots import resolve_plot_keys from chives.plotters.plotters_util import run_plotter, run_command log = logging.getLogger(__name__) MADMAX_PLOTTER_DIR = "ma...
the-stack_0_13063
import json from ..constants.path import get_cache_path from ..Utils.decorators import change_working_directory, cache_data from ..Utils.utils import search from .text import TextEntityAnnotation TASK_TYPE = { 'TextEntityAnnotation':TextEntityAnnotation } @change_working_directory @cache_data def list_datasets(*...
the-stack_0_13064
from setuptools import setup import os from codecs import open with open('README.rst', 'r', 'utf-8') as f: readme = f.read() here = os.path.abspath(os.path.dirname(__file__)) about = {} with open(os.path.join(here, 'inputimeout', '__version__.py'), 'r', 'utf-8') as f: exec(f.read(), about) tests_...
the-stack_0_13065
import atexit import glob import logging import numpy as np import os import subprocess from typing import Dict, List, Optional, Any from mlagents_envs.side_channel.side_channel import SideChannel from mlagents_envs.base_env import ( BaseEnv, BatchedStepResult, AgentGroupSpec, AgentGroup, AgentId,...
the-stack_0_13066
#! /usr/bin/env python2 # # This file is part of khmer, http://github.com/ged-lab/khmer/, and is # Copyright (C) Michigan State University, 2009-2015. It is licensed under # the three-clause BSD license; see doc/LICENSE.txt. # Contact: khmer-project@idyll.org # # pylint: disable=invalid-name,missing-docstring """ Take ...
the-stack_0_13068
import collections from packaging.version import Version import inspect import logging from numbers import Number import numpy as np import time import warnings from mlflow.tracking.client import MlflowClient from mlflow.utils.file_utils import TempDir from mlflow.utils.mlflow_tags import MLFLOW_PARENT_RUN_ID from mlf...
the-stack_0_13069
import json import threading import time import os import stat from copy import deepcopy from .util import user_dir, print_error, print_stderr, PrintError from .bitcoin import MAX_FEE_RATE, FEE_TARGETS SYSTEM_CONFIG_PATH = "/etc/electrum.conf" config = None def get_config(): global config return config ...
the-stack_0_13071
""" Pulls data from specified iLO and presents as Prometheus metrics """ from __future__ import print_function from _socket import gaierror import sys import os import hpilo import time import prometheus_metrics from BaseHTTPServer import BaseHTTPRequestHandler from BaseHTTPServer import HTTPServer from SocketServer i...
the-stack_0_13073
""" Tests for the company model database migrations """ from django_test_migrations.contrib.unittest_case import MigratorTestCase from InvenTree import helpers class TestForwardMigrations(MigratorTestCase): migrate_from = ('company', helpers.getOldestMigrationFile('company')) migrate_to = ('company', helpe...
the-stack_0_13075
import unittest from siobrultech_protocols.gem import packets from tests.gem.packet_test_data import assert_packet, read_packet class TestPacketFormats(unittest.TestCase): def test_bin32_abs(self): check_packet("BIN32-ABS.bin", packets.BIN32_ABS) def test_bin32_net(self): check_packet("BIN32...
the-stack_0_13076
import sys, time, cv2 from matplotlib import pyplot as plt sys.path.insert(0, sys.path[0].replace('examples', 'src')) from robot import Robot from utils import * def display_image(image): """ Displays a image with matplotlib. Args: image: The BGR image numpy array. See src/utils.py. ...
the-stack_0_13078
# this is chenqi's modification for custom datasets! # version 2: based on v1, do the following updates: # (1) in the func test(), instead of kNN on class, do kNN on img index! <-- then each image represents a class during implementation. # (2) in data-aug for training, replace color jitter with Gaussian blur (+ Gaussi...
the-stack_0_13079
import pytest from mock import MagicMock from mock import AsyncMock from datetime import datetime from robot_server.service.dependencies import get_session_manager from robot_server.service.errors import RobotServerError from robot_server.service.session.errors import ( SessionCreationException, UnsupportedCommand...
the-stack_0_13082
from django.utils.deprecation import MiddlewareMixin#中间件基类 from django.core.cache import cache class CountMiddleware(MiddlewareMixin): #中间件类必须接受一个response参数,就是说必须在中间件类中定义一个__init__函数和一个__call__函数 #def __init__(self, get_response): #self.get_response = get_response #def __call__(self, request): #return self.get...
the-stack_0_13084
################################################################ ### various add-ons to the SciPy morphology package ################################################################ from numpy import * import pylab from pylab import * from scipy.ndimage import morphology,measurements,filters from scipy.ndimage.morph...
the-stack_0_13085
import os, sys, tempfile import datetime, time, re from seiscomp import mseedlite as mseed def _timeparse(t, format): """Parse a time string that might contain fractions of a second. Fractional seconds are supported using a fragile, miserable hack. Given a time string like '02:03:04.234234' and a for...
the-stack_0_13087
from tensorflow.keras.optimizers import Adam from tensorflow.keras.callbacks import TensorBoard, CSVLogger, ModelCheckpoint from lipnet.lipreading.generators import BasicGenerator from lipnet.lipreading.callbacks import Statistics, Visualize from lipnet.lipreading.curriculums import Curriculum from lipnet.core.decoders...
the-stack_0_13088
# -*- coding: utf-8 -*- import logging from . import config, models from .models.util import _fetch_data class Nvdb(object): """ The main class for interfacing with the API. :param client: Name of client using the API :type client: str :param contact: Contact information of user of the A...
the-stack_0_13089
import base64 import io import os import threading import time from typing import Optional, List from platypush import Config from platypush.context import get_bus from platypush.message.event.qrcode import QrcodeScannedEvent from platypush.message.response.qrcode import QrcodeGeneratedResponse, QrcodeDecodedResponse,...
the-stack_0_13090
from uuid import uuid4 from django.conf import settings try: from django.utils.deprecation import MiddlewareMixin except ImportError: # Django < 1.10 MiddlewareMixin = object from .locals import set_cid, get_cid, log_output class CidMiddleware(MiddlewareMixin): """ Middleware class to extract the c...
the-stack_0_13091
import numpy as np from numpy.random import normal from scipy.sparse import issparse import scipy.sparse.linalg as slinalg from scipy import linalg, stats __all__ = [ "quad_potential", "QuadPotentialDiag", "QuadPotentialDiagAdapt", "isquadpotential", "QuadPotentialLowRank", ] def quad_potential(...
the-stack_0_13093
# %% Load packages import matplotlib.patches as mpatches import matplotlib.pyplot as plt import numpy as np import pandas as pd from bnn_mcmc_examples.examples.mlp.noisy_xor.setting1.mcmc.constants import num_chains from bnn_mcmc_examples.examples.mlp.noisy_xor.setting1.mcmc.dataloaders import test_dataloader from bn...
the-stack_0_13094
from overwatch import app import xmltodict import asyncio import aiohttp loop = asyncio.get_event_loop() semaphore = asyncio.Semaphore(5) def fetch_urls(urls, parser): async def fetch(url): with (await semaphore): async with aiohttp.ClientSession() as session: async with sessi...
the-stack_0_13095
# -*- coding: utf-8 -*- import json from odoo import api, models, _ from odoo.tools import float_round class ReportBomStructure(models.AbstractModel): _name = 'report.mrp.report_bom_structure' _description = 'BOM Structure Report' @api.model def _get_report_values(self, docids, data=None): d...
the-stack_0_13096
# Copyright (c) SenseTime. All Rights Reserved. from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import argparse import logging import os import time import math import json import random import numpy as np import tor...
the-stack_0_13097
# Copyright 2020 MONAI Consortium # 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, s...