text stringlengths 3.07k 22.1k |
|---|
from collections import namedtuple, MutableSequence
from .cv import Term, TermSet
def _isclose(x, y, atol=1e-3):
return abs(x - y) < atol
class IsolationWindow(namedtuple("IsolationWindow", ['lower', 'target', 'upper'])):
r"""Describes the m/z interval a precursor ion was isolated from in the precursor sca... |
import dataclasses
from typing import Any, Callable
import jax
import jax.numpy as jnp
from flax import struct
import optax
from daves_rl_lib import networks
from daves_rl_lib import train
from daves_rl_lib import util
@struct.dataclass
class AgentState:
state: Any
step: jnp.ndarray
accumulated_reward: ... |
import math
import torch
import torch.nn.functional as F
from torch import nn, Tensor
from typing import List, Tuple, Dict, Optional
class ImageList(object):
"""
Structure that holds a list of images (of possibly
varying sizes) as a single tensor.
This works by padding the images to the s... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
import json
import logging
import markdown
try:
# Py3k
from html.parser import HTMLParser
except ImportError:
# Py2.7
from HTMLParser import HTMLParser
from pelican import signals
from pelican.readers import MarkdownReader, HTM... |
"""
This file implement a base trainer class.
You should finish `compute_action` and run this file to verify the base trainer is implement correctly.
-----
*2020-2021 Term 1, IERG 5350: Reinforcement Learning. Department of Information Engineering, The Chinese University of
Hong Kong. Course Instructor: Professor <NA... |
from tamarco.core.utils import set_thread_name
try:
from confluent_kafka import Producer
except ImportError: # pragma: no cover
import logging
logging.getLogger("tamarco.init").error(
"Tamarco don't have support for kafka, please reinstall tamarco with support for it"
" > pip install ta... |
import argparse
import datetime
import frontmatter
import jinja2
import logmuse
import os
import re
import subprocess
import sys
import time
import yaml
from collections.abc import Mapping
from datetime import date
from jinja2 import Template
from jinja2.filters import FILTERS, environmentfilter
from logging import ge... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2016 <NAME> and <NAME>
# See License.txt
"""
Access to twitter's real-time streams
-------------------------------------
Connects to twitter's real-time streams for random sample and tracking streams
Requirements:
- depends on authentication module aut... |
# -*- coding: utf-8 -*-
"""Utility functions for ProDEC."""
import functools
import sys
from collections import deque
from itertools import islice
from numbers import Number
from multiprocessing import cpu_count, Manager, Pool
from typing import Callable, List, Optional, Type, Union
import numpy as np
from psutil im... |
import networkx
from collections.abc import Iterable
class NTerminalDevice():
_prefix = ''
_pins = ()
_parameters = {} # name : defaultval
name = ''
pins = {} # name: net
parameters = {} # name : val
@classmethod
def add_parameters(self, parameters):
self._parameters.update(p... |
import sys
import time
import pygame
from pygame.locals import *
from mineblock import *
import os
def resource_path(relative_path):
"""
定义一个读取相对路径的函数
"""
if hasattr(sys, "_MEIPASS"):
base_path = sys._MEIPASS
else:
base_path = os.path.abspath(os.path.dirname(__file... |
"""
Code Generator - https://github.com/wj-Mcat/code-generator
Authors: <NAME> (吴京京) <https://github.com/wj-Mcat>
2020-now @ Copyright wj-Mcat
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
h... |
from tkinter import *
from tkinter.simpledialog import askstring
from datetime import date
from PIL import Image
from PIL import ImageTk
import os, os.path
import tkinter.messagebox
import fnmatch
root = Tk()
root.title("OSWalkpy v1.0")
root.geometry("510x440")
root.resizable(0,0)
labelframe = LabelFrame(root)
labelf... |
"""Engine class for running a matchup game.
Handles player input and manages game state.
"""
import random
class GameEngine():
"""Game Engine.
Runs the game using the game model for data and interacts with the player
through the game console.
Attributes:
model: Data model for the game.
console:... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import mimetypes
from sys import argv
from cleave.http import HttpServer
from cleave.http.handler import HandleRequest
from cleave.http.response import Response
from cleave.debug import Log
class FileStorage(HandleRequest):
BASE_DIR = None
BASE_FILE = No... |
# Data location. Please edit.
# A tfrecord containing tf.Example protos as downloaded from the Waymo dataset
# webpage.
# Replace this path with your own tfrecords.
import tensorflow as tf
from test.models import Model, SimplModel, MultyModel, PercieverBased, MapLess
from test.train import train, train_multymodal
f... |
# Copyright 2020 <NAME>, <NAME>, and <NAME>. 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 app... |
"""
In this file, we gather useful function form multiple sources like internet, our's, etc.
"""
import os
import sys
import logging
import re
import shutil
from collections import Counter, defaultdict
import traceback
import subprocess
import hashlib
logger = logging.getLogger("DRY")
def remove_path_or_file(path)... |
import torch
import gpytorch
from matplotlib import pyplot as plt
from config.modelconfig import *
from train import train, train_dwt_a, train_dwt_d
import copy
import pywt
from tools.evaluator import Evaluator
import time
def test(model, likelihood, test_x):
model.eval()
likelihood.eval()
with torch.n... |
# NTKUtils by not-nef
import ctypes
import re
import tkinter
from functools import partial
import platform
from tkinter import ttk
try:
from win32mica import MICAMODE, ApplyMica
except: pass
from .cfgtools import *
win_error = "Your window specification does not appear to be a tkinter window."
... |
'''
Rhythm helpers
'''
import mido
BASE_RESOLUTION = (2 ** 6) * 3
class AbstractTimeUnit(object):
unit_multiplier = -1
resolution = BASE_RESOLUTION
def __init__(self):
self._dots = 0
self._joined_notes = []
def dot(self):
'''
A dot adds 1/2 of the prior unit
... |
import hand
import players
import board
import deck
import verbose
class Cribbage():
def __init__(self, player_one, player_two):
self.player_one = player_one #players.Player() object
self.player_two = player_two
self.board = board.Classic(self.player_one, self.player_two) ... |
"""Main module."""
import requests
import re
from bs4 import BeautifulSoup
import bibtexparser
from pathlib import Path
import json
from tqdm import tqdm
import multiprocessing as mp
from tqdm.contrib.concurrent import process_map
from acm_dl_searcher._utils import _ensure_data_directory_exists, SEARCH_STRING
# TODO: ... |
""" res_parser_mfdn_v15
Provides parser for mfdn v15 results files.
Language: Python 3
<NAME>
University of Notre Dame
10/06/17 (mac): Created, from res_parser_spncci.py
04/27/18 (mac): Rename parameter Mj to M.
09/06/18 (pjf): Added initial built-in transition extraction.
12/12/18 (... |
"""
Tmo Hackathon: Alexa Guide for Onboarding
"""
from __future__ import print_function
import smtplib
#Name, email, id
user = ("<NAME>", "<EMAIL>","123456")
#subject,link,body
email = ["","",""]
# --------------- Email handler -----------------
def send_email(email, subject, message):
"""Sends email to employee"... |
# -*- coding: utf-8 -*-
"""
Created on Jan 09 10:39 2018
@author(s): <NAME>
"""
import datetime
import cmf
import spotpy
from spotpy.parameter import Uniform
import os
import numpy as np
import pandas as pd
class ScalingTester:
"""
A class to determine how CMF handles different amounts of cells. To test
... |
import obspython as _obs
import threading
import traceback
from . import data as _data
from . import _helper
class Future:
_NOTSET = object()
_EXCEPTION = object()
_INTERRUPT = object()
_WAITING = []
def __init__(self):
self._result = self._NOTSET
self._exception = None
se... |
"""
email-normalize
===============
Library for returning a normalized email-address stripping mailbox provider
specific behaviors such as "Plus addressing" (<EMAIL>).
"""
import asyncio
import copy
import dataclasses
import logging
import operator
import time
import typing
from email import utils
import aiodns
from... |
from datetime import datetime, timedelta
from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
from django.template.defaultfilters import slugify
from django.core.urlresolvers import reverse
from taggit.managers import TaggableManager
from markupfield.fields import M... |
"""
common
~~~~~~
Common utility functions for the imgblender module.
"""
from functools import wraps
from typing import Callable, Union
import numpy as np
# Global data.
X, Y, Z = 2, 1, 0
# Decorators.
def can_fade(fn: Callable) -> Callable:
"""Adjust how much the blend affects the base array."""
@wraps(... |
import sys
from pathlib import Path
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
from datetime import datetime
try:
PLOT_STYLE = True
from bg_mpl_stylesheet.bg_mpl_stylesheet import bg_mpl_style
except ImportError:
PLOT_STYLE = None
fro... |
"""
This is an ML estimate of HKY85 molecular evolutionary parameters.
"""
import time
import numpy as np
import algopy
from scipy import optimize, linalg
# AGCT subsititution counts between human and chimp mitochondrial coding dna.
g_data = np.array([
[2954, 141, 17, 16],
[165, 1110, 5, 2],
... |
import tensorflow as tf
import tensorflow_addons as tfa
from tensorflow.keras import layers
def tfa_sampler(image, coords, mask=False):
''' Value sampler using tfa.image.resampler
Args:
image: tensor with shape (bs*h*w, h/i**2, w/i**2, 1)
coords: coordinates tensor with shape (bs*h*w,, 2r+1, 2r+1,... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Created by <NAME>
from pkg_resources import resource_filename
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from mtoolnote.classes import Annotator, Field, Variant, Parser
from mtoolnote.constants import HUMAN_HEADERS
from mtoolnote.models ... |
import os
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
from enum import Enum
from collections import deque, defaultdict
class PDN:
def __init__(self, L, C, R, VDC, CLK):
self.L = L
self.C = C
self.R = R
self.VDC = VDC
self.CLK... |
import logging
from flask import jsonify, request
import flask_login
import mediacloud.error
from server import app, mc
import server.views.apicache as base_apicache
from server.auth import user_mediacloud_client, user_mediacloud_key
from server.util.request import form_fields_required, api_error_handler, json_error_r... |
# Copyright 2018 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... |
# Copyright (C) 2022 <NAME> <EMAIL> All rights reserved.
from __future__ import absolute_import
import math
from .. import util, util_file
from . import api
from . import core
from . import attr
from . import geo
if util.is_in_maya():
import maya.cmds as cmds
def apply_shading_eng... |
"""
Cozmo protocol connection.
"""
import select
import socket
from datetime import datetime, timedelta
from queue import Queue, Empty
from threading import Thread, Lock
from typing import Optional, Tuple, Any
from .logging import logger, logger_protocol
from .frame import Frame
from .protocol_ast import PacketType... |
import os
import ast as ast39
import time
from typed_ast import ast27
from collections import deque
from urllib import request
from compare_string_version import compareVersion
def ast_parse(code):
# ast related: refer to Python doc >> ast
try:
body = ast39.parse(code).body
this_ast = ast39
... |
# (c) <NAME>
# Distributed under MIT License. See LICENCE file in the root directory for details.
# This module defines classes and functions to identify and search for individual frames of videos.
from subprocess import call
import re
import sys
from typing import List
from .settings import CSV_SEPARATOR, DEFAULT_F... |
"""
obj.py
A hacked-up "Obj" class which represents an entire tree of attributes,
returning an object Obj.Empty (which evaluates to False using bool()) when a
nonexistent attribute is accessed, even for nested attributes:
a = Obj()
if not a.b.c.foo:
print("a.b.c.foo not found.") # this executes; no exception i... |
from __future__ import unicode_literals
try:
import simplejson as json
except ImportError:
import json
from collections import MutableMapping
try:
import simplejson as json
except ImportError:
import json
import sys
from decimal import Decimal
mapping_base = MutableMapping
GEO_INTERFACE_MARKER = "... |
import pandas as pd
import numpy as np
datasets = ['breast', 'campus', 'churn', 'climate',
'compas', 'diabetes', 'german', 'heart',
'stroke', 'student', 'water', 'credit']
from sklearn.tree import DecisionTreeClassifier
from interpret.glassbox import ExplainableBoostingClassifier
from interpr... |
import os
from shutil import copyfile
import subprocess
import time
import mediapipe as mp
import cv2
import numpy as np
# 找出人物位置並置中 調成768*1024
def pretreat(path,output):
mp_pose = mp.solutions.pose
# For static images:
IMAGE_FILES = [f"{path}/{file}"for file in os.listdir(path)]
with ... |
import array
import logging
import os
import subprocess
import time
from os.path import join
import scipy.sparse as sp
# from mtest.utils.data import load_csr, save_csr
from tqdm import tqdm
import faiss
# from ..utils.data import load_sift, save_sift
import numpy as np
logger = logging.getLogger(__name__)
GT_IP_FN... |
from utils import read_data
from advent2019_day15_intcode import run_tape_generator
from typing import NamedTuple, Generator, Dict, Tuple, Union
import numpy as np
from readchar import readkey
import os
import sys
import shutil
import curses
SCREEN_TTY = sys.stdout.isatty()
SCREEN_SIZE = shutil.get_terminal_size((0, ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2016 <NAME> (http://www.jdhp.org)
# This script is provided under the terms and conditions of the MIT license:
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Softw... |
from django.db.models import Q
from django.shortcuts import render
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.authentication import BasicAuthentication
from rest_framework.permissions import IsAuthenticated, IsAuthenticatedOrReadOnly, AllowAny
from rest_framework.resp... |
from drf_yasg.utils import swagger_auto_schema
from social_django.utils import load_strategy, load_backend
from social_core.exceptions import MissingBackend
from social_core.backends.oauth import BaseOAuth1
from django.http import HttpResponseRedirect
from django.conf import settings
from django.core import mail
from ... |
# ---
# jupyter:
# jupytext:
# formats: py:percent,ipynb
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.4.2
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %% [markdown]
# # 1... |
#!/usr/bin/env python
# coding=utf-8
"""
Statistical functions
| Option | Description |
| ------ | ----------- |
| title | stats.py |
| authors | <NAME>, <NAME> |
| date | 2020-03-18 |
"""
from collections import namedtuple
import numpy as np
import matplotlib.pylab as plt
import mne
fro... |
import os.path, shutil, tempfile
_function = type(lambda x:x)
_bifunc = type(repr)
_module = type(shutil)
class TestPermissionError(PermissionError): pass
def argwrap(f):
'''wraps a function in another function, to prevent func.whatever = ... from poluting the original'''
def ans(*args, **kargs):
ret... |
# Copyright 2016 Poznan Supercomputing and Networking Center (PSNC)
#
# 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 a... |
import torch
import torchvision
from torchvision import transforms
import numpy as np
from enum import Enum
# from models.Q_mnist import QMNIST
from models.vae_model_wen import ConvVAE
from utils import print_losses
from utils import freeze_ENC_DEC
from utils import write_train_results
from torch.nn import functional ... |
from ..v1 import configuration
from ..v2 import configuration as configuration2
from ..v1 import ConnectApi
from ..v2 import ConnectApi as ConnectApi2
from ..v1 import LoginApi
from ..v1.rest import ApiException
from .instance import InstanceBase
from .model_manage import ModelManage
from .engine import Engine
from .... |
"""Database models."""
from __future__ import absolute_import, unicode_literals
import peewee
import pytz
from datetime import timedelta
from django.db import models
# from django.db.models import signals
from playhouse import signals
def post_save_handler(sender, instance, created):
print('%s was just saved' % ... |
#
# Copyright(c) 2021 Avalanche Studios.All rights reserved.
# Licensed under the MIT License.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files(the "Software"), to deal
# in the Software without restriction, including without limitat... |
"""
PyAlge
Provides pattern matching through the "Case" class and (minimal support of)
algebraic data type (ADT).
ADT are implemented as namedtuple.
"""
from __future__ import print_function, absolute_import
from collections import namedtuple
import functools
import operator
import tokenize
import inspect
import st... |
from . import util
def get_transaction(tx_id):
"""
Request information about a transaction by ID
:param str tx_id: transaction ID
:return: an instance of :class:`Transaction` class
"""
resource = f'tx/{tx_id}'
tx_data = util.call_api(resource)
return Transaction(tx_data)
def get_tra... |
import argparse
import sys
import code
import readline, rlcompleter
import re
try:
import IPython
use_ipython = True
except ImportError:
use_ipython = False
try:
from twisted.internet import reactor, defer
from autobahn.wamp.types import SubscribeOptions
from autobahn.twisted.wamp import Appli... |
from __future__ import absolute_import, division, print_function
import os
import numpy as np
import h5py as h5
import re
import json
from glob import glob
from tqdm import trange
import shutil
import time
from multiprocessing import Process, Queue, current_process, freeze_support
class Frame(object):
pass
cl... |
# coding: utf-8
# In[ ]:
import csv
import math
import numpy as np
import pandas
import sys
import warnings
from collections import Counter
from csv import reader
from sklearn import tree
from sklearn import decomposition
from sklearn.base import BaseEstimator, ClassifierMixin
from sklearn.utils import check_random... |
import random
from pathlib import Path
from typing import Tuple
import glob
import numpy as np
import cv2
import torch
from torch.utils.data import Dataset
import torchvision.transforms as transforms
import torchvision.transforms.functional as TF
from ganslate.utils.io import make_dataset_of_files
# Config imports
f... |
#!/usr/bin/env python
import rospy
import tf2_ros
import tf.transformations as tft
from geometry_msgs.msg import Pose
from geometry_msgs.msg import TransformStamped
from geometry_msgs.msg import Twist
from sensor_msgs.msg import Joy
import numpy as np
class TwistToTf(object):
def __init__(self):
self._t... |
import pennylane as qml
from pennylane.operation import Channel
from pennylane import numpy as np
import math
eps = 1e-7 # constant
def max_entangled_state(settings, wires):
"""Ansatz function for maximally entangled two-qubit state preparation.
A general ``qml.Rot`` unitary is applied to one-side of a
... |
"""
Handles a single chunk of data (16x16x128 blocks) from a Minecraft save.
For more information about the chunck format:
https://minecraft.gamepedia.com/Chunk_format
"""
from io import BytesIO
from struct import pack
import array
from . import nbt
# Legacy numeric block identifiers
# mapped to alpha identifiers i... |
# -*- coding: utf-8 -*-
"""Main entry point of the ``digestiflow-demux`` application."""
import os
import argparse
import logging
import shutil
import attr
import coloredlogs
import tempfile
import toml
from .api_client import ApiClient
from .exceptions import ApiProblemException
from .bases_mask import BaseMaskConf... |
from utils import TailableProc
import json
import logging
import os
import time
import subprocess
import re
import socket
class PtarmD(TailableProc):
def __init__(self, lightning_dir, bitcoin_dir, port=9735):
TailableProc.__init__(self, lightning_dir, 'ptarmd({}).format(port)')
self.lightning_di... |
# _*_ coding:utf-8 _*_
'''
Codes for signal processing
e.g. get train data, preprocessing...
'''
import logging
from sklearn import preprocessing
import numpy as np
from scipy.signal import stft
from scipy import interpolate
import matplotlib.pyplot as plt
from LoadData import EEGDataSet
class SigProcess:
# @pa... |
import copy
# order should be: x < y < D < Leave < z < G() < A < N
# to provide it, use lexicographic order
class Axis:
X = 'x'
Y = 'y'
DIAGONAL = 'yd'
LEAVE = 'yyLeave'
Z = 'z'
GROWTH = 'zGrowth'
APOPTOSIS = 'zzApoptosis'
NONE = 'zzNone' # for really not existing node
def axis_shor... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2021 The TARTRL 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unle... |
import torch
from torch import nn
import torchvision
import torch.nn.functional as F
class LabelSmoothingCrossEntropy(nn.Module):
def __init__(self, eps=0.1, reduction='mean'):
super(LabelSmoothingCrossEntropy, self).__init__()
self.eps = eps
self.reduction = reduction
def... |
import tensorflow as tf
from dlsgs.transformer.base import TransformerEncoder
from dlsgs.transformer import positional_encoding
class TransformerCritic(tf.keras.layers.Layer):
def __init__(self, params, latent_mode=False, sigmoid=False):
super().__init__()
params = params.copy()
self.par... |
import random
import pygame
import utils
class SnakeEnv:
def __init__(self, snake_head_x, snake_head_y, food_x, food_y):
self.game = Snake(snake_head_x, snake_head_y, food_x, food_y)
self.render = False
def get_actions(self):
return self.game.get_actions()
def reset(self):
... |
import os
import typing
import webbrowser
from svgwrite import shapes, Drawing
from copy import deepcopy
# Typing
StrVector = typing.List[str]
IntVector = typing.List[int]
StringMatrix = typing.List[StrVector]
NumberMatrix = typing.List[IntVector]
CoordinateVector = typing.List[tuple]
# Map the strings
BLOCK = '#'
EX... |
"""
This code is modified from Hengyuan Hu's repository.
https://github.com/hengyuan-hu/bottom-up-attention-vqa
"""
from __future__ import print_function
import os
import json
import _pickle as cPickle
import numpy as np
import src.utils as utils
import warnings
with warnings.catch_warnings():
warnings.filterwarnin... |
import os, math, tempfile
def identify_missing_bids(source_list_filename: str, dest_list_filename: str,
subject_savename: str = None, missing_savename: str = None) -> (list, list):
"""
Given a list of files in the source and the destination, this function creates a list of files whic... |
from __future__ import unicode_literals
from builtins import bytes, dict, list, int, float, str
import base64
import errno
import json
import os.path
import select
import socket
import ssl
import sys
import time
if sys.version_info.major == 2:
class ConnectionRefusedError(Exception):
pass
class SSLEO... |
import os
import csv
import json
import numpy as np
import pickle
import torch
import pdb
from tqdm import tqdm
def msmarco_tokenizer(tokenizer, querys, passages, targets):
query_ids = []
for query in querys:
tokens = tokenizer.tokenize(query.strip())
query_ids.append(tokenizer.convert_tokens_... |
import os
import sys
import numpy as np
from netCDF4 import Dataset, default_fillvals
from datetime import datetime, timedelta
import pathlib
import glob
import tarfile
quick = False
quick = True
path = "/data_ballantine02/miyoshi-t/honda/SCALE-LETKF/AIP_SAFE/realtime_20200825"
path_a = "/data_ballantine02/miyoshi-t... |
import numpy as np
import scipy.ndimage as ndi
import SimpleITK
import warnings
from skimage.measure import regionprops
import cv2
CORRECTION = 255
def nodule_size(nodule):
tmp = nodule.copy()
tmp[tmp != 0] = 255
tmp = tmp.astype(int)
properties = regionprops(tmp)
width = 0.0
height = 0.0
... |
"""Prettifiers for genshinstats api returns.
Fixes the huge problem of outdated field names in the api,
that were leftover from during development
"""
import re
from datetime import datetime
from math import ceil
def _recognize_character_icon(url):
"""Recognizes a character's icon url and returns its name."""
... |
import os
from copy import deepcopy
import xml.etree.ElementTree as ET
import numpy as np
import cv2
import config
dirname_train = config.dirname_trainimage
def transform_image(image):
"""
INPUT : image shape (config.width, config.height, 3) BGR only read by cv2\n
OUTPUT: image shape (3, confi... |
from __future__ import unicode_literals
import uuid
from typing import TYPE_CHECKING
from typing import Union
from django.conf import settings
from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
from django.core.validators import RegexValidator
from djang... |
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 11 19:18:48 2018
@author: Alex
Fit LDA or NNMF
"""
# Code modified from: https://medium.com/mlreview/topic-modeling-with-scikit-learn-e80d33668730
#%% Import packages
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from sklearn.decompositio... |
import math
import random
import time
import subprocess
from datetime import datetime, timedelta
import freesound
import giphy_client
import requests
from giphy_client.rest import ApiException
from googleapiclient.discovery import build
from pafy import pafy
from pixabay import Image
from tqdm import tqdm
import conf... |
import cv2
import time
import yaml
import argparse
import logging
import pkg_resources
from pathlib import Path
import os
from tqdm import tqdm
from moviepy.editor import VideoFileClip
import numpy as np
import glob
from matplotlib import pyplot as plt
from src.tracker import Tracker
from src.preprocessing import Tim... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Component: YLPF
# Package : battm
# Name : UKF
# Author : NBIC
# License : BSD 2-Clause
# -------------------------------------------------------------------
#
# Copyright (C) 2019 NEC Brain Inspired Computing
# Research Alliance Laboratories
# ... |
#!usr/bin/env python3
# -*- coding: UTF-8 -*-
from functools import wraps
from tensorflow.keras.regularizers import l2
from xl_tensorflow.utils.common import compose
from tensorflow.keras import layers, models, backend
import os
from keras_applications.imagenet_utils import _obtain_input_shape
from keras_applications.i... |
"""
config
Utility object for ML project configuration
<NAME> 2021
"""
from collections import OrderedDict
from sortedcontainers import SortedDict
from .logger import Logger
_log = Logger(__file__)
class _ID(object):
pass
no_default = _ID() # creates a unique object which can be used to detect if a default va... |
#/usr/bin/python3
import subprocess
import os
import re
from pathlib import Path
from typing import List, Union
from multiprocessing import Pool
from datetime import datetime
from configparser import ConfigParser
from uuid import uuid4
import random
from itertools import islice
common_aa = "ARNDCQEGHILKMFPSTWYV"
de... |
import os
import sys
import argparse
import re
#import logging
from fuzzywuzzy import process, fuzz
#from nltk.tokenize.treebank import TreebankWordTokenizer
from util import www2fb, processed_text
#tokenizer = TreebankWordTokenizer()
#logger = logging.getLogger()
#logger.disabled = True
def get_indices(src_list, pat... |
from __future__ import annotations
import datetime
import json
import os
import re
from os.path import join
from typing import Any
from urllib.parse import urlparse
import pandas as pd
import yaml
from PIL import Image
from dateutil.tz import tzutc
def tag_parser(source, id, tag, value):
if tag.startswith("VALU... |
# Copyright 2013: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... |
# project: fuzzrl
# Copyright (C) 6/12/18 - 9:03 PM
# Author: bbrighttaer
import random
from collections import OrderedDict
import numpy as np
from fuzzrl.core.io.simdata import *
class Experience:
def __init__(self, agent_id, state, action_probs, action, reward, next_state=None):
"""
Stores an... |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import models
from mlx.od.centernet.decoder import decode
from mlx.od.centernet.encoder import encode
from mlx.od.centernet.loss import loss
from mlx.od.centernet.utils import get_positions, prob2logit
class FCN(nn.Module... |
#!/usr/bin/env python3
import argparse
import math
import os
import pandas as pd
import numpy as np
import soundfile as sf
import sys
default_values = {
'debug': 0,
'mode': 'safe',
'output': 'audio_compare',
}
def dBToFloat(val):
""" "
Calculates a float value ranging from -1.0 to 1.0
Where... |
import datetime
import json
import re
import time
import discord
from utils.enums.Timer import TimerType
from utils.ext import checks
from utils.ext import logs
from utils.ext import standards as std
from utils.ext.context import Context
DISCORD_INVITE = r'(discord(app\.com\/invite|\.com(\/invite)?|\.gg)\/?[a-zA-Z0... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.