filename
stringlengths
13
19
text
stringlengths
134
1.04M
the-stack_0_3162
from ..action import Action from db.models.user import User from db.models.account import Account from db.models.artist import Artist from db.serializers.user_serializer import UserSerializer from db.serializers.account_serializer import AccountSerializer class ArtistAccount(Action): arguments = ['user'] def...
the-stack_0_3163
# coding:utf-8 """ author:Qiu Yurui """ import tensorflow as tf import numpy as np import os import sys import cv2 import argparse import glob import tensorflow.contrib.slim as slim import matplotlib.pyplot as plt from tensorflow.python.framework import graph_util from tensorflow.python import pywrap_tensorflow def ...
the-stack_0_3165
# data loader from __future__ import print_function, division import glob import torch from skimage import io, transform, color import numpy as np import random import math import matplotlib.pyplot as plt from torch.utils.data import Dataset, DataLoader from torchvision import transforms, utils from PIL import Image ...
the-stack_0_3167
#!/usr/bin/env python # coding: utf-8 from __future__ import print_function from __future__ import absolute_import import os import tct import sys params = tct.readjson(sys.argv[1]) binabspath = sys.argv[2] facts = tct.readjson(params['factsfile']) milestones = tct.readjson(params['milestonesfile']) resultfile = para...
the-stack_0_3168
import datetime from json.decoder import JSONDecodeError import python_http_client.exceptions from twilio.base.exceptions import TwilioException import tornado from tornado.ioloop import IOLoop import io import math from dateutil.parser import isoparse from sqlalchemy.orm import joinedload from sqlalchemy import func, ...
the-stack_0_3169
from __future__ import annotations from functools import wraps from sys import getsizeof from typing import ( TYPE_CHECKING, Any, Callable, Collection, Hashable, Iterable, List, Sequence, Tuple, cast, ) import warnings import numpy as np from pandas._config import get_option ...
the-stack_0_3171
# -*- coding: utf-8 -*- """Code for maintaining the background process and for running user programs Commands get executed via shell, this way the command line in the shell becomes kind of title for the execution. """ import collections import logging import os.path import re import shlex import signal import sub...
the-stack_0_3172
# Copyright (c) 2017 Intel Corporation. All rights reserved. # Use of this source code is governed by a MIT-style # license that can be found in the LICENSE file. from collections import defaultdict from tastypie.exceptions import NotFound from django.core.exceptions import ObjectDoesNotExist import tastypie.http as ...
the-stack_0_3175
import win32gui from errors import IdenticalWindowsError, WindowNotFound from typing import Any class WindowsHandler: """ Extract a handler for a specific active window. Parameters ---------- screen_name : str A ``string`` of the title to match from the list of enumerated windows. """...
the-stack_0_3176
# -*- coding: utf-8 -*- """ CSV related help functions """ import csv import codecs from setup import eol, encoding, delimiter def dict2csv(csv_path, a_dict, sort=None): """ Writes a dictionary to a csv file, optinally sorted by key (sort=0) or value (sort=1) """ with codecs.open(csv_path, 'w', ...
the-stack_0_3177
# Copyright (c) 2010-2012 OpenStack Foundation # # 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 agree...
the-stack_0_3178
""" Module to provide for a simple summarization of relevant output files from a build. """ import argparse import os import runpy import sys from shutil import copyfile from project_summarizer.cobertura_plugin import CoberturaPlugin from project_summarizer.junit_plugin import JUnitPlugin from project_summarizer.proje...
the-stack_0_3180
import numpy as np from utils import * from images import * np.random.seed(2) class Imager(object): def __init__(self, input_size, labels): if type(input_size) is int: self.input_size = (input_size, input_size) else: self.input_size = input_size self.labels = l...
the-stack_0_3181
""" License: Apache-2.0 Author: Huadong Liao E-mail: naturomics.liao@gmail.com """ import numpy as np import tensorflow as tf from core.utils import * epsilon = 1e-9 class CapsLayer(object): ''' Capsule layer. Args: input: A 4-D tensor. num_outputs: the number of capsule in this layer. ...
the-stack_0_3182
import wx from .icons import icons8_keyboard_50 from .mwindow import MWindow _ = wx.GetTranslation class KeymapPanel(wx.Panel): def __init__(self, *args, context=None, **kwds): kwds["style"] = kwds.get("style", 0) | wx.TAB_TRAVERSAL wx.Panel.__init__(self, *args, **kwds) self.context = c...
the-stack_0_3183
import logging from threading import Thread from time import sleep, time from test.cl_node.errors import NonZeroExitCodeError from test.cl_node.wait import wait_for_block_hashes_propagated_to_all_nodes from test.cl_node.casperlabsnode import extract_block_hash_from_propose_output CONTRACT_1 = 'old_wasm/helloname_inva...
the-stack_0_3184
"""Support for deCONZ binary sensors.""" from __future__ import annotations from collections.abc import Callable, ValuesView from dataclasses import dataclass from pydeconz.sensor import ( Alarm, CarbonMonoxide, DeconzSensor as PydeconzSensor, Fire, GenericFlag, OpenClose, Presence, Vi...
the-stack_0_3185
""" This file offers the methods to automatically retrieve the graph Chloroflexi bacterium RBG_16_70_13. The graph is automatically retrieved from the STRING repository. References --------------------- Please cite the following if you use the data: ```bib @article{szklarczyk2019string, title={STRING v11: prot...
the-stack_0_3186
# Common utility functions used by various script execution tests # e.g. test_cmd_line, test_cmd_line_script and test_runpy import sys import os import re import os.path import tempfile import subprocess import py_compile import contextlib import shutil try: import zipfile except ImportError: #...
the-stack_0_3189
# Copyright (c) 2019 Eric Steinberger import pdb import time from os.path import dirname, abspath import numpy as np import sys from DeepCFR.EvalAgentDeepCFR import EvalAgentDeepCFR # These two eval agents HAVE TO come from the same training run and iteration for this analysis to make sense. if len(sys.argv) < 2: ...
the-stack_0_3192
from PySide2 import QtCore, QtWidgets from keychain.ui import constants class SettingsMenu(QtWidgets.QWidget): def __init__(self, settings, parent=None): super(SettingsMenu, self).__init__(parent) self.settings = settings # self.setWindowFlags(QtCore.Qt.Dialog) self.setWindowFlags(...
the-stack_0_3194
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """The fsl module provides classes for interfacing with the `FSL <http://www.fmrib.ox.ac.uk/fsl/index.html>`_ command line tools. This was written to work with FSL version 4.1.4. Change directory to p...
the-stack_0_3195
# -*- coding: utf-8 -*- # ------------------------------------------------------------------------------ # # Copyright 2018-2019 Fetch.AI 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 ...
the-stack_0_3196
#!/usr/bin/env python # -*- coding: utf-8 -*- # File: deconv.py # Author: Qian Ge <geqian1001@gmail.com> import os import scipy.misc import argparse import numpy as np import tensorflow as tf from tensorcv.dataflow.image import ImageFromFile import config_path as config import sys sys.path.append('../') from lib.net...
the-stack_0_3197
import subprocess import typer from typer.testing import CliRunner from docs_src.options.name import tutorial005 as mod runner = CliRunner() app = typer.Typer() app.command()(mod.main) def test_option_help(): result = runner.invoke(app, ["--help"]) assert result.exit_code == 0 assert "-n, --name TEXT"...
the-stack_0_3198
import csv import numpy as np from sklearn.model_selection import train_test_split from sklearn.metrics.classification import accuracy_score from sklearn.metrics import classification_report #from dbn import SupervisedDBNClassification from sklearn.model_selection import cross_val_score from sklearn.ensemble import Ran...
the-stack_0_3202
import scrapy # noqa: F401 import snoop import isort # noqa: F401 from itertools import zip_longest class SPIDER_1984(scrapy.Spider): name = 'spider_1984' start_urls = ["https://www.reddit.com/r/linux/comments/sjlu6l/version_0345_pipewire/"] @snoop def parse(self, response): srch_titles ...
the-stack_0_3203
import sys sys.path.insert(0, '../../') import pyrosim def send_point_mass_example( sim ): fixed_box = sim.send_box( position = ( -2, 0, 1 ) ) sim.send_slider_joint( -1, fixed_box, joint_range = 0 ) free_box = sim.send_box( position = ( -2.5, 0, 1 ) ) sim.send_point_mass_spring_joint( fixed_box, free_b...
the-stack_0_3204
#!/usr/bin/env python3 import json import sys pastafile = "./plugins/copypasta/copypastas.json" def commandlist(obj): commands = "" for key in obj: commands += str(key) + " " cmds = "`"+commands.strip().replace(" ", ", ")+"`" return cmds with open(pastafile) as pf: try: obj ...
the-stack_0_3205
#!/usr/bin/env python r""" See help text for details. """ import sys import subprocess import re save_dir_path = sys.path.pop(0) modules = ['gen_arg', 'gen_print', 'gen_valid', 'gen_misc', 'gen_cmd', 'var_funcs'] for module in modules: exec("from " + module + " import *") sys.path.insert(0, save_dir_path) par...
the-stack_0_3209
import os import copy import regex import asyncio import logging import contextlib import collections from collections.abc import Mapping import synapse import synapse.exc as s_exc import synapse.axon as s_axon import synapse.common as s_common import synapse.telepath as s_telepath import synapse.datamodel as s_datam...
the-stack_0_3214
import asyncio import collections import gc from contextlib import contextmanager, suppress import copy import functools from glob import glob import io import itertools import logging import logging.config import os import queue import re import shutil import signal import socket import subprocess import sys import te...
the-stack_0_3215
# -*- coding: utf-8 -*- # # Database upgrade script # # RLPCM Template Version 1.1.5 => 1.1.6 # # Execute in web2py folder after code upgrade like: # python web2py.py -S eden -M -R applications/eden/modules/templates/BRCMS/RLP/upgrade/1.1.5-1.1.6.py # import sys from uuid import uuid4 #from gluon.storage import Storag...
the-stack_0_3217
# -*- coding: utf-8 -*- import DIRAC from DIRAC import gLogger from DIRAC.Core.Base import Script Script.setUsageMessage(""" Download LFNs in a dataset Usage: %s <dataset name> """ % Script.scriptName) Script.registerSwitch("", "save=", "The directory which save files.") Script.parseCommandLine( ignoreErrors =...
the-stack_0_3218
#!/usr/bin/python import matplotlib.pyplot as plt import matplotlib.animation as animation import numpy as np import serial import sys import time from demo_plot_defs import * from other_funcs import get_freq_response, get_phase_response if (sys.argv[1] == "help"): print ("usage: demo_plot.py MIN MAX options..."...
the-stack_0_3220
import os import discord from discord import Embed import settings def prune_participant_name(name): name = name.split(' ')[0] name = name.split('/')[0] name = name.split('\\')[0] name = name.split('-')[0] name = name.split('(')[0] name = name.split(')')[0] name = name.split('+')[0] ...
the-stack_0_3221
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Apr 19 09:04:27 2018 @author: jeremiasknoblauch Description: Well-log data processing """ """System packages/modules""" import numpy as np import scipy import matplotlib.pyplot as plt import csv import datetime import matplotlib """Modules of the BOC...
the-stack_0_3222
from django.http import HttpResponseForbidden from django.shortcuts import get_object_or_404, render_to_response from django.template import RequestContext from boxes.authorization import load_can_edit from boxes.forms import BoxForm from boxes.models import Box # @@@ problem with this is that the box_edit.html and ...
the-stack_0_3223
import sst import os sst.setProgramOption("timebase", "1ps") sst_root = os.getenv( "SST_ROOT" ) app = sst_root + "/sst-elements/src/sst/elements/ariel/frontend/simple/examples/stream/stream" if not os.path.exists(app): app = os.getenv( "OMP_EXE" ) l2PrefetchParams = { "prefetcher": "cassini.StridePrefet...
the-stack_0_3224
import taso as ts import onnx import os import argparse import re def squeeze(graph, out_channels, input): weight = graph.new_weight(dims=(out_channels, input.dim(1), 1, 1)) return graph.conv2d(input=input, weight=weight, strides=(1, 1), padding="SAME", ...
the-stack_0_3225
from Task import Task from Settings import EvolvedConfig from Interfaces import Evolved5gJenkinsApi from Helper import Level class JenkinsBase(Task): def __init__(self, name, parent, params, logMethod): super().__init__(name, parent, params, logMethod, None) self.config = EvolvedConfig().JenkinsAp...
the-stack_0_3226
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # ============================================================================== # # author: Gabriele Girelli # email: gigi.ga90@gmail.com # version: 1.1.1dev # date: 180308 # project: pre-processing sequencing data # # credits: # Dr. F. Agostini for the nice chats and ...
the-stack_0_3227
"""Tests for certbot.cli.""" import argparse import unittest import os import tempfile import mock import six from six.moves import reload_module # pylint: disable=import-error from acme import challenges from certbot import cli from certbot import constants from certbot import errors from certbot.plugins import di...
the-stack_0_3228
import torch from torch.nn.functional import cross_entropy def check_accuracy(loader, model, device): num_correct = 0 num_samples = 0 model.eval() # set model to evaluation mode with torch.no_grad(): for x, y in loader: x = x.to(device=device) y = y.to(device=device, dt...
the-stack_0_3229
# import the necessary packages import win32gui #import keyboard as keyboard #import pygame as pygame #import pythoncom #import win32con from PIL import ImageGrab, Image from imutils.video import VideoStream, FPS import numpy as np import argparse import imutils import time import cv2 import pyautogui i...
the-stack_0_3230
import gym import numpy as np from gym.spaces.box import Box import pdb # Taken from https://github.com/openai/universe-starter-agent def create_atari_env(env_id): env = gym.make(env_id) return env # process each frame def _process_frame42(frame): frame = frame[34:34 + 160, :160] # Resize by half, the...
the-stack_0_3232
#!/usr/bin/env python3 # -*- coding:utf-8 -*- class Solution: def isMatch(self, s: str, p: str) -> bool: self.s = " "+s self.p = " "+p self.matrix = [[0]*len(self.p) for x in self.s] self.matrix[0][0]=1 for i in range(len(s)+1): for j in range(1,len(p)+1): ...
the-stack_0_3234
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: david@reciprocitylabs.com # Maintained By: david@reciprocitylabs.com from ggrc import db from .mixins import deferred, Base class PopulationSample...
the-stack_0_3237
"""Common methods used across tests for Bond.""" from asyncio import TimeoutError as AsyncIOTimeoutError from contextlib import nullcontext from datetime import timedelta from typing import Any, Dict, Optional from homeassistant import core from homeassistant.components.bond.const import DOMAIN as BOND_DOMAIN from hom...
the-stack_0_3238
import discord import datetime import pytz from discord.ext import commands from utils.bot import EpicBot from config import MAIN_COLOR from utils.time import convert_int_to_weekday from utils.custom_checks import mutual_guild from handler import slash_command, InteractionContext stream_schedule = { 0: True, # M...
the-stack_0_3242
# # Copyright (C) 2019 Databricks, 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 i...
the-stack_0_3243
# # Copyright (c) 2021 Airbyte, Inc., all rights reserved. # from setuptools import find_packages, setup MAIN_REQUIREMENTS = [ "airbyte-protocol", "base-python", "backoff==1.10.0", "pendulum==1.2.0", "requests==2.25.1", ] TEST_REQUIREMENTS = ["pytest", "requests_mock==1.8.0"] setup( name="...
the-stack_0_3247
# Copyright (c) 2015 Cloudera, 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 o...
the-stack_0_3248
import sys class VirtualMachine: def __init__(self, name, ram=1, cpu=1.3, hdd=100, os="debian"): self.name = name self.ram = ram self.cpu = cpu self.hdd = hdd self.os = os self.status = 0 self.proc = [] def stop(self): self.status = 0 sel...
the-stack_0_3250
""" This file offers the methods to automatically retrieve the graph friendster. The graph is automatically retrieved from the NetworkRepository repository. References --------------------- Please cite the following if you use the data: ```bib @inproceedings{nr, title = {The Network Data Repository with Intera...
the-stack_0_3251
""" Common options for ``minidcos docker`` commands. """ from typing import Callable import click from dcos_e2e.backends import Docker from dcos_e2e.node import Transport def node_transport_option(command: Callable[..., None]) -> Callable[..., None]: """ An option decorator for node transport options. ...
the-stack_0_3252
from django.core.urlresolvers import reverse from django.core import mail from oscar.apps.customer.models import CommunicationEventType from oscar.test.factories import UserFactory from oscar.test.testcases import WebTestCase class TestAnAdmin(WebTestCase): def setUp(self): self.staff = UserF...
the-stack_0_3253
# # 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 # ...
the-stack_0_3254
import hashlib import itertools import logging from collections import OrderedDict from typing import Any, Generator, Iterable, List, Mapping, Type, Union logger = logging.getLogger(__name__) def make_hash(data: Union[List, OrderedDict]) -> str: return hashlib.md5(str(data).encode()).hexdigest() def ensure_lis...
the-stack_0_3255
import discord from discord.ext import commands from logger import getLogger l = getLogger("main") class Curation(commands.Cog, description="Information about curating games for Flashpoint."): def __init__(self, bot): self.bot = bot @commands.command(name="curation", aliases=["ct", "curation-tutor...
the-stack_0_3256
""" Using a while loop with an and conditional """ if __name__ == "__main__": i = 0 while( (input("Enter your name: ")!= "your name") and i < 10): print("Nope sorry try again") i = i + 1 print("Done with program")
the-stack_0_3257
# -*- coding: utf-8 -*- from __future__ import print_function import collections from operator import itemgetter import os.path import oursql import phpserialize as php import wmflabs def is_autopatrol(log_params): p = php.loads(log_params) return p["6::auto"] == 1 def get_patrol_stats(db, oldest_ts): ...
the-stack_0_3259
# 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_3260
from setuptools import setup, find_packages with open('README.md') as f: readme = f.read() with open('LICENSE') as f: license = f.read() setup( name='sample', version='0.1.0', description='RPyOpenCL', long_description=readme, author='Shazz', author_email='shazz@metaverse.fr', url...
the-stack_0_3264
import utils as util import os import ImgSplit_multi_process import SplitOnlyImage_multi_process import shutil from multiprocessing import Pool from DOTA2COCO import DOTA2COCOTest, DOTA2COCOTrain import argparse wordname_5 = ['1', '2', '3', '4', '5'] def parse_args(): parser = argparse.ArgumentParser(description=...
the-stack_0_3268
import pandas as pd from os import path import vowpalwabbit import unittest import platform import math import re def helper_get_test_dir(): curr_path = path.dirname(path.realpath(__file__)) return path.join(path.dirname(path.dirname(curr_path)), "test") def helper_get_data(): train_data = [ { ...
the-stack_0_3271
# -*- coding: utf-8 -*- from datetime import datetime import requests from shipane_sdk.base_quant_client import BaseQuantClient from shipane_sdk.joinquant.transaction import JoinQuantTransaction class JoinQuantClient(BaseQuantClient): BASE_URL = 'https://www.joinquant.com' def __init__(self, **kwargs): ...
the-stack_0_3272
#!/usr/bin/env python # Description: access topcons.net via WSDL service # Copyright Nanjiang Shu (nanjiang.shu@scilifelab.se) from __future__ import print_function import os import sys import argparse progname = os.path.basename(sys.argv[0]) wspace = ''.join([" "]*len(progname)) no_suds_message="""\ suds is not in...
the-stack_0_3273
import random import math import torch from torch import nn, Tensor import torchvision from torch.jit.annotations import List, Tuple, Dict, Optional from torchvision.ops import misc as misc_nn_ops from .image_list import ImageList from .roi_heads import paste_masks_in_image @torch.jit.unused def _resize_image_and_ma...
the-stack_0_3274
import time import os import argparse import sys import datetime sys.path.append('../../python/src') from libnyumaya import AudioRecognition, FeatureExtractor from auto_platform import AudiostreamSource, play_command,default_libpath def detectKeywords(libpath): audio_stream = AudiostreamSource() extractor = Featu...
the-stack_0_3276
import os import torch import torch.nn as nn from torch_geometric.nn.conv import RGCNConv, GCNConv, GINConv import torch_geometric.nn as gnn import numpy as np from torch_geometric.data import Data import torch.nn.functional as F class TemporalExtGCN(nn.Module): def __init__(self, lfd_params, is_training=False, f...
the-stack_0_3277
# coding: utf-8 # # Copyright 2016 The Oppia 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 requi...
the-stack_0_3278
# this builtin is needed so we can overwrite in test import asyncio import json import logging import os import aiohttp import questionary from aiohttp import ClientTimeout from prompt_toolkit.styles import Style from typing import Any from typing import Text, Optional, Dict, List from rasa.cli import utils as cli_ut...
the-stack_0_3279
# https://rosalind.info/problems/sims/ def fmtfa(fasta: list): prev = True header = [] seq = [] for f in fasta: if ">" in f: header.append(f[1:]) prev = True elif prev: seq.append(f) prev = False else: seq[-1] += f ...
the-stack_0_3280
import matplotlib.pyplot as plt plt.figure(1, figsize=(3,3)) ax = plt.subplot(111) ax.annotate("", xy=(0.2, 0.2), xycoords='data', xytext=(0.8, 0.8), textcoords='data', arrowprops=dict(arrowstyle="->", connectionstyle="arc3"), ) plt.show() ...
the-stack_0_3281
# JupyterHub configuration # ## If you update this file, do not forget to delete the `jupyterhub_data` volume before restarting the jupyterhub service: ## ## docker volume rm jupyterhub_jupyterhub_data ## ## or, if you changed the COMPOSE_PROJECT_NAME to <name>: ## ## docker volume rm <name>_jupyterhub_data ## ...
the-stack_0_3282
#!/usr/bin/env python # encoding: utf-8 r""" Module containing all Pyclaw solution objects """ from __future__ import absolute_import import six class State(object): r""" A PyClaw State object contains the current state on a particular patch, including the unkowns q, the time t, and the auxiliary coeffici...
the-stack_0_3284
from hydroDL import kPath, utils from hydroDL.app import waterQuality from hydroDL.master import basins from hydroDL.data import usgs, gageII, gridMET, ntn from hydroDL.master import slurm from hydroDL.post import axplot, figplot import numpy as np import matplotlib.pyplot as plt import pandas as pd import scipy codeL...
the-stack_0_3285
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('account', '0003_subscription'), ] operations = [ migrations.AlterModelOptions( name='subscription', ...
the-stack_0_3286
# Copyright (C) 2016 The Android Open Source Project # # 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 ag...
the-stack_0_3288
''' QUESTÃO 5 Um palíndromo é uma seqüência de caracteres cuja leitura é idêntica se feita da direita para esquerda ou vice−versa. Por exemplo: OSSO e OVO são palíndromos. Em textos mais complexos os espaços e pontuação são ignorados. A frase SUBI NO ONIBUS é o exemplo de uma frase palíndroma onde os espaços foram igno...
the-stack_0_3289
from abc import ABC, abstractmethod from typing import List, Tuple, Union import torch from torch.nn import functional as F class Bandit(ABC): """Abstract Base class for bandits""" @abstractmethod def step(self, action: int) -> Tuple[torch.Tensor, int]: """Generate reward for given action and se...
the-stack_0_3292
# -*- coding: utf-8 -*- """ The :mod:`sklearn.naive_bayes` module implements Naive Bayes algorithms. These are supervised learning methods based on applying Bayes' theorem with strong (naive) feature independence assumptions. """ # Author: Vincent Michel <vincent.michel@inria.fr> # Minor fixes by Fabian Pedre...
the-stack_0_3294
from __future__ import annotations import typing from types import TracebackType import httpx from ._endpoints_mappings import MappingsEndpoint from ._endpoints_near_misses import NearMissesEndpoint from ._endpoints_recordings import RecordingsEndpoint from ._endpoints_requests import RequestsEndpoint from ._endpoin...
the-stack_0_3297
from abc import ABC import numpy as np from numpy.lib.function_base import copy from scipy.signal import convolve2d from typing import List import re import sys class Filter(ABC): def apply(self, data: np.ndarray) -> np.ndarray: raise NotImplementedError() class ConvFilter(Filter): def __init__(se...
the-stack_0_3298
#!/usr/bin/env python3 # Copyright (c) 2014-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """ ZMQ example using python3's asyncio Faithcoin should be started with the command line argume...
the-stack_0_3299
import ms2pip.peptides class TestModifications: def test_add_from_ms2pip_modstrings(self): mods = ms2pip.peptides.Modifications() mods.add_from_ms2pip_modstrings([ "Oxidation,15.994915,opt,M", "Acetyl,42.010565,opt,N-term", "Methyl,14.01565,opt,L", ]) ...
the-stack_0_3301
# SPDX-FileCopyrightText: 2021 Dylan Herrada for Adafruit Industries # SPDX-License-Identifier: MIT import time import math import board import busio from digitalio import DigitalInOut import displayio from adafruit_display_shapes.rect import Rect import adafruit_imageload import adafruit_touchscreen # E...
the-stack_0_3302
from django.urls import reverse import pytest from pytest_django.asserts import assertTemplateUsed from Post.views import get_post_by_query_text class TestViews: @pytest.mark.django_db def test_view_posts_GET(self, client): response = client.get(reverse('view posts')) assert response.status_co...
the-stack_0_3305
import os import pickle import time import torch from torch.utils.data.dataset import Dataset from filelock import FileLock from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging logger = logging.get_logger(__name__) class TextDataset(Dataset): """ This will be superseded by a...
the-stack_0_3307
#!/usr/bin/env python3 """ for testing the module awsbuild """ import sys import logging from bao_config import AwsConfig from bao_connector import AwsConnector from bao_vpc import AwsVPC from bao_target_group import AwsTargetGroup def main(): """ main """ my_logfile = 'logs/awsbuild.log' my_region = 'us-...
the-stack_0_3308
#!/usr/bin/env python import setuptools with open('README.md', 'r') as fh: long_description = fh.read() setuptools.setup( name='PLTable', version='1.0.2', license='BSD (3 clause)', description='Python library for easily displaying tabular data in a visually appealing text table format', long_...
the-stack_0_3309
from flask import Response, request, stream_with_context, abort from fHDHR.exceptions import TunerError class Tuner(): endpoints = ['/tuner<tuner_number>/<channel>'] endpoint_name = "tuner" def __init__(self, fhdhr): self.fhdhr = fhdhr def __call__(self, tuner_number, channel, *args): ...
the-stack_0_3312
#!/usr/bin/env python import rospy from std_msgs.msg import Bool from dbw_mkz_msgs.msg import ThrottleCmd, SteeringCmd, BrakeCmd, SteeringReport from geometry_msgs.msg import TwistStamped import math from twist_controller import Controller ''' You can build this node only after you have built (or partially built) th...
the-stack_0_3313
#!/usr/bin/env python3 # Copyright 2016 the V8 project authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from collections import namedtuple import textwrap import sys SHARD_FILENAME_TEMPLATE = "test/mjsunit/compiler/inline-exception-{...
the-stack_0_3314
# Copyright 2019 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
the-stack_0_3316
# 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 # d...
the-stack_0_3318
''' Header reading / writing functions for nifti1 image format Author: Matthew Brett ''' import numpy as np import numpy.linalg as npl from nifti.volumeutils import Recoder, make_dt_codes, \ HeaderDataError, HeaderTypeError, allopen from nifti.batteryrunners import Report from nifti.quaternions import fillposit...
the-stack_0_3319
"""functions for evaluating embeddings and neighbor networks""" import scanpy as sc import numpy as np import pandas as pd def fidelity(adata, name, groupby='label'): """look in .obsp[name_connectivities] for connectivity data and see how well it preserves the given labelling""" labels = adata.obs[groupby].v...
the-stack_0_3320
import os import time import yaml from platform import python_version from unittest import skipIf import bzt from bzt.engine import EXEC from bzt.modules import ConsolidatingAggregator from bzt.modules._selenium import GeckoDriver from bzt.modules.functional import FuncSamplesReader, LoadSamplesReader, FunctionalAgg...