content
stringlengths
5
1.05M
import os import shutil import pytest from olive.optimization_config import OptimizationConfig from olive.optimize import optimize ONNX_MODEL_PATH = os.path.join(os.path.dirname(__file__), "onnx_mnist", "model.onnx") SAMPLE_INPUT_DATA_PATH = os.path.join(os.path.dirname(__file__), "onnx_mnist", "sample_input_data.np...
__version__ = '0.2.7.dev'
import unittest,os import pandas as pd from igf_data.utils.fileutils import get_temp_dir,remove_dir from igf_airflow.seqrun.calculate_seqrun_file_size import calculate_seqrun_file_list class Calculate_seqrun_file_list_testA(unittest.TestCase): def setUp(self): self.workdir = get_temp_dir() self.seqrun_id = '...
from __future__ import absolute_import, division, print_function, unicode_literals import logging import threading from datetime import datetime from os import getpid from time import sleep from scout_apm.core.commands import ApplicationEvent from scout_apm.core.context import AgentContext from scout_apm.core.sampler...
# -*- coding: utf-8 -*- """ Created on Jul 21 2017 @author: J. C. Vasquez-Correa """ from scipy.io.wavfile import read import os import sys import numpy as np import matplotlib.pyplot as plt plt.rcParams["font.family"] = "Times New Roman" import pysptk try: from .phonation_functions import jitter_env, logEnergy...
''' Created on Nov 13, 2017 @author: khoi.ngo ''' from .constant import Colors, Constant import asyncio import json from indy import wallet, pool, ledger from indy.error import IndyError class Common(): """ Wrapper the common steps. """ # Static methods =================================================...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #stdlib import import json class ErrorEllipseAxis: """ A conversion class usd to create, parse, and validate error ellipse axis data """ # JSON Keys ERROR_KEY = "Error" # Required AZIMUTH_KEY = "Azimuth" # Required DIP_KEY = "Dip" # Required def __init_...
#!/usr/bin/python ''' Visual genome data analysis and preprocessing.''' import json import os from collections import Counter import xml.etree.cElementTree as ET from xml.dom import minidom dataDir = '/home/new/file/dataset/VRD' outDir = '/home/new/file/rel_det/ProcessVG-master/data/vrd' # Set maximum values for n...
def date_formatter(string_date: str) -> str: """ Args: string_date: string containing date in format 22.08.2018 12:27:00 Returns: string of date in format YYYY-mm-dd-hh """ if string_date[11].isspace(): pos = 0 srr = "" for i in string_date: ...
class Error: def __init__(self, file_name, line_number, error_name, error_details = None) -> None: self.file_name = file_name self.line_number = line_number self.error_name = error_name self. error_details = error_details def __repr__(self) -> str: if self.file_name != N...
import math def get_sum(n: int) -> int: sum = 0 i = 1 while i <= math.sqrt(n): if n % i == 0: if n / i == i: sum += i else: sum += i sum = sum + (n / i) i += 1 sum = sum - n return sum def is_abundant(n: int) ...
test = { 'name': 'q3', 'points': 3, 'suites': [ { 'cases': [ {'code': '>>> hailstone(4)\n4\n2\n1\n3', 'hidden': False, 'locked': False}, {'code': '>>> hailstone(10)\n10\n5\n16\n8\n4\n2\n1\n7', 'hidden': False, 'locked': False}, {'code...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. r"""Utility functions.""" import json import math import os from urllib.parse import urlparse import urllib.request import matplotlib.pyplot as plt import numpy as np from PIL import Image import torch import torch.nn.functional as F EPSILON_DO...
import json from django.conf import settings from django.http import HttpResponse, Http404 from django.shortcuts import redirect from django.contrib import messages from django.core.mail import send_mail from django.urls import reverse_lazy from django.views import View from django.views.generic.edit import FormView f...
from .opt_setup import * def test_project_to_ball(): n = 32 x = random.normal(keys[0], (n,)) y = opt.project_to_ball(x) def test_project_to_box(): n = 32 x = random.normal(keys[0], (n,)) y = opt.project_to_box(x) def test_project_to_real_upper_limit(): n = 32 x = random.normal(keys[0...
import json import os import unittest from onedrivesdk.helpers.http_provider_with_proxy import HttpProviderWithProxy from onedrived import get_resource, od_auth, od_api_session def get_sample_authenticator(): auth = od_auth.OneDriveAuthenticator() session_params = json.loads(get_resource('data/session_respo...
# -*- coding: utf-8 -*- """ tossi.coda ~~~~~~~~~~ Coda is final consonant in a Korean syllable. That is important because required when determining a particle allomorph in Korean. This module implements :func:`guess_coda` and related functions to guess a coda from any words as correct as possible. ...
#!/usr/bin/env python # Copyright (c) 2015, Robot Control and Pattern Recognition Group, # Institute of Control and Computation Engineering # Warsaw University of Technology # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the ...
from django import template import readtime import math register = template.Library() def read(html): with_text = readtime.of_html(html) result = math.ceil(with_text.seconds / 60) return result register.filter('readtime', read)
from .telebot import TeleBot from .wxworkbot import WxWorkBot from .dingbot import DingBot
import rdflib import rdfextras rdfextras.registerplugins() import sys if sys.version_info[0] < 3: from StringIO import StringIO else: from io import StringIO from pandas import DataFrame ''' sparql.py: part of the nidmviewer package Sparwl queries ''' def do_query(ttl_file,query,rdf_format="turtle",serialize...
# 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 # distributed under the Li...
class Solution: def calPoints(self, ops: List[str]) -> int: scores = [] for op in ops: if op=="D": scores.append(scores[-1] * 2) elif op=="+": scores.append(scores[-1] +scores[-2]) elif op=="C": sc...
import os from invoke import task @task def clean(ctx): """ Clean pyc files and build assets. """ join = os.path.join rm_files = [] rm_dirs = [] for base, subdirs, files in os.walk("."): if "__pycache__" in subdirs: rm_dirs.append(join(base, "__pycache__")) eli...
import math import torch import numpy as np import torch.nn as nn import torch.nn.functional as F from torch.distributions.categorical import Categorical from src.util import init_weights, init_gate from src.module import VGGExtractor, CNNExtractor, RNNLayer, ScaleDotAttention, LocationAwareAttention class ASR(nn.Mo...
# -*- coding: utf-8 -*- """ Created on Wed Feb 21 12:37:40 2018 @author: slauniai """ import os #import spotpy import pickle import numpy as np from scipy import stats import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from spathy_sve import SpatHy, initialize_netCDF, read_setup from iotools im...
""" [ #476580 ] 'del obj.non_member' : wrong exception """ import support class C : pass o = C() try: o.foo except AttributeError: pass try: del o.foo except AttributeError: pass
from django.test import TestCase import requests, json # Create your tests here. base = 'http://localhost:8000/api/' header = {'Content-Type': 'application/json'} class myTest(TestCase): @classmethod def setUpTestData(cls): # print("setUpTestData: Run once to set up non-modified data for all class met...
""" Module Logger """ from app import app # retreive app object import logging from logging.handlers import SMTPHandler, RotatingFileHandler import os from time import strftime from flask import Flask, render_template, request if not app.debug: # Mail Logging if app.config['MAIL_LOGGING']: auth = Non...
# coding: utf-8 # In[1]: print("Hello UTC")
# This program displays ten balls with random colors and placed at random locations, from tkinter import * # Import tkinter from random import randint class RandomBalls: def __init__(self): window = Tk() # Create a window window.title("Random Balls") # Set title x = 100 y = ...
"""Provides hooks for session life-cycle events.""" import asyncio import iterm2 class SessionTerminationMonitor: """ Watches for session termination. A session is said to terminate when its command (typically `login`) has exited. If the user closes a window, tab, or split pane they can still undo closing...
from marshmallow import ValidationError from marshmallow_jsonapi import fields class CompleteNestedRelationship(fields.Relationship): def extract_value(self, data): """Extract the object with data and validate the request structure.""" errors = [] if 'type' not in data: errors....
from .reaction_classifier import classify, is_transport, is_complex_assembly
#!/usr/bin/env python # coding: utf-8 """ Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root. Note: The length of path between two nodes is represented by the number of edges between them. """ # Definition for a bi...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # from __future__ import annotations # isort:skip # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from __future__ import annotations from typi...
"""Main module """ # Standard library imports import string # Third party imports import numpy as np import justpy as jp import pandas as pd START_INDEX: int = 1 END_INDEX: int = 20 GRID_OPTIONS = """ { class: 'ag-theme-alpine', defaultColDef: { filter: true, sortable: false, resizab...
# -*- coding: utf-8 -*- # # Copyright 2017 AVSystem <avsystem@avsystem.com> # # 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...
import sys import os import builtins print('Hi') os.chdir(sys.argv[-1]) PYDK= os.environ.get('PYDK',"/data/cross/pydk") ASSETS = "./assets" sys.path[0]='./assets' def rootfn(fn): return os.path.join( ASSETS, fn ) log = print def CLI(): print('CLI') def STI(): print('STI') ver = f'{sys.version_...
"""Utilities for evaluating the fairness of die""" from typing import List, Union, Tuple from scipy.linalg import solve from scipy.optimize import minimize from pydantic import BaseModel, Field import numpy as np def _pretty_multiplier(x: float) -> str: """Make a prettier version of a multiplier value Args:...
# BOJ 1028 # diamondmine.py from collections import deque import sys input = sys.stdin.readline dy = (-1, 1) r, c = map(int, input().split()) mine = [] for _ in range(r): mine.append(list(input().strip())) max_level = round((min(r,c)+0.1) / 2) tmp = 0 def check(lvl, x, y, r, c): remain_x = r - x remain_...
"""NDG XACML one and only functions module NERC DataGrid """ __author__ = "P J Kershaw" __date__ = "01/04/10" __copyright__ = "" __license__ = "BSD - see LICENSE file in top-level directory" __contact__ = "Philip.Kershaw@stfc.ac.uk" __revision__ = '$Id$' from ndg.xacml.core.functions import (AbstractFunction, ...
import os import discord from discord.ext import commands from dotenv import load_dotenv load_dotenv() TOKEN = os.getenv('DISCORD-TOKEN') intents = discord.Intents.default() client = commands.Bot(command_prefix = "m!", intents = intents) print("Commands:\n") for filename in os.listdir("./commands"): client.lo...
from pedal.report.imperative import MAIN_REPORT def make_resolver(func, report=None): ''' Decorates the given function as a Resolver. This means that when the function is executed, the `"pedal.resolver.resolve"` event will be triggered. Args: func (callable): The function to decorate....
import logging import sys from logging import Logger, StreamHandler, FileHandler from logging.handlers import MemoryHandler from osbot_utils.decorators.lists.group_by import group_by from osbot_utils.decorators.lists.index_by import index_by from osbot_utils.utils.Misc import random_string, obj_dict from osbo...
from functions import * names = ['Name_sim1_scen_MQ_del2_M_28-30.dfsu', 'Name_sim3_scen_Q10_del2_M_28-30.dfsu', 'Name_sim1_scen_MQ_del2_M_28-30.m21fm', 'Name_sim3_scen_Q10_del2_M_28-30.m21fm', 'Klaralven_sim1_scen_MQ_del2_M_28-30.m21fm - Result Files', 'Klaralven_sim2_scen_MQ_klimat_del2_M_2...
# %% import os import pathlib import chardet import pandas as pd import pathlib from utils import get_projectpaths (projectroot, rawdatapath, cleandatapath, processeddatapath) = get_projectpaths() # %% listoffiles = [] for path, subdirs, files in os.walk(rawdatapath): [listoffiles.append(str(pathlib.PurePath(path...
import logging from typing import Dict, List, Iterable from allennlp.data.dataset_readers.dataset_utils import to_bioul from allennlp.common.file_utils import cached_path from allennlp.common.checks import ConfigurationError from allennlp.data.dataset_readers.dataset_reader import DatasetReader from allennlp.data.fi...
import numpy as np import openmdao.api as om class ComputeSinCos(om.ExplicitComponent): # computes sin and cos of the input angle def initialize(self): self.options.declare('num_nodes', default=1, desc="Number of nodes to compute") def setup(self): nn = self.options['num_nodes'] a...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def add_element(): name = input('Конечный пункт: ') num = input('Номер поезда: ') tm = input('Время отправления: ') trains = {} trains['name'] = name trains['num'] = int(num) trains['tm'] = tm return trains def find_train(trains): num...
import math n = int(input()) x = int(math.sqrt(n)) + 1 val = 1 while val <= x: if val == x: val*=2 print(val)
import os import uuid from datetime import datetime, timedelta import mock import pytz from django.conf import settings from django.contrib.auth.models import User from django.test import TestCase from utils.widget import quill from wiki.forms import wikipageform from wiki.models import wikipage, wikisection from wiki...
import os import datetime from utils import get_python_version python_version = get_python_version() attacks = ['bim']#, 'jsma', 'cw', 'bim'] labels = [0,1,2,3,4,5,6,7,8,9] qq = [2,3] rel_num = [6,8,10, 12] model_names = ['neural_networks/cifar_original'] #model_names = ['neural_net...
""" Setup for pytrafikverket """ from setuptools import setup setup( name="pytrafikverket", version="0.1.5.8", description="api for trafikverket in sweden", url='https://github.com/AnderssonPeter/pytrafikverket', author="Peter Andersson", license="MIT", install_requires=["aiohttp", "async-...
import os import pytest import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_hosts_file(host): f = host.file('/etc/hosts') assert f.exists assert f.user == 'root' assert f.group == ...
from .utils import * from .music import *
#!/usr/bin/env python """Lists results directories with a summary of their contents. Useful for quickly inspecting which directory contains which experiments. Also shows if any scripts are still running. For scripts that run many experiments, it shows the number of experiments finished, expected and unfinished. For ex...
import collections class Solution: def getHint(self, secret: str, guess: str) -> str: table = collections.Counter() bull = cow = 0 for s, g in zip(secret, guess): if s == g: bull += 1 else: if table[s] < 0: cow += 1 ...
c = get_config() c.Exchange.root = '/srv/nbgrader/exchange' c.Exchange.course_id = "2018s-ocng469"
from enum import Enum class OpArithmetic(Enum): PLUS = 1 MINUS = 2 TIMES = 3 DIVIDE = 4 MODULE = 5 POWER = 6 class OpLogical(Enum): GREATER = 1 LESS = 2 EQUALS = 3 NOT_EQUALS = 4 GREATER_EQUALS = 5 LESS_EQUALS = 6 LIKE = 7 NOT_LIKE = 8 class OpRelational(Enu...
from logging import BASIC_FORMAT import tictactoe as t import test_helper as helper import unittest class TestTicTacToe(unittest.TestCase): def test_player(self): for test_case in helper.test_cases: self.assertEqual(t.player(test_case["board"]),test_case["player"]) def test_terminal(self)...
# -*- coding: utf-8 -*- """ Universidade Federal de Pernambuco (UFPE) (http://www.ufpe.br) Centro de Informática (CIn) (http://www.cin.ufpe.br) Projeto Programação 1 Graduando em Sistemas de Informação IF968 - Programação 1 Autor: Matheus Ribeiro Brant Nobre (mrbn) Email: mrbn@cin.ufpe.br Copyright(c) 2018 M...
#!/usr/bin/env python # coding=utf8 # File: lab_export.py from rllab.utils import logger ___all__ = ['lab_export'] class lab_export(object): """decorator to export RLlab API""" def __init__(self, *args): self._name = args[0] def __call__(self, func): """Calls this decorator""" fu...
# Copyright (c) Youngwan Lee (ETRI) All Rights Reserved. from .config import add_vovnet_config from .vovnet import build_vovnet_fpn_backbone, build_vovnet_backbone from .mobilenet import build_mobilenetv2_fpn_backbone, build_mnv2_backbone
#!/usr/bin/env python # # Make a legend for specific lines. from pylab import * t1 = arange(0.0, 2.0, 0.1) t2 = arange(0.0, 2.0, 0.01) # note that plot returns a list of lines. The "l1, = plot" usage # extracts the first element of the list inot l1 using tuple # unpacking. So l1 is a Line2D instance, not a sequence...
operations_maps = { 'eq': lambda first, second: first == second, 'ne': lambda first, second: first != second, 'gt': lambda first, second: first > second, 'ge': lambda first, second: first >= second, 'lt': lambda first, second: first < second, 'le': lambda first, second: first <= second, }...
""" AssignResources class for CentralNodeLow. """ # PROTECTED REGION ID(CentralNode.additionnal_import) ENABLED START # # Standard Python imports import json import time # Tango imports import tango from tango import DevState, DevFailed # Additional import from ska.base.commands import BaseCommand from tmc.common.ta...
from ast import parse import copy import os import sys import argparse from tracemalloc import start import smartsheet from pptree import * def init_client(): token_name = "SMARTSHEET_ACCESS_TOKEN" token = os.getenv(token_name) if token == None: sys.exit(f"{token_name} not set") client = smart...
import unittest from io import StringIO import re import numpy as np import openmdao.api as om from openmdao.utils.array_utils import evenly_distrib_idxs from openmdao.utils.mpi import MPI class MixedDistrib2(om.ExplicitComponent): def setup(self): # Distributed Input self.add_input('in_dist', ...
"""Test functions for Aracnid Logger functionality. """ import os import pytest from aracnid_logger import Logger, SlackLogger def test_module_main(): """Tests that Aracnid Logger was imported successfully. """ config_dir = os.path.dirname(__file__) logger = Logger('__main__', config_dir=config_dir) ...
#!/usr/bin/env python """Functional testing framework for command line applications""" import difflib import itertools import optparse import os import re import signal import subprocess import sys import shutil import time import tempfile try: import configparser except ImportError: import ConfigParser as co...
import abc from collections import OrderedDict from typing import Iterable,MutableMapping from torch import nn as nn from rlkit.core.batch_rl_algorithm import BatchRLAlgorithm from rlkit.core.batch_rl_algorithm_modenv import BatchRLAlgorithmModEnv from rlkit.core.offline_rl_algorithm import BatchOfflineRLAlgorithm fro...
import os from dotenv import load_dotenv, find_dotenv from fastapi import FastAPI from starlette.middleware.cors import CORSMiddleware from starlette.responses import RedirectResponse import spacy import uvicorn from app.models import AzureSearchDocumentsRequest, AzureSearchDocumentsResponse load_dotenv(find_dotenv...
from litex.soc.cores.cpu.ibex.core import Ibex
import heapq import time import uuid import asyncio class Timer: def __init__(self): self.timerList = list() self.d = dict() # ratio:间隔,runSize:次数 def addTimer(self, func, args: list, ratio=1, runSize=-1): if ratio == 0: raise while (uid := uuid.uuid4()) in sel...
import numpy as np import csv # import matplotlib.pyplot as plt def get_gt_infos(cfg, dataset): ''' :param dataset: dataset object :param cfg: object containing model config information :return: gt_infos--containing gt boxes that have labels corresponding to the classes of interest, as well as the ...
from .color import Color import random import time class Animation: def on_listen(self, provider): provider.clear_all() groups = int(provider.run_params.num_leds / 3) while provider.run_params.curr_state == "ON_LISTEN": for i in range(0, 3): for g in range(0, gro...
import json import re import os import time import pygame from . import logic from random import randrange from settings import * class Menu: def __init__(self, game): """ Class which represents the menu. :param game: Game class that allows connection between game logic and me...
""" List Exercise 1 Implementieren Sie die Funktion list_from_range(), um damit eine Liste mit allen Elementen von 'min' bis und mit 'max' zu erstellen. Verwenden Sie List.append() und benutzen Sie die nachfolgenden Tests zur Kontrolle. """ def list_from_range(min, max): my_list = [] for element in range(min...
# -*- encoding: utf-8 -*- import logging from celery import task from checkout.models import ObjectPaymentPlanInstalment logger = logging.getLogger(__name__) @task() def process_payments(): logger.info('process_payments') ObjectPaymentPlanInstalment.objects.process_payments() @task() def refresh_card_exp...
# coding: utf-8 import gym from gym import wrappers import random import math import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable import torch.nn.functional as F import matplotlib.pyplot as plt from collections import deque import numpy as np env = gym.make('CartPole-v...
import dropbox from dropbox import DropboxOAuth2FlowNoRedirect from papergit.config import config class Dropbox: """ The base dropbox class to access. """ def __init__(self): self.dbx = None def initialize(self): assert config.initialized self.dbx = dropbox.Dropbox(self.g...
from dbca_utils.utils import env import dj_database_url import os from pathlib import Path import sys # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = str(Path(__file__).resolve().parents[1]) PROJECT_DIR = str(Path(__file__).resolve().parents[0]) # Add PROJECT_DIR to the system path. ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Python version: 3.6 # import matplotlib # matplotlib.use('Agg') # import matplotlib.pyplot as plt import copy import os import pickle import itertools import numpy as np import pandas as pd from tqdm import tqdm from scipy.stats import mode from torchvision import datase...
from typing import Dict, List import pytest import torch from torch.optim import AdamW from bert_summarizer.config.bertsum import BertSumAbsConfig from bert_summarizer.models.bertsum import BertSumAbs from bert_summarizer.trainers.lr_lambda import ( TransformerScheduler, get_transformer_schedule_with_warmup, ...
# Faça um programa que leia um numero inteiro qualquer e mostre na tela a sua tabuada taboada = int(input('\nDigite o número da taboada: ')) n1 = taboada * 1 n2 = taboada * 2 n3 = taboada * 3 n4 = taboada * 4 n5 = taboada * 5 n6 = taboada * 6 n7 = taboada * 7 n8 = taboada * 8 n9 = taboada * 9 n10 = taboada * 10 prin...
import asyncio import hashlib import logging import time import os from aiohttp import WSMsgType from aiohttp.web import ( WebSocketResponse, json_response, FileResponse, Response, ) logger = logging.getLogger('ira') TEMPLATE_ROOT = os.path.join( os.path.dirname(__file__), 'templates', ) FR...
from __future__ import division import numpy as np import pdb import matplotlib.pyplot as plt import matplotlib.image as mpimg def final_l2(path1, path2): row1 = path1[-1] row2 = path2[-1] return np.linalg.norm((row2.x.item() - row1.x, row2.y.item() - row1.y)) def average_l2(path1, path2, n_predictions)...
class ButtonMapper: """ Used to build a dictonary of button roles to the raw buttons for the controller This is performing well and exiting its thread properly """ def __init__(self): """ Contains a list of all possible buttons that could be mapped to check against the user...
# This script will use a list of strains in order to generate the model files for the strains. # All files generated will be put into the "out" directory in the main application. # Why? Generating the needed data outside of minecraft means less delay when loading the mod. # I could do it all in the mod itself, but why...
from .falcon import FalconAPI, StreamManagementThread from .worker import WorkerThread from .queue import falcon_events from .config import config from .backends import Backends from .falcon_data import FalconCache if __name__ == "__main__": # Central to the fig architecture is a message queue (falcon_events). GC...
# coding=utf-8 # Copyright 2016 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import subprocess im...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
""" Handling a Bank Account """ class Account: # parent class def __init__(self, title=None, balance=0): self.title = title self.balance = balance # withdrawal method subtracts the amount from the balance def withdrawal(self, amount): self.balance = self.balance - amount # de...
import os import string from typing import Any, Union def random_string( length: int = 64, characters: str = string.ascii_letters + string.digits ) -> str: result_str = "".join(random_choice(characters) for i in range(length)) return result_str def random_int() -> int: """ Select a random intege...
from pathlib import Path import json import pandas as pd from sklearn.utils import Bunch STRATEGY_FILE = "benchmark_strategies.json" PHENOTYPE_INFO = { "ds000228": {"columns": ["Age", "Gender"], "replace": {'Age': 'age', 'Gender': 'gender'}}, "ds000030": {"columns": ["age", "gender...
#! /usr/bin/env python3 from json import loads from biowardrobe_migration.tests.outputs import chipseq_se from biowardrobe_migration.utils.files import norm_path, get_broken_outputs correct, broken = get_broken_outputs(loads(chipseq_se)) print("CORERCT:", correct) print("BROKEN:", broken)
r""" Store input key strokes if we did read more than was required. The input classes `Vt100Input` and `Win32Input` read the input text in chunks of a few kilobytes. This means that if we read input from stdin, it could be that we read a couple of lines (with newlines in between) at once. This creates a problem: pote...
"""This is an example of interface module.""" from abc import ABC, abstractmethod class Interface(ABC): """Interface example.""" @abstractmethod def add(self, a, b): pass @abstractmethod def add_positional(self, a, b, c, d): pass # @abstractmethod # def add_default(self...
import pytest from flake8_import_conventions.errors import generate_message @pytest.mark.parametrize( "number,package_number,alias,expected", [ ( 1, "altair", "alt", "IC001 altair should be imported as `import altair as alt`", ), ( ...