content
stringlengths
5
1.05M
from gym.envs.registration import register register( id='snake-v0', entry_point='snake_gym.envs:SnakeEnv', ) register( id='snake-tiled-v0', entry_point='snake_gym.envs:SnakeEnvTiled', )
colors = ["red", "white", "blue"] colors.insert(2,"yellow") print(colors)
#!/usr/bin/env python3 # IBM_PROLOG_BEGIN_TAG # This is an automatically generated prolog. # # $Source: op-test-framework/common/OpTestCronus.py $ # # OpenPOWER Automated Test Project # # Contributors Listed Below - COPYRIGHT 2015 # [+] International Business Machines Corp. # # # Licensed under the Apache License, Vers...
import os from ehive.runnable.IGFBaseProcess import IGFBaseProcess from igf_data.utils.fileutils import copy_remote_file, calculate_file_checksum class TransferAndCheckRemoteBclFile(IGFBaseProcess): ''' A class for transferring files from remote server and checking the file checksum value ''' def param_default...
from base import AlertApp, parse_list, parse_tod, between class GenericAlert(AlertApp): def initialize(self): self.telegram_list = self.args.get("telegram") or [] self.states = parse_list(self.args.get("state")) self.message = self.args.get("message") self.done_message = self.args....
def astronauts(): """Astronauts crews URL from NASA Api""" return "http://api.open-notify.org/astros.json" def locations(): """ISS location from NASA Api""" return "http://api.open-notify.org/iss-now.json"
# 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 th...
import sys if './' not in sys.path: sys.path.append('./') from abc import ABC from scipy.misc import derivative import numpy as np from types import FunctionType, MethodType class NumericalPartialDerivative_txyz(ABC): """ Numerical partial derivative, we call it '4' because we compute a function or metho...
import matplotlib.pyplot as plt from matplotlib import rcParams def plotlib_costobj(df=None, savefig=True, savefilepathandname=None, xname='theta', title='Minimal Total Cost vs. Load Constraint', xlabel='Load Reduction (%) Lower Bound Constraint', ...
#!/usr/bin/env python3 # # Cross Platform and Multi Architecture Advanced Binary Emulation Framework # import json, os, sys from Registry import Registry from qiling.os.windows.const import * from qiling.exception import * from qiling.const import * # Registry Manager reads data from two places # 1. config.json #...
logo = """ ,adPPYba, ,adPPYYba, ,adPPYba, ,adPPYba, ,adPPYYba, 8b,dPPYba, a8" "" "" `Y8 a8P_____88 I8[ "" "" `Y8 88P' "Y8 8b ,adPPPPP88 8PP""""""" `"Y8ba, ,adPPPPP88 88 "8a, ,aa 88, ,88 "8b, ,aa aa ]8I 88, ,88 88 `"Ybbd8"' `"8bbdP"Y8 `"Ybbd8...
""" This script makes a few modifications to the Methane data from 2012-2018. Eventually it will also import new 2019 data from the spreadsheet. Created on May 29th, 2019 """ # Import libraries from fileLoading import loadExcel import pandas as pd import numpy as np import matplotlib.pyplot as plt root = r'C:\Users\A...
import pytest from PIL import Image from fairypptx import constants from fairypptx import Slide, Shape, Shapes, Slides def test_to_image(): slide = Slide() image = slide.to_image() assert isinstance(image, Image.Image) def test_leaf_shapes(): slide = Slides().add(layout=constants.ppLayoutBlank) ...
# -*- coding: utf-8 -*- import math import numpy as np import scipy.special as scipy import torch from torch import Tensor from .faddeeva_erf import FaddeevaErfi from ..global_config import mnn_config def chebyshev_val(x: Tensor, c: Tensor) -> Tensor: """ Evaluate a Chebyshev series at points x x: tenso...
import unittest, sys, time sys.path.extend(['.','..','../..','py']) import h2o_cmd, h2o, h2o_browse as h2b, h2o_import as h2i class Basic(unittest.TestCase): def tearDown(self): h2o.check_sandbox_for_errors() @classmethod def setUpClass(cls): h2o.init(java_heap_GB=12) @classmethod ...
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html # For details: https://github.com/PyCQA/pylint/blob/main/LICENSE # Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt """Everything related to the 'pylint-config' command. Everything in this module is private. """ ...
# 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 # distrib...
# -*- coding: utf-8 -*- """ Descripttion: Author: SijinHuang Date: 2021-12-06 21:19:11 LastEditors: SijinHuang LastEditTime: 2021-12-13 21:40:15 """ import json import numpy as np import insightface from common.dao import fetch_img recognition_model = insightface.model_zoo.get_model('./.insightface/models/buffalo_m/...
# -*- coding: utf-8 -*- # Generated by Django 1.11.18 on 2019-03-05 05:52 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('sass', '0037_auto_20190226_0923'), ('sass', '0036_auto_20190226_0630'), ] operatio...
#!/usr/bin/python import sys import re empty_line_pattern = re.compile(r'\s*$') begin_model_pattern = re.compile(r'begin\(model\((\w+)\)\)') end_model_pattern = re.compile(r'end\(model\((\w+)\)\)') start_models_predicate_pattern = re.compile(r'(\w+)\(') def is_empty_line(line:str)->bool: return empty_line_patter...
import aioredis from .settings import get_broker_settings async def connect_redis() -> aioredis.Redis: broker_settings = get_broker_settings() return await aioredis.create_redis(f"redis://{broker_settings.host}:{broker_settings.port}/{broker_settings.db}")
import gym import numpy as np np.random.seed(2) import copy from mushroom_rl.utils.spaces import Box, Discrete from sklearn.ensemble import ExtraTreesRegressor from ARLO.environment import BaseEnvironment, BaseObservationWrapper from ARLO.block import DataGenerationRandomUniformPolicy, ModelGenerationMushroomOfflineF...
import os from multiprocessing.dummy import Pool as ThreadPool import socket import itertools import urllib.request import array import http.client class ImageDownloader(object): def __init__(self, root_dir='./data', workers=1): self.workers = 1 self.root_dir = root_dir def download_images(s...
from argparse import ArgumentError import sys import typing from advent2021.core import run class BingoCard: ROW_COUNT = 5 COL_COUNT = 5 """Represents a 5 ร— 5 Bingo Card""" def __init__(self, board: typing.List[typing.List[int]]): # Sanity check. :) if len(board) != BingoCard.ROW_COUNT...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Exercise 9.12 from Kane 1985. Answer does not match text. """ from __future__ import division from sympy import Dummy from sympy import expand, symbols from sympy.physics.mechanics import ReferenceFrame, Point from sympy.physics.mechanics import dynamicsymbols from util...
# # @lc app=leetcode id=1507 lang=python3 # # [1507] Reformat Date # # @lc code=start from datetime import datetime from re import sub class Solution: def reformatDate(self, date: str) -> str: return datetime.strptime(sub(r"st|nd|rd|th", "", date), "%d %b %Y").strftime("%Y-%m-%d") # @lc code=end
from abc import ABCMeta, abstractmethod import numpy from PIL import Image from skimage.color import rgb2lab import typing import six @six.add_metaclass(ABCMeta) class BaseDataProcess(object): @abstractmethod def __call__(self, data, test): pass class RandomScaleImageProcess(BaseDataProcess): def...
from ._GMatNonLinearElastic import *
class Solution: # Time complexity: O(log n) where n == target # Space complexity: O(1) def brokenCalc(self, startValue: int, target: int) -> int: res = 0 while target > startValue: res += 1 if target % 2: target += 1 else: t...
id = 1 class Patient( object ): def __init__( self, id, name='Alex', age=85 ): #This is the constructor of the object self.name = name self.age = age self.id = id def printDetails( self ): print('Name:'+self.name) print('Age:'+str(self.age)) p1 = Patient(id)...
import os from unittest.mock import patch from urllib.parse import urlsplit, urlunsplit from alembic import command from alembic.config import Config from pytest import fixture from sqlalchemy import create_engine, text try: import asyncpg # noqa from sqlalchemy.ext.asyncio import create_async_engine as...
import asyncio import datetime from pyrogram.errors import FloodWait, UserNotParticipant from pyrogram.types import Message from pytgcalls import StreamType from pytgcalls.exceptions import NoActiveGroupCall from pytgcalls.types.input_stream import AudioPiped, AudioVideoPiped from .calls import Call from database.lan...
""" Module that provides a class that filters profanities Source: https://stackoverflow.com/a/3533322 """ __author__ = "leoluk" __version__ = '0.0.1' import random import re class ProfanitiesFilter(object): def __init__(self, filterlist, ignore_case=True, replacements="$@%-?!", complete=True, ...
"""925. Long Pressed Name https://leetcode.com/problems/long-pressed-name/ Your friend is typing his name into a keyboard. Sometimes, when typing a character c, the key might get long pressed, and the character will be typed 1 or more times. You examine the typed characters of the keyboard. Return True if it is possi...
from Queue import CodaListaCollegata from Queue import CodaArrayList from Queue import CodaArrayList_deque from time import time #global functions def enqueueTest(q,n=50000): start = time() for i in range(n): q.enqueue(i) elapsed = time() - start print("Required time:", elapsed, "seconds.") d...
#!/usr/bin/env python # -*- coding: utf-8 -*- from functools import wraps from flask import abort from flask_login import current_user from .models import User def role_required(role): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): if not current_user.is_...
expected_output = { "r5-s": { "name": "r5-s", "color": 102, "end_point": "5.5.5.5", "owners": "CLI", "status": { "admin": "up", "operational": { "state": "up", "time_for_state": "20:10:54", "since": "08-2...
from collections import deque, namedtuple ExploreItem = namedtuple('ExploreItem', ['coordinates', 'distance']) def find_path(walls, start_coordinates, end_coordinates): '''Finds the length of the shortest path from start_coordinates to end_coordinates. >>> t = True; f = False >>> find_path([[f, f, f], [f...
# The prime factors of 13195 are 5, 7, 13 and 29. # What is the largest prime factor of the number 600851475143 ? import math def main(num): factors = [] # True condition ok here as all numbers should have prime factors # so return should always exit the loop while True: n = spf(num) # ...
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2018-11-17 20:54 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django_countries.fields import mirrors.fields class Migration(migrations.Migration): initial = True ...
import re from django.db import models from .settings import * from django.conf import settings from django.template import Template from django.utils.translation import ugettext_lazy as _ from cms.models import CMSPlugin try: from urllib.parse import urlencode except ImportError: # py2 from urllib import...
""" Module initialization that adjusts the path for beets. """ from pkgutil import extend_path __path__ = extend_path(__path__, __name__)
""" Copyright 2017 Akamai Technologies, 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 ...
#! /usr/bin/env python3 # -*- coding: utf-8 -*- """ representation of coordinates as latitude/longitude distance calculations: https://gist.github.com/rochacbruno/2883505 more calculations: http://www.movable-type.co.uk/scripts/latlong.html """ import math def norm_lat(lat): return max(-90.0, min(lat, 90.0)) d...
import os import tensorflow as tf from config.config_Faster_RCNN import cfg import random import numpy as np import skimage.io from utils.faster_rcnn.anchors import all_anchor_conner, anchor_labels_process import cv2 import xml.etree.ElementTree as ET class preprocess: def __init__(self, is_train=True): #...
import argparse parser = argparse.ArgumentParser() parser.add_argument('text', help='Message to encode') parser.add_argument('-d', '--dict', dest='dict', default=None, help='Language file to load') parser.add_argument('-m', '--mark', dest='mark', default='*', help='Mark character/string') parser.add_argument('-s', '--...
from typing import Any from malib.algorithm.common.trainer import Trainer from malib.algorithm.ppo.loss import PPOLoss from malib.algorithm.ppo.policy import PPO class PPOTrainer(Trainer): def __init__(self, tid): super(PPOTrainer, self).__init__(tid) self._loss = PPOLoss() self.cnt = 0 ...
#!/usr/bin/python print "deprecated since version 1.1.0 of mtools. Use 'mlogfilter <logfile> <logfile> ...' instead."
import pytest from rollo.constraints import Constraints from deap import base, creator from collections import OrderedDict test_output_dict = OrderedDict( { "packing_fraction": "openmc", "keff": "openmc", "num_batches": "openmc", "max_temp": "moltres", } ) test_input_constraint...
"""Do some stuff with polynomials. Going to try and write up a nice docstring to get rid of the error. We'll see... It worked! """ import sys # 6.00 Problem Set 2 # # Successive Approximation def call_poly(): """Get poly inputs and send them to compute_deriv function.""" print("Enter your polynomial coeffic...
from clickatell import Transport class Rest(Transport): """ Provides access to the Clickatell REST API """ def __init__(self, apiKey): """ Construct a new API instance with the auth key of the API :param str apiKey: The auth key """ self.apiKey = apiKey ...
from compare import * my_language = language("patterns/patterns_en.txt", "entities/entities_en.txt") print(compare(input("> "), [["Hello", "Hi", "Hey"], "bot"], entities = my_language.entities))
#!/usr/bin/env python #-*- coding:utf-8 -*- from array import array import socket import os.path from base import * class Board(object): def __init__(self, history_file=None): self.board = array("B", (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)) self.history = array("B") self.history_file = history_f...
import os from tensorflow import keras def train_model(x_train, y_train, x_val, y_val, model, params, logger): """ Trains a TensorFlow model Parameters ---------- x_train : Training data y_train : Training labels x_val : Validation data y_val : Validation labels model : TensorFlo...
# Reproduce results from Fig 11 of # M. Bocquet and P. Sakov (2012): "Combining inflation-free and # iterative ensemble Kalman filters for strongly nonlinear systems" from mods.Lorenz63.sak12 import setup # The only diff to sak12 is R: boc12 uses 1 and 8, sak12 uses 2 (and 8) from common import * setup.h.noise.C = C...
import os.path import torch.utils.data from .data_loader import get_transform_dataset from ..transforms import augment_collate class AddaDataLoader(object): def __init__(self, net_transform, dataset, rootdir, downscale, crop_size=None, resize=None, batch_size=1, shuffle=False, num_workers=2, half_cro...
import cv2 import numpy as np import matplotlib.pylab as plt # src = cv2.imread("bottle.jpg") # image = cv2.imread('bottle.jpg',cv2.IMREAD_COLOR) # image = cv2.bilateralFilter(image,9,75,75) # original = np.copy(image) # if image is None: # print ('Can not read/find the image.') # exit(-1) # hsv_image = cv2....
# -*- extra stuff goes here -*- from zope.i18nmessageid import MessageFactory fileMessageFactory = MessageFactory('collective.geo.file') def initialize(context): """Initializer called when used as a Zope 2 product."""
import os, sys, re, subprocess from typing import List def get_pycore_dir() -> str: dirs = os.listdir("/tmp") pycore_dir = None for dir in dirs: ## Example: pycore.32777 if dir[:7] == "pycore.": pycore_dir = dir break if pycore_dir is None: print("pycore directory not found: Have you s...
import logging import random import re import warnings from concurrent.futures import ProcessPoolExecutor from contextlib import contextmanager from dataclasses import dataclass from decimal import ROUND_HALF_UP from functools import lru_cache, partial from io import BytesIO from itertools import islice from math impor...
#!/usr/bin/env python import argparse from pathlib import Path import tensorflow as tf from gym import wrappers from yarll.environment.registration import make class ModelRunner(object): """ Run an already learned model. Currently only supports one variation of an environment. """ def __init__(sel...
import librosa import math import numpy as np class AudioFeatureExtractor(object): def __init__(self, sample_rate=16e3, window_size=0.02, window_stride=0.01, window='hamming', feat_type='mfcc', normalize_audio=True ): self.sample_rate = sample_rate self.window_size = window_s...
import threading import os global _collector_thread _collector_thread = None def find(folder, fileName): print "Search for : " + fileName + " in " + folder global _collector_thread if _collector_thread != None: _collector_thread.stop() print "GOT HERE" _collector_thread = ParsingThread([], folder, 30) _colle...
from django.conf import settings from django.conf.urls import include from django.conf.urls.static import static from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path('agenda/', include('apps.agenda.urls')), ...
# *-* encoding utf-8 # Author: kalizar78 from __future__ import print_function import tensorflow as tf import numpy as np ##################################################################### # LSTM Specific initializations using numpy ##################################################################### # I forgot wh...
# origin https://primes.utm.edu/lists/small/millions/ file = open("primes2.txt", "r") full = file.read() file.close() lines = full.split("\n\n") texto = "" for x in range(0, len(lines)): temp = lines[x].split(" ") while "" in temp: temp.remove("") texto += "\n" for x in temp: texto += x...
from discord.ext import commands import re import discord import random import typing import emoji import unicodedata import textwrap import contextlib import io import asyncio import async_tio import itertools import os import base64 import secrets import utils from difflib import SequenceMatcher from discord.ext.comm...
# parsetab.py # This file is automatically generated. Do not edit. # pylint: disable=W,C,R _tabversion = '3.10' _lr_method = 'LALR' _lr_signature = 'nonassocINleft+-left*/rightUMINUSrightUPLUSright^DEL EQUATION FLOAT IMPORT IN RAWSTR RESET SI SOLVE STRING UNIVARIATE_FN VARIABLESstart : statement\n | comm...
import numpy as np from tqdm import tqdm def angle_to_state(angle): return int(30 * ((angle + np.pi) / (2 * np.pi) % 1)) # Discretization of the angle space def vel(theta, theta_0=0, theta_dead=np.pi / 12): return 1 - np.exp(-(theta - theta_0) ** 2 / theta_dead) def rew(theta, theta_0=0, theta_dead=np.pi...
import matplotlib.pyplot as plt import networkx as nx def graph(tmp_graph): """Plots networkx graph.""" node_list = [ tmp_graph.nodes[idx]['label'] for idx in range(len(tmp_graph.nodes))] nx.draw_networkx(tmp_graph) print(dict(zip(range(len(node_list)), node_list))) def similarity...
import turtle as t import random te = t. Turtle() te. shape("turtle") #์•…๋‹น ๊ฑฐ๋ถ์ด(๋นจ๊ฐ„์ƒ‰) te. color("red") te. speed(0) te. up() te. goto(0, 200) ts = t. Turtle() #๋จน์ด(์ดˆ๋ก์ƒ‰ ๋™๊ทธ๋ผ๋ฏธ) ts. shape("circle") ts. color("green") ts. speed(0) ts. up() ts. goto(0, -200) def turn_right(): t. seth(0) de...
from output.models.nist_data.atomic.positive_integer.schema_instance.nistschema_sv_iv_atomic_positive_integer_min_exclusive_5_xsd.nistschema_sv_iv_atomic_positive_integer_min_exclusive_5 import NistschemaSvIvAtomicPositiveIntegerMinExclusive5 __all__ = [ "NistschemaSvIvAtomicPositiveIntegerMinExclusive5", ]
# -*- coding: utf-8 -*- """ Created on Fri Jul 23 15:13:36 2021 @author: RWint """ import pandas as pd import warnings from pandas.core.common import SettingWithCopyWarning warnings.simplefilter(action="ignore", category=SettingWithCopyWarning) def preproc_exprs_matrix(exprs_matrix, exprs_percentil...
# Copyright 2014 Facebook, Inc. # You are hereby granted a non-exclusive, worldwide, royalty-free license to # use, copy, modify, and distribute this software in source code or binary # form for use in connection with the web services and APIs provided by # Facebook. # As with any software that integrates with the Fa...
# -*- coding: utf-8 -*- from typing import Dict import os import pkg_resources from bag.design import Module yaml_file = pkg_resources.resource_filename(__name__, os.path.join('netlist_info', 'clk_invamp_diff_reset...
# # soaplib - Copyright (C) Soaplib contributors. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This l...
# Erica Brophy # BMI_503 # 09/28/19 # Calculator Project 1 import sys class MyCalculator: # define functions to parse equation based on * and / > + and - import re calc_input = input("Enter your equation that you would like the calculator to solve: \n") calc_list = re.findall("[a-zA-Z]|[\d\.]+|[^a-z...
email_header = """ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <title>Traveling Strategy</title> </head> """ email_exterior_bg = """ <body leftma...
# Standard Library import logging # Third-Party import pydf from rest_framework_json_api.filters import OrderingFilter from rest_framework_json_api.django_filters import DjangoFilterBackend from django_fsm import TransitionNotAllowed from dry_rest_permissions.generics import DRYPermissions from rest_framework import ...
from ontobio import OntologyFactory from ontobio.tsv_expander import expand_tsv import csv INPUT = "tests/resources/data_table.tsv" OUTPUT = "tests/resources/data_table-expanded.tsv" def test_expand(): factory = OntologyFactory() ontobj = factory.create("tests/resources/goslim_pombe.json") expand_tsv(INP...
# Copyright 2017 Brocade Communications Systems, 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 la...
import util class test_views: """ Test accumulate of all kind of views""" def init(self): for cmd, shape in util.gen_random_arrays("R", 4, dtype="np.float32"): cmd = "R = bh.random.RandomState(42); a = %s; " % cmd for i in range(len(shape)): yield (cmd, i) ...
#!/usr/bin/env python def main(): res = 0 a = 3 b = 2 digsA = 1 digsB = 1 ceilA = 10 ceilB = 10 it = 1 while(it < 1000): it += 1 b += a; a += 2*(b-a) if(a > ceilA): digsA += 1 ceilA *= 10 if(b > ceilB): dig...
from shexer.core.class_shexer import ClassShexer def get_class_shexer(class_instances_target_dict, class_profile_dict): class_count_dicts = {} for a_class_key in class_instances_target_dict: class_count_dicts[a_class_key] = len(class_instances_target_dict[a_class_key]) return ClassShexer( ...
from .dataPipeline import DataPipeline from .moleculePipeline import MoleculePipeline __all__ = ['DataPipeline', 'MoleculePipeline']
#!/usr/bin/env python3 # Copyright (c) 2014-2015 The Bitcoin Core developers # Copyright (c) 2015-2017 The Bitcoin Unlimited developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. import test_framework.loginit # Test mempool li...
#!/usr/bin/env python3 # https://codeforces.com/problemset/problem/761/A # ้ข˜็›ฎๆ˜ฏinteral, ไธไธ€ๅฎšๆ˜ฏไปŽ1ๅผ€ๅง‹, ๆ‰€ไปฅไน‹ๅ‰ๅš้”™ไบ†; ไฝ†่ฟ˜ๆ˜ฏๅพˆๆ— ่Š็š„้ข˜็›ฎ # 0 0 ไธๅฏ่ƒฝ, ้”™็ฌฌไบŒๆฌก def f(l): a,b = l return (b==a+1 or b==a or b==a-1) and (a+b>0) l = list(map(int,input().split())) print('YES' if f(l) else 'NO')
"""Example using Bio.SeqIO to load a FASTA file as a dictionary. An example function (get_accession_num) is defined to demonstrate a non-trivial naming scheme where the dictionary key is based on the record identifier. The first version uses Bio.SeqIO.parse() and loads the entire FASTA file into memory as a Python di...
import os import numpy import sysconfig from Cython.Build import cythonize from Cython.Distutils import build_ext from distutils.core import Extension, setup # pylint: disable=import-error,no-name-in-module def get_ext_filename_without_platform_suffix(filename): name, ext = os.path.splitext(filename) ext_suffix ...
"""Asymetrically course searching algorithm using Pre-trained MS MARCO models.""" import time import numpy as np import torch from sentence_transformers import SentenceTransformer, util from sqrl import create_app from sqrl.models import Campus, Course def get_courses() -> list[Course]: """Returns a list of cou...
# encoding: utf-8 """Module to compute salary-based recommendations using 1 - CDF (CDF = Cumulative Distribution Function). Design doc : https://docs.google.com/document/d/1WjyjxYOzC0_98ULXVr4nsmGwcDsN2qm-sXuTb__1nkE The recommendation can be summed up in several steps: Step 1 : Check for each available salaries, how ...
""" PRIVATE MODULE: do not import (from) it directly. This module contains the ``BaseMatcher``class. """ from typing import Any, Optional from jacked._compatibility_impl import get_naked_class from jacked._injectable import Injectable from jacked._container import Container class BaseMatcher: """ This is the...
import os from deriva.core import stob from deriva.core.utils.mime_utils import guess_content_type from deriva.transfer.download import DerivaDownloadError, DerivaDownloadConfigurationError from deriva.transfer.download.processors.base_processor import BaseProcessor, LOCAL_PATH_KEY, SOURCE_URL_KEY from bdbag import bdb...
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: agent/api/proto/v1/protoconf_service.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _mes...
# 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...
''' Finite state gridworld environment with multiple agents. ''' import gym import numpy as np class GridWorld(gym.Env): ''' Finite 2D grid with each agent occupying a point in the grid. ''' def __init__(self, grid_size, start_positions): self.grid_size = np.array(grid_size, dtype=int) ...
#!/usr/bin/env python ''' Originally this was used as the main driver for the trading logic. It's sole purpose in life was to determine if you should buy or sell. Currently that logic has been removed while I rework the algorithm. ''' import getMtGoxRequest as req import time import dbConnection as db from decimal ...
from backend.views import style, test def setup_routes(app): # GET routes: app.router.add_get('/test', test) # POST routes: app.router.add_post('/style', style)
class BackupNotFoundError(Exception): def __init__(self): super().__init__("backup not found") class BackupsFailureInGroupError(Exception): def __init__(self, completed_backups, exceptions): """ :param completed_backups: dictionary of completed backups. ...
from aiogram.dispatcher.filters.state import StatesGroup, State class States(StatesGroup): get_amount_balance_targ = State() class Mailing(StatesGroup): mailing_text_targ = State() class SendMessage(StatesGroup): send_message_targ = State() class Phone(StatesGroup): get_phone_targ = State() class A...