filename
stringlengths
13
19
text
stringlengths
134
1.04M
the-stack_0_5713
#!/usr/bin/env python """ requests_cache ~~~~~~~~~~~~~~ Transparent cache for ``requests`` library with persistence and async support Just write:: import requests_cache requests_cache.install_cache() And requests to resources will be cached for faster repeated access:: i...
the-stack_0_5714
# Copyright (c) 2021 PaddlePaddle 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 appli...
the-stack_0_5717
class Complex: def __init__(self, realpart, imagpart): self.r = realpart self.i = imagpart def add(self, addend): return Complex(self.r + addend.r, self.i + addend.i) def subtract(self, subtrahend): return Complex(self.r - subtrahend.r, self.i - subtrahend.i) def multi...
the-stack_0_5721
__author__ = 'jlegind' from urllib import parse, request import requests import json import collections import csv class SearchAPI(object): def __init__(self, url, read_path, write_path, suffix='', separator='\t'): """ :param url: JSON api url :param read_path: File that contains the sear...
the-stack_0_5722
from __future__ import unicode_literals import click import six from ..aliases import aliases_database from .base import cli @cli.command(name='clean-aliases', short_help="Remove aliases mapping to closed or inexistent " "activities.") @click.option('-y', '--yes', 'force_yes', i...
the-stack_0_5723
import glob import os from typing import List from torch import sigmoid import matplotlib.pyplot as plt import seaborn as sn import torch import wandb from pytorch_lightning import Callback, Trainer from pytorch_lightning.loggers import LoggerCollection, WandbLogger from sklearn import metrics from sklearn.metrics imp...
the-stack_0_5724
# -*- coding: utf-8 -*- import wtforms from flask import render_template, request, Markup, abort, flash, redirect, escape, url_for, make_response from .. import b__ as __ from .form import Form from .fields import SubmitField class ConfirmDeleteForm(Form): """ Confirm a delete operation """ # The lab...
the-stack_0_5725
import math import pytest from click.testing import CliRunner from r2b2.athena import Athena from r2b2.cli import cli from r2b2.contest import Contest from r2b2.contest import ContestType from r2b2.minerva import Minerva from r2b2.tests import util as util default_contest = util.generate_contest(10000) def test_si...
the-stack_0_5727
# Copyright 2021 Huawei Technologies Co., Ltd # # 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...
the-stack_0_5728
import os import sys import importlib # Setting the correct config file config_path = ".".join(["models", sys.argv[1]]) + "." if len(sys.argv) >= 2 else "" config = importlib.import_module(config_path + "config") output_FF_layers = [100, 2] #[4000, 1000, 100, 1] #[200, 200, 100, 100, 1] cur_work_dir = os.getcwd() d_m...
the-stack_0_5733
import sys import os.path from PyQt5 import QtWidgets, uic from PyQt5.QtCore import QThread, pyqtSlot from mychat_client.client import User from mychat_client.handlers import GuiReceiver try: addr = sys.argv[1] except IndexError: addr = 'localhost' try: port = int(sys.argv[2]) except IndexError: port =...
the-stack_0_5734
import torch.nn as nn import torch.nn.functional as F from layers import GraphSN import torch class GNN(torch.nn.Module): def __init__(self, input_dim, hidden_dim, output_dim, n_layers, batchnorm_dim, dropout_1, dropout_2): super().__init__() self.dropout = dropout_1 ...
the-stack_0_5737
import configparser import logging import os import warnings _logger = logging.getLogger(__name__) FILENAME = "jolly_brancher.ini" # CONFIG VARS KEYS_AND_PROMPTS = [ ["auth_email", "your login email for Atlassian"], ["base_url", "the base URL for Atlassian (e.g., https://cirrusv2x.atlassian.net)"], [ ...
the-stack_0_5739
if __name__ == '__main__': import numpy as np import pandas as pd import matplotlib.pyplot as plt import warnings warnings.filterwarnings("ignore") plt.style.use('ja') data_dir = '../IceCubeData/' mp = 1.0 nu_mass = 0.15 filename = 'mp' + str(mp) + 'mnu' + str(nu_mass) + '.csv' data = pd.read_csv(data_dir +...
the-stack_0_5740
""" Spin up an instance, run a single command, spin it down :-) Usage: run.py [options] -- <COMMAND> ... run.py [options] <COMMAND> ... Options: --type TYPE type, eg ng0 for bfboost, or ngd3 for dual Titan X [default: ng0] --image IMAGE image [default: s1] """ from __future__ import print_function impor...
the-stack_0_5741
from __future__ import print_function, division from sympy.core import S, C from sympy.core.compatibility import u from sympy.core.exprtools import factor_terms from sympy.core.function import (Function, Derivative, ArgumentIndexError, AppliedUndef) from sympy.core.logic import fuzzy_not from sympy.functions.eleme...
the-stack_0_5742
"""This module contains nodes for spectral analysis with Timeflux.""" import numpy as np import pandas as pd import xarray as xr from scipy.signal import welch from scipy.fft import fftfreq, rfftfreq, fft, rfft from timeflux.core.node import Node class FFT(Node): """Compute the one-dimensional discrete Fourier ...
the-stack_0_5744
# Copyright 2016 Medical Research Council Harwell. # # 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...
the-stack_0_5745
# Copyright 2012 Red Hat, Inc. # Copyright 2013 IBM Corp. # 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....
the-stack_0_5746
import KratosMultiphysics import KratosMultiphysics.StructuralMechanicsApplication as StructuralMechanicsApplication import KratosMultiphysics.KratosUnittest as KratosUnittest from math import sqrt, sin, cos, pi, exp, atan class TestComputeCenterOfGravity(KratosUnittest.TestCase): # muting the output KratosM...
the-stack_0_5747
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright 2013 Kitware Inc. # # Licensed under the Apache License, Version 2.0 ( the "License" ); # you may not use this file except in compliance with the License. # You may obtain a cop...
the-stack_0_5748
from transformers import AutoTokenizer, AutoModelWithLMHead import numpy as np from pathlib import Path import json import joblib def model_fn(model_dir): tokenizer = AutoTokenizer.from_pretrained("distilgpt2", cache_dir=model_dir) model = AutoModelWithLMHead.from_pretrained("distilgpt2", cache_dir=model_dir)...
the-stack_0_5751
#!/usr/bin/env python """ /proc/thedir """ from slashproc_parser.basic_parser import BasicSPParser class TheParser(BasicSPParser): THEDIR = "/proc/thedir" def __init__(self): super(TheParser, self).__init__(self) @staticmethod def get_groups(): """ REMOVE THIS DOCSTRING AND...
the-stack_0_5753
# -*- coding: utf-8 -* #!/usr/bin/python from dealctrl import * class deal_7_com(dealctrl): def __init__(self,con): dealctrl.__init__(self,con) def run(self): userid=int(self.recvdic['userid']) aid=int(self.recvdic['aid']) content=self.recvdic['content'] sql=("...
the-stack_0_5754
from __future__ import print_function import torch import torch.nn as nn import numpy as np import scipy import numbers import random from matplotlib import colors import matplotlib.patches as mpatches from statsmodels.nonparametric.kde import KDEUnivariate from PIL import ImageFilter from kornia import augmentation...
the-stack_0_5762
""" Author: Andreas Rössler """ import os import argparse import torch import pretrainedmodels import torch.nn as nn import torch.nn.functional as F from xception import xception import math import torchvision def return_pytorch04_xception(init_checkpoint=None): # Raises warning "src not broadcastable to dst" ...
the-stack_0_5764
from math import ceil # 入力 N, A, B = map(int, input().split()) h = [int(input()) for _ in range(N)] # 二分法により解を求める def bis(p, ok, ng): mid = (ok + ng) // 2 return ( ok if abs(ok - ng) == 1 else bis(p, mid, ng) if p(mid) else bis(p, ok, mid) ) ans = bis( lambda k: sum(max(0, c...
the-stack_0_5767
import requests as req import json from django.http import HttpResponseRedirect from django.urls import reverse from django.conf.urls import url from django.conf import settings from django.core.mail import send_mail client_id = settings.FENIX_CLIENT_ID clientSecret = settings.FENIX_CLIENT_SECRET redirect_uri = settin...
the-stack_0_5769
# coding: utf-8 """ Translator Knowledge Beacon Aggregator API This is the Translator Knowledge Beacon Aggregator web service application programming interface (API) that provides integrated access to a pool of knowledge sources publishing concepts and relations through the Translator Knowledge Beacon API. Th...
the-stack_0_5770
# Copyright 2021 Sony Group 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 required by applicable law or agreed to ...
the-stack_0_5771
""" Contains a class for logic of the Subjects. """ import os import logging import json import pkg_resources import mne import meggie.utilities.filemanager as filemanager from meggie.mainwindow.dynamic import find_all_datatype_specs class Subject: """ The class for holding subject-specific information an...
the-stack_0_5772
# Copyright (c) 2011 OpenStack Foundation. # 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...
the-stack_0_5775
# encoding: utf-8 """ Gherkin step implementations for chart features. """ from __future__ import absolute_import, print_function import hashlib from itertools import islice from behave import given, then, when from pptx import Presentation from pptx.chart.chart import Legend from pptx.chart.data import ( Bub...
the-stack_0_5779
# This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but ...
the-stack_0_5781
## Alarm Server ## Supporting Envisalink 2DS/3 ## ## This code is under the terms of the GPL v3 license. evl_Commands = { 'KeepAlive' : '000', 'StatusReport' : '001', 'DumpZoneTimers' : '008', 'PartitionKeypress' : '071', 'Disarm' : '040', 'ArmStay' : '031', 'ArmAway' : '030', 'ArmMax' ...
the-stack_0_5783
#!/usr/bin/env python # coding: utf-8 #takes as input a csv or tsv file, and a evalue cutoff, loads the data in pandas and fiters the dataframe by this value. #writes a clean csv/tsv file. If imported as library is able to take as input a pandas df and return a clean pandas df import pandas as pd from sys import argv ...
the-stack_0_5784
import os from flask import Flask, jsonify, request, abort from components import CardsView, Card, CardHeader app = Flask(__name__) @app.route("/", methods=['POST']) def index(): # process payload from archy payload = request.json.get('payload', {}) args = payload.get('args', {}) links = [{ ...
the-stack_0_5785
#!/usr/bin/env python3 import shutil import iterm2 async def main(connection): component = iterm2.StatusBarComponent( short_description="RootVolume Usage", detailed_description="Show Root Volume Usage", knobs=[], exemplar="[RootVolume Usage]", update_cadence=30, id...
the-stack_0_5786
#!/usr/bin/python3 # -*- coding:utf-8 -*- # Project: http://plankton-toolbox.org # Copyright (c) 2010-2018 SMHI, Swedish Meteorological and Hydrological Institute # License: MIT License (see LICENSE.txt or http://opensource.org/licenses/mit). import codecs import toolbox_utils import plankton_core class Im...
the-stack_0_5789
# Begin: Python 2/3 compatibility header small # Get Python 3 functionality: from __future__ import\ absolute_import, print_function, division, unicode_literals from future.utils import raise_with_traceback, raise_from # catch exception with: except Exception as e from builtins import range, map, zip, filter from i...
the-stack_0_5790
#------------------------------------------------------------------------------- # # Project: EOxServer <http://eoxserver.org> # Authors: Fabian Schindler <fabian.schindler@eox.at> # #------------------------------------------------------------------------------- # Copyright (C) 2011 EOX IT Services GmbH # # Permission...
the-stack_0_5792
# -*- coding: utf-8 -*- """ sentence, word, morph, ... __author__ = 'Jamie (jamie.lim@kakaocorp.com)' __copyright__ = 'Copyright (C) 2019-, Kakao Corp. All rights reserved.' """ ########### # imports # ########### import logging import re from typing import List, Tuple MAX_LEN = 64 ######### # types # ######### ...
the-stack_0_5793
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
the-stack_0_5796
""" Galaxy Metadata """ import copy import json import logging import os import shutil import sys import tempfile import weakref from collections import OrderedDict from collections.abc import Mapping from os.path import abspath from typing import Any, Iterator, Optional, TYPE_CHECKING, Union from sqlalchemy.orm impo...
the-stack_0_5798
#!/usr/bin/python from ansible.module_utils.opsmanager import ansible_setup if __name__ == '__main__': module, opsmanager = ansible_setup() group = opsmanager.get_group_by_name(module.params['cluster']) response = opsmanager.delete_maintenance(group) module.exit_json(changed=False, meta=response)
the-stack_0_5801
# Test script for opening and closing gate def main(robot): # Setup timestep = int(robot.getBasicTimeStep()) # Main loop, perform simulation steps until Webots is stopping the controller while robot.step(timestep) != -1: if not(gate_open := robot.gate.open()): print(gate_open)
the-stack_0_5804
import re import numpy as np import matplotlib.pyplot as plt def _plot_primitives_boxplots(log_file): with open(log_file, 'r') as file: lines = file.readlines() # read Primitives p = [re.findall('P=\d+', line) for line in lines] p = [v[0] for v in p if v] p = np.array([float(v.split('=')[...
the-stack_0_5805
"""Facilities for implementing hooks that call shell commands.""" from __future__ import print_function import logging import os from subprocess import Popen, PIPE from certbot import errors logger = logging.getLogger(__name__) def validate_hooks(config): """Check hook commands are executable.""" _validate...
the-stack_0_5806
from contextlib import AsyncExitStack from asyncpg import create_pool from fastapi import FastAPI from pytest import fixture from fastapi_pagination import LimitOffsetPage, Page, add_pagination from fastapi_pagination.ext.asyncpg import paginate from ..base import BasePaginationTestCase from ..utils import faker @...
the-stack_0_5807
# -*- coding=utf-8 -*- #Implmentation of anmm model based on bin sum input of QA matrix from __future__ import print_function from __future__ import absolute_import import keras import keras.backend as K from keras.models import Sequential, Model from keras.layers import * from keras.activations import softmax from m...
the-stack_0_5809
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. """Train a video classification model.""" import numpy as np import pprint import torch from fvcore.nn.precise_bn import get_bn_modules, update_bn_stats import slowfast.models.losses as losses import slowfast.models.optimi...
the-stack_0_5810
#------------------------------------------------------------------------------ # test_try.py #------------------------------------------------------------------------------ # BSD 3-Clause License # # Copyright (c) 2018, Affirm # All rights reserved. # # Redistribution and use in source and binary forms, with or withou...
the-stack_0_5813
# -*- coding: utf-8 -*- # Copyright 2020 Minh Nguyen (@dathudeptrai) # # 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 ...
the-stack_0_5814
## Main """ OpenAI gym execution. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import importlib import json import logging import os import time import sys from tensorforce import TensorForceError from tensorforce.agents import Age...
the-stack_0_5819
# Copyright 2019 DeepMind Technologies Ltd. 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 appl...
the-stack_0_5821
# 1080 n, m = map(int, input().split()) cnt = 0 normal = [list(map(int, list(input()))) for _ in range(n)] comp = [list(map(int, list(input()))) for _ in range(n)] def change(a, b): for i in range(a, a+3): for j in range(b, b+3): if normal[i][j] == 1: normal[i][j] = 0 ...
the-stack_0_5822
# Copyright 2018-2021 Streamlit Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wr...
the-stack_0_5823
#!env python from importlib import import_module import sys import logging logger = logging.getLogger('root') import canmatrix import os if sys.version_info > (3, 0): import io else: import StringIO moduleList = ["arxml", "cmcsv", "dbc", "dbf", "cmjson", "kcd", "fibex", "sym", "xls", "xlsx", "yam...
the-stack_0_5824
from functools import partial from urllib.parse import urlunsplit, urlencode from strava.base import RequestHandler from strava.constants import APPROVAL_PROMPT, SCOPE, DEFAULT_VERIFY_TOKEN from strava.helpers import BatchIterator, from_datetime_to_epoch class StravaApiClientV3(RequestHandler): api_path = 'api/v...
the-stack_0_5825
# Copyright (c) 2020 PaddlePaddle 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 appli...
the-stack_0_5828
# Copyright 2017, OpenCensus 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 or agreed to in w...
the-stack_0_5829
import os from aiohttp import web from aiohttp.test_utils import AioHTTPTestCase, unittest_run_loop from meross_iot.controller.device import HubDevice from meross_iot.manager import MerossManager from meross_iot.model.enums import OnlineStatus from tests import async_get_client if os.name == 'nt': import asyncio ...
the-stack_0_5830
import qiskit.quantum_info from qiskit.quantum_info.synthesis.xx_decompose import XXDecomposer import numpy as np from scipy.stats import unitary_group from monodromy.coverage import * from monodromy.static.examples import * from monodromy.haar import expected_cost import monodromy.render def default_zx_operation_c...
the-stack_0_5833
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
the-stack_0_5835
from _collections import deque males = [int(x) for x in input().split()] females = deque([int(x) for x in input().split()]) matches = 0 while males and females: current_female = females[0] current_male = males[-1] if current_female <= 0: females.popleft() elif current_male <= 0: males...
the-stack_0_5837
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst import fnmatch import time import re import datetime import warnings from collections import OrderedDict, defaultdict import numpy as np from astropy.utils.decorators import lazyproperty from astropy.utils.exceptions import Astro...
the-stack_0_5841
from __future__ import print_function import collections import logging from itertools import chain, product import math import random _logger = logging.getLogger(__name__) EvaluationConfig = collections.namedtuple('EvaluationConfig', ['num_samples', 'sample_size']) FORMAT_...
the-stack_0_5842
# Copyright 2020 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
the-stack_0_5843
from PIL import Image import pytesseract import argparse import os import time ap = argparse.ArgumentParser() ap.add_argument("-p", "--path", default="post", help="path of folder with images to be OCR'd, folder should not include another forlders") args = vars(ap.parse_args()) path=args["path"]+"/" pri...
the-stack_0_5845
# uncompyle6 version 3.2.0 # Python bytecode 2.4 (62061) # Decompiled from: Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)] # Embedded file name: pirates.piratesgui.BoardingPermissionPanel from pandac.PandaModules import * from direct.gui.DirectGui import DGG from pirates.piratesgu...
the-stack_0_5847
#{{{ Import import numpy as np pi = np.pi #}}} #{{{ Snell's Law def deflection_angle(theta, n1, n2, deg=True): """Calculate deflection angle according to Snell's law. Parameters ---------- theta : float Angle of incidence. n1 : float Refractive index of the first medium. n2 : ...
the-stack_0_5849
# -*- coding: utf-8 -*- """ Created on Fri Aug 16 14:52:14 2019 @author: Artemis """ """ import numpy as np import matplotlib.pyplot as plt line = np.linspace(-5, 5, 200) plt.plot(line, np.tanh(line), label='tanh') plt.plot(line, np.maximum(line, 0), label='relu') plt.legend(loc='best') plt.xlabel('x') plt.ylabel(...
the-stack_0_5851
from vdb.lib.npm import NpmSource from depscan.lib import config as config from depscan.lib.pkg_query import npm_metadata, pypi_metadata # Dict mapping project type to the audit source type_audit_map = {"nodejs": NpmSource(), "js": NpmSource()} # Dict mapping project type to risk audit risk_audit_map = { "nodejs...
the-stack_0_5853
import logging import datetime import xml.etree.cElementTree as ET import core from core.helpers import Url logging = logging.getLogger(__name__) ''' Does not supply rss feed -- backlog searches only. ''' def search(imdbid, term): proxy_enabled = core.CONFIG['Server']['Proxy']['enabled'] logging.info('Sear...
the-stack_0_5854
import torch from torch.testing._internal.common_utils import TestCase, run_tests from torch.utils._pytree import tree_flatten, tree_unflatten, TreeSpec, LeafSpec from torch.utils._pytree import _broadcast_to_and_flatten class TestPytree(TestCase): def test_treespec_equality(self): self.assertTrue(LeafSpec...
the-stack_0_5855
""" mbed CMSIS-DAP debugger Copyright (c) 2006-2015 ARM Limited 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 ...
the-stack_0_5856
# Copyright (c) Yuta Saito, Yusuke Narita, and ZOZO Technologies, Inc. All rights reserved. # Licensed under the Apache 2.0 License. """Off-Policy Evaluation Class to Streamline OPE.""" from dataclasses import dataclass from logging import getLogger from pathlib import Path from typing import Dict from typing import L...
the-stack_0_5859
from __future__ import print_function from builtins import range import json class selectionParser(object): def __init__(self,selectStr): self.__result={} self.__strresult={} strresult=json.loads(selectStr) for k,v in strresult.items(): expandedvalues=[] for w...
the-stack_0_5863
#!/usr/bin/python # -*- encoding: utf-8 -*- import torch from torch.utils.data import Dataset import torchvision.transforms as transforms import os.path as osp import os from PIL import Image import numpy as np import json from transform import * class CityScapes(Dataset): def __init__(self, rootpth, cropsiz...
the-stack_0_5864
import pytest import json from bitarray import bitarray from bigsi.tests.base import CONFIGS from bigsi import BIGSI from bigsi.storage import get_storage from bigsi.utils import seq_to_kmers import pytest def test_create(): for config in CONFIGS: get_storage(config).delete_all() bloomfilters = [...
the-stack_0_5866
# coding=utf-8 # Copyright 2021 The OneFlow 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 require...
the-stack_0_5870
import pandas as pd import pytest import torch from deepdow.benchmarks import OneOverN from deepdow.callbacks import Callback from deepdow.experiments import History, Run from deepdow.losses import MeanReturns, StandardDeviation from deepdow.nn import DummyNet def test_basic(): n_channels = 2 x = torch.rand(...
the-stack_0_5871
import re from pyspark import SparkConf, SparkContext def normalizeWords(text): return re.compile(r'\W+', re.UNICODE).split(text.lower()) conf = SparkConf().setMaster("local").setAppName("WordCount") sc = SparkContext(conf = conf) input = sc.textFile("file:///sparkcourse/book.txt") words = input.flatMa...
the-stack_0_5873
# Copyright 2015 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_5875
import socket import time import pychromecast from gtts import gTTS def get_speaker(ip_addr=None, name=None): if ip_addr: return pychromecast.Chromecast(str(ip_addr)) speakers = pychromecast.get_chromecasts() if len(speakers) == 0: print("No devices are found") raise Exception ...
the-stack_0_5879
# model settings model = dict( type='CascadeRCNN', num_stages=3, pretrained='open-mmlab://msra/hrnetv2_w32', backbone=dict( type='HRNet', extra=dict( stage1=dict( num_modules=1, num_branches=1, block='BOTTLENECK', ...
the-stack_0_5880
# Copyright (c) 2019 Sony Corporation. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
the-stack_0_5882
import pandas as pd from ..utils.messages import msg_warning, msg_info def _drop(df: pd.DataFrame, *cols) -> pd.DataFrame: try: index = df.columns.values for col in cols: if col not in index: msg_warning("Column", col, "not found. Aborting") return ...
the-stack_0_5884
""" Sumarize results for the train/valid/test splits. # PROGRAM : metrics.py # POURPOSE : compute model metrics on the test datasete # AUTHOR : Caio Eadi Stringari # EMAIL : caio.stringari@gmail.com # V1.0 : 05/05/2020 [Caio Stringari] """ import argparse import numpy as np import tensorf...
the-stack_0_5885
"""Eclect.us view""" __docformat__ = "numpy" from gamestonk_terminal.stocks.fundamental_analysis import eclect_us_model from gamestonk_terminal.rich_config import console def display_analysis( ticker: str, ) -> None: """Display analysis of SEC filings based on NLP model. [Source: https://eclect.us] Para...
the-stack_0_5886
#------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. #-------------------------------------------------------------------------- import time...
the-stack_0_5887
import discord from discord.ext import commands from random import randint class Bottlespin: """Spins a bottle and lands on a random user.""" def __init__(self, bot): self.bot = bot @commands.command(pass_context=True, no_pm=True, alias=["bottlespin"]) async def spin(self, ctx, role): ...
the-stack_0_5888
""" Periodic maintenance tasks """ import time import typing class Maintenance: """ Container for periodic maintenance tasks """ def __init__(self, app): self.app = app self.tasks: typing.Dict[typing.Callable[[], None], typing.Dict[str, float]] = {} def r...
the-stack_0_5892
""" Copyright 2015 Rackspace Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software dist...
the-stack_0_5894
import collections.abc import copy import inspect import warnings from datetime import timedelta from typing import ( TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Mapping, Optional, ) import prefect import prefect.engine.cache_validators from prefect.engine.results import ResultH...
the-stack_0_5897
import numpy as np import tensornetwork as tn import itertools as itt #from scipy.sparse import linalg as la #import matrixproductstates as mp import scipy as SP import pymps as mp def kdelta(i,j): """ Parameters ---------- i : int State index i. j : int State ind...
the-stack_0_5898
'''Melhore o desafio 028, onde o computador vai 'pensar' em um número entre 1 e 10. Só que agora o jogador vai tentar adivinhar até acertar, mostrando no final quantos palpites foram necessários para vencer.''' from random import choice lista = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] cont = 0 res = 'S' while res != 'N': ...
the-stack_0_5900
#!/usr/bin/env python import csv import dataset import json import locale import logging import re import sys from collections import OrderedDict from itertools import groupby SECTION_BREAK = 'CLEARANCE RATE DATA FOR INDEX OFFENSES' END_BREAK = ' READ' FIELDNAMES = ['year', 'state', 'ori7', 'lea_name', 'population'...
the-stack_0_5901
import torch.nn as nn import torch.nn.functional as F # from ws.wsRLInterfaces.PARAM_KEY_NAMES import STATE_DIMENSIONS, ACTION_DIMENSIONS class ActorCritic(nn.Module): def __init__(self, app_info): super(ActorCritic, self).__init__() env = app_info.ENV action_size = env.fn_get_action_siz...
the-stack_0_5903
#!/usr/bin/env python # -.- coding: UTF-8 -.- # Creted by Jordan Newman 10th June 2017 import os, sys, socket, struct BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = '\033[30m', '\033[31m', '\033[32m', '\033[33m', '\033[34m', '\033[1;35m', '\033[36m', '\033[37m' if not sys.platform.startswith('linux'): raise...