text
stringlengths
3.07k
22.1k
# -*- coding: utf-8 -*- """ Coil module Created on Tue Jan 26 08:31:05 2021 @author: <NAME> """ from __future__ import annotations from typing import List import numpy as np import os import matplotlib.pyplot as plt from ..segment.segment import Segment, Arc, Circle, Line from ..wire.wire import Wire, WireRect, Wi...
import math import torch import pyro from pyro import poutine from pyro.poutine.util import prune_subsample_sites from pyro.util import warn_if_nan from pyro.infer.util import torch_item from pyro.contrib.util import lexpand, rexpand class BlackBoxMutualInformation(object): def __init__( self, model, cr...
import numpy as np import argparse # from rllab.envs.normalized_env import normalize from maci.learners import MADDPG, MAVBAC, MASQL from maci.misc.kernel import adaptive_isotropic_gaussian_kernel from maci.replay_buffers import SimpleReplayBuffer from maci.value_functions.sq_value_function import NNQFunction, NNJoin...
""" Detection of trends: Given prices of X previous hours, will price increase or decrease Y% amount within next Z hours? (1) X = previous prices (2) y = next prices (3) X_norm = X \ X[0] - 1 # Normalize X (4) y_norm = y \ X[0] - 1 # Normalize y (5) Given X_norm, which decision should we take if we know y_norm ? (5....
__author__ = 'allentran' import json import os import re import datetime import unidecode from spacy.en import English import requests import pandas as pd import numpy as np import allen_utils logger = allen_utils.get_logger(__name__) class Interval(object): def __init__(self, start, end): assert isin...
#!/usr/bin/env python3 # # Copyright 2017-2020 GridGain Systems. # # 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 applicab...
# From http://code.activestate.com/recipes/498245/ import collections import functools from itertools import ifilterfalse from heapq import nsmallest from operator import itemgetter class Counter(dict): 'Mapping where default values are zero' def __missing__(self, key): return 0 def lru_cache(maxsi...
from __future__ import absolute_import, division, print_function import six.moves.cPickle as pickle from dxtbx.model import Detector, Panel from libtbx.test_utils import approx_equal from scitbx.array_family import flex def tst_get_gain(detector): detector[0].set_gain(2.0) assert abs(detector[0].get_gain() - 2.0)...
#!/usr/bin/env python """ Compute a density raster for input geometries or sum a property. """ from __future__ import division import affine import click import fiona as fio import numpy as np import rasterio as rio import rasterio.dtypes from rasterio.features import rasterize import str2type.ext def cb_res(ctx...
import matplotlib.pyplot as plt import numpy as np import matplotlib.cm as cm from torch.nn import Softmax2d import torch from os.path import basename class plt_loss(object): def __call__(self, train_loss, valid_loss, figsize=(10, 10), savefig=None, display=False): train_loss=np.array(train_loss) v...
import base64 from collections import namedtuple from datetime import datetime import hashlib import os import secrets import struct import sys import time from fido2.client import Fido2Client from fido2.ctap2 import CTAP2 from fido2.ctap2 import CredentialManagement from fido2.hid import CtapHidDevice from fido2.util...
from defusedcsv import csv import importlib import logging import os import re from pathlib import Path from tempfile import mkstemp from urllib.parse import urlparse import pypandoc from django.apps import apps from django.conf import settings from django.http import Http404, HttpResponse, HttpResponseBadRequest from...
import requests from bs4 import BeautifulSoup import re from tqdm import tqdm import math import json from datetime import datetime # Taken from https://stackoverflow.com/questions/1345827/how-do-i-find-the-time-difference-between-two-datetime-objects-in-python def get_duration( then, now = datetime.now(), interval = ...
from copy import copy from typing import Union import numpy as np from fedot.core.data.data import InputData, OutputData from fedot.core.data.multi_modal import MultiModalData from fedot.core.operations.evaluation.operation_implementations.data_operations.ts_transformations import ts_to_table from fedot.core.reposito...
# This file is part of the P3IV Simulator (https://github.com/fzi-forschungszentrum-informatik/P3IV), # copyright by FZI Forschungszentrum Informatik, licensed under the BSD-3 license (see LICENSE file in main directory) import unittest import numpy as np import matplotlib.pyplot as plt import logging from p3iv_utils_...
# flake8: noqa import json import logging import os import re import shlex import xml.etree.ElementTree as ET from xml.dom import minidom from .. import exception from . import process_provider, util logger = logging.getLogger(__name__) # TODO: NCL-3503: Finish implementation once the other components are figured o...
"""Convenience functions for writing netcdf files.""" import fnmatch import logging import os import iris import numpy as np from .iris_helpers import unify_1d_cubes logger = logging.getLogger(__name__) VAR_KEYS = [ 'long_name', 'units', ] NECESSARY_KEYS = VAR_KEYS + [ 'dataset', 'filename', 'pr...
import os import sys import json import traceback import argparse import time import multiprocessing import ray from ray import tune from ray.tune.schedulers import AsyncHyperBandScheduler from ray.tune.suggest.hyperopt import HyperOptSearch from ray.tune.suggest import ConcurrencyLimiter from hyperopt import hp fro...
import numpy as np import matplotlib.pyplot as plt import uncertainties from scipy.signal import find_peaks from scipy.optimize import curve_fit import scipy.constants as sc import scipy.integrate as integrate from uncertainties import ufloat from uncertainties import unumpy as unp from uncertainties.unumpy import nomi...
import scipy.stats as ss import numpy as np def read_data(path): file = open(path) lines = file.readlines() file.close() dic = {} for line in lines[1:]: sl = line.split(',') pid = int(sl[0].split('_')[0]) data_len = float(sl[1]) dic[pid] = data_len return dic def main(): no_data = read_...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # logalyzer: # Parses your bloated HTTP access logs to extract the info you want # about hits from (hopefully) real people instead of just the endless # stream of hackers and bots that passes for web traffic # nowadays. Stores the info in a relational database where you c...
import pygame, sys from pygame.locals import * from pygame import * # Initialisation de la bibliothèque Pygame pygame.init() wait = 0 # Ouverture de la fenêtre Pygame larg_fenetre = 1419 haut_fenetre = 731 fenetre = pygame.display.set_mode((larg_fenetre, haut_fenetre)) # Chargement et collage du fond fond = pygame....
# FIXME[hack]: this is just using a specific keras network as proof of # concept. It has to be modularized and integrated into the framework import os import logging logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) import tensorflow as tf from tensorflow import keras import numpy as np print(f"nu...
''' Function: train the model Author: <NAME> ''' import os import copy import torch import warnings import argparse import torch.nn as nn import torch.distributed as dist from modules import * from cfgs import BuildConfig warnings.filterwarnings('ignore') '''parse arguments in command line''' def parseArgs():...
# Copyright 2018 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file or at # https://developers.google.com/open-source/licenses/bsd from __future__ import absolute_import from __future__ import division from __future__ import p...
import cv2 import numpy as np import glob def comparator(result, groundTruth): """ Compares the background/foreground of 2 grayscale images as states in http://jacarini.dinf.usherbrooke.ca/datasetOverview/ but with some simplification: the shadows and unknown are considered as good classification in e...
""" This file defines the core research contribution """ import matplotlib matplotlib.use('Agg') import math import re import torch from torch import nn from models.encoders import psp_encoders from models.encoders import cond_mappers from models.stylegan2.model import Generator from configs.paths_config im...
from math import gcd, ceil, sqrt from numpy import around, int32, zeros from numpy.random import RandomState from polymod import Poly def isprime(n): """ >>> isprime(1109) True >>> isprime(10**6) False """ # this is slow and basic, but saves the sympy dependency # alternatively, fro...
# 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 t...
import numpy as np from numpy import pi, sin, cos, tan, sqrt, arctan2, arcsin, arctan, arccos, log10 from .orbital_elements import elements, jupiter_oe, saturn_oe, uranus_oe from .utils import * from .transform import cartesian_to_spherical, spherical_to_cartesian, ecliptic_to_equatorial, elements_to_ecliptic, radec_to...
""" some utility functions""" # import paramiko import datetime from defaultlist import defaultlist from collections import defaultdict, Iterable def create_response_dict(code: int, message: str = "", nodes: list = None, links: list = None) -> dict: """ use code, nodes and links to chrate a response dict ...
import os from datetime import datetime from unittest.mock import patch import pytest from slackclient import SlackClient as RealSlackClient from sqlalchemy import create_engine from sqlalchemy.orm import Session import karmabot.commands.topchannels from karmabot.commands.joke import _get_closest_category from karmab...
import abc from contextlib import contextmanager import datetime from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, String, ForeignKey, Float, Integer, DateTime, Enum from . import requests from . import storage RequestsBase = declarative_base() class SQLAlchemyStorage(abc.ABC):...
import scrapy import json import requests import time from spiderUtil import FbrefFixtureResponseWrapper, FbrefMatchResponseWrapper from hashlib import md5 from dateSearch import DateSearch from itertools import permutations from scrapy.http import HtmlResponse class FixturesSpider(scrapy.Spider): name = "Fixtu...
''' Missense variant miner: find missense variants in ExAC, score them using PROVEAN, MutPred and dbNSFP return csv file. ''' from __future__ import print_function import os import pandas as pd import csv import zipfile VCF_HEADER = ['CHROM', 'POS', 'ID', 'REF', 'ALT', 'QUAL', 'FILTER', 'INFO'] # Sets protein ID...
# coding=utf-8 # 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 requ...
# -*- coding: utf-8 -*- # Copyright (C) 2012, <NAME> # # Visvis is distributed under the terms of the (new) BSD License. # The full license can be found in 'license.txt'. """ The WX backend. """ # NOTICE: wx has the same general problem with OpenGl being kinda # unmanaged and frames not being drawn on Gnome. Howev...
# Copyright 2018 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Driver for common sequences for image management on switchable usb port.""" import glob import os import shutil import subprocess import tempfile impo...
from functools import reduce from operator import and_ from operator import or_ import collections import copy import enum import itertools from django.db.models import Q from django.utils.functional import cached_property import django.db.models.query import django.template import django_tables2 as tables from . im...
#!/usr/bin/env python # Core from __future__ import print_function from decimal import * from functools import wraps import logging import math import pprint import random import re import time import ConfigParser # Third-Party import argh from clint.textui import progress import funcy import html2text from PIL im...
import re import os.path import functools import mathutils from math import radians import bpy import pyawd from pyawd.core import * from pyawd.anim import * from pyawd.scene import * from pyawd.geom import * from pyawd.material import * from pyawd.utils.math import * from pyawd.utils.geom import AWDGeomUtil class...
import torch from torch.utils.data import Dataset import os from PIL import Image import numpy as np import PIL import torch.nn as nn from config import opt import pandas as pd import matplotlib.pyplot as plt from pathlib import Path import random import math class TextureDataset(Dataset): """Dataset wrapping ima...
from typing import Dict, Set, Tuple from automaton import abstract __all__ = ["NDFA"] class NonDetTransitions: """Transitions is a wrapper for a graph of moves over non-deterministic state machine.""" def __init__(self, d: Dict[int, Dict[chr, Set[int]]] = None): """Constructor for a non-determinist...
""" PSoC bootloader command line tool This Python file encompasses the command line utility cyflash. If you need to use this package in your own program, then use bootload.py """ import argparse import codecs import time import six import sys import logging import logging.config from builtins import input from cyfl...
from typing import Optional, Tuple from sqlalchemy.orm import Session from sqlalchemy import func from amcat4annotator.models import Unit, User, Annotation, CodingJob, JobSetUnits from amcat4annotator.crud import crud_codingjob class ValidationError(Exception): pass class RuleSet: """ A Rule set encodes...
from ..tools.velocity_embedding import quiver_autoscale, velocity_embedding from ..tools.utils import groups_to_bool from .utils import * from .scatter import scatter from .docs import doc_scatter, doc_params from sklearn.neighbors import NearestNeighbors from scipy.stats import norm as normal from matplotlib import r...
import numpy as np np.random.seed(0) import torch torch.manual_seed(0) from torch.utils.data import Dataset, DataLoader, ConcatDataset, RandomSampler import torchvision import imageio import importlib import random import glob import os import transforms_3d class patch_DS(Dataset): """Implementation of torch...
import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation from mpl_toolkits.mplot3d import Axes3D import numpy as np from RK_Driver import dcm_from_q # Make a 2D plot of the results for the angular velocity # Inputs: # - Time array (time[ N ]) [sec] # - Angular rate array (om_arr[ N ][ 3 ]) [rad/s...
import collections import hashlib import inspect import os import pathlib import click import django from django.conf import settings from django.db import connections from django.db.migrations import executor as django_migration_executor from django.db.migrations import loader as django_migration_loader from django.u...
from ...empty import SingleRoom from ...scene_elements import * from ....utils import PositionAreaSampler, Trajectory from ....playground import PlaygroundRegister import math @PlaygroundRegister.register('test_basic') class Basics(SingleRoom): def __init__(self, size = (200, 200), **playground_params): ...
""" Judge suit: 最好的一组5张牌 cards: 手牌 Card: size=2数组表示(kind, digit) """ from collections import defaultdict import enum import numpy as np from .poker import PokerDigit, PokerKind, PokerCard class TexasLevel(enum.IntEnum): # 皇家同花顺 和 同花顺 可以一起比较 straight_flush = 9 # 同花顺 four = 8 # 4条 full_h...
import sys import os; os.umask(7) # group permisions but that's all import os.path as osp import pdb import json import tqdm import numpy as np import torch import torch.nn.functional as F from dirtorch.utils.convenient import mkdir from dirtorch.utils import common from dirtorch.utils.pytorch_loader import get_load...
import sys import os from pathlib import Path from PyQt5.QtCore import QThread, pyqtSignal from PyQt5.QtWidgets import QApplication, QWidget, QToolTip, QPushButton, QGridLayout, QLineEdit, QLabel from PyQt5.QtGui import QFont from utils import get_chat, get_chat_contents, text_to_speech os.chdir(sys.path[0...
# -*- coding: utf-8 -*- """Generating the training data. This script generates the training data according to the config specifications. Example ------- To run this script, pass in the desired config file as argument:: $ generate baobab/configs/tdlmc_diagonal_config.py --n_data 1000 """ import os, sys import r...
import argparse from evaluator_package.evaluator_utilities import is_ogc import evaluator_package.selection_expression_validator as expr_val import shlex def common_commands_parser(): """The commands common to all parsers in all mode. If an argument has a const value of 'MISSING_USER_DEFINED_VALUE', a value w...
from datetime import datetime, timedelta import pandas as pd import prefect from legal_api.models import Filing from prefect import task, Flow, unmapped from prefect.executors import LocalDaskExecutor from prefect.schedules import IntervalSchedule from config import get_named_config from common.firm_queries import ge...
"""lake/utils.py""" import os import math import random import datetime import torch import numpy as np import matplotlib.pyplot as plt def get_summary_dir(): now = datetime.datetime.now() summary_dir = os.path.join('.', 'runs', now.strftime("%Y%m%d-%H%M%S")) return summary_dir def set_seed(seed): random....
""" Contains classes used for the player selection screen. """ import pygame as pg import yaml from settings import prepare, tools, status_machine, menu_functions from entity import enemy_entity, player from .constants import * FONT = pg.font.Font(prepare.FONTS["Fixedsys500c"], 60) ### SMALL_FONT = pg.font.Font(prep...
from scipy.io import loadmat import numpy as np import pyfftw from scipy.special import erf np.set_string_function(lambda a: str(a.shape), repr=False) def mat_to_npy(file_name): return loadmat(file_name + '.mat')[file_name] def mat_to_npy_vec(file_name): a = mat_to_npy(file_name) return a.reshape(a.sha...
#!/usr/bin/env python3 import os import json import torch from misc_scripts import run_cl_exp, run_rep_exp from utils import get_mini_imagenet, get_omniglot from core_functions.vision import evaluate from core_functions.vision_models import OmniglotCNN, MiniImagenetCNN, ConvBase from core_functions.maml import MAML ...
# coding=utf-8 from __future__ import absolute_import, division, print_function, unicode_literals from threading import Timer import time import os import octoprint.plugin from octoprint.util.version import get_octoprint_version_string from octoprint.util import RepeatedTimer from prometheus_client import Counter, Inf...
import click import json import os import sdc_client from typing import Optional from agent import pipeline, source, streamsets, check_prerequisites from agent.modules.tools import infinite_retry from jsonschema import ValidationError from texttable import Texttable from agent.cli import prompt, preview from sdc_clien...
# 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...
""" """ import copy import random, sys, time import torch import numpy as np from gmpy2 import mpz, powmod, invert, is_prime, random_state, mpz_urandomb, rint_round, log2, gcd, f_mod, f_div, sub, \ mul, add rand = random_state(random.randrange(sys.maxsize)) digits = 10e8 b = 10 class PrivateKey(obj...
# Copyright 2017-2018 FUJTISU LIMITED. # 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 requ...
""" Tests the serialization and deserialization of all the types in Fw/Python/src/fprime/common/models/serialize/ Created on Jun 25, 2020 @author: hpaulson, mstarch """ import json from collections.abc import Iterable import pytest from fprime.common.models.serialize.array_type import ArrayType from fprime.common.mo...
#!/usr/bin/env python3 import argparse import socket as s import math import time import os import logging import statistics import threading import prometheus_client from prometheus_client.samples import Timestamp from pyparsing import * from collections import deque from prometheus_client.core import ( InfoMe...
#!/usr/bin/env python3 """Detect vanishing points in non-Manhattan world. Usage: eval_nyu.py [options] <yaml-config> <checkpoint> eval_nyu.py ( -h | --help ) Arguments: <yaml-config> Path to the yaml hyper-parameter file <checkpoint> Path to the checkpoint Options: -h...
import pytest import logging import json import random import string from typing import List # from flask import FlaskClient from werkzeug.wrappers import Response from . import common ENDPOINT: str = common.BASE_URL + "/depot" @pytest.fixture() def random_depot(): """Return random generated depot""" ret...
import os import pathlib import re from os.path import join as _ from generate_map import generate_dynasty_name_mapping, generate_first_name_mapping from special_escape import generate_printer, generate_encoder encoder = generate_encoder("eu4", "txt") printer = generate_printer("eu4", "txt") # 万能ではないが、とりあえずこれで force...
# # tokenize.py # # Part of the "perky" Python library # Copyright 2018-2021 by <NAME> # import ast import collections import sys token_first_characters = set() c_to_tokens = collections.defaultdict(list) s_to_token = {} tokens = {} token_to_name = {} def token(s, description): base = description.strip().lower...
import pytest import deepdiff import typing from sqlalchemy.orm import Session from mlrun.api import schemas from mlrun.api.db.base import DBInterface from mlrun.api.db.sqldb.models import ( _classes, Function, Project, Run, Artifact, FeatureSet, Feature, Entity, Schedule, ) from te...
import sys import os import torch import yaml from easydict import EasyDict as edict from pytorch_transformers.tokenization_bert import BertTokenizer from vilbert.datasets import ConceptCapLoaderTrain, ConceptCapLoaderVal from vilbert.vilbert import VILBertForVLTasks, BertConfig, BertForMultiModalPreTraining from vilb...
""" Routines for Fourier transform. """ from __future__ import division from ..datatable.wrapping import wrap from ..datatable import column from . import waveforms, specfunc import numpy as np import numpy.fft as fft def truncate_len_pow2(trace, truncate_power=None): """ Truncate trace length to t...
""" Downloads and clips videos from youtube, rumble, bitchute (using yt-dlp) and clips the video using ffmpeg. """ import os import shutil import subprocess import sys import time from concurrent.futures import ThreadPoolExecutor from typing import Optional, Tuple def _find_video_file_from_stdout(stdout: str...
from scipy.spatial.distance import cdist import matplotlib.pyplot as plt from numpy.linalg import eig from PIL import Image import numpy as np import argparse import glob import time import os parser = argparse.ArgumentParser() parser.add_argument("--kernel-type", type=str, default="rbf", help="k...
import pandas as pd import trade_client as tr import settings import logging import processing import time import datetime from joblib import load import csv import warnings warnings.simplefilter(action='ignore', category=pd.core.common.SettingWithCopyWarning) def write_csv(time_str, predict_re...
# -*- coding: utf-8 -* """Implementation of the ``repeat_analysis`` step The ``repeat_analysis`` step takes as the input the results of the ``ngs_mapping`` step (aligned reads in BAM format) and performs repeat expansion analysis. The result are variant files (VCF) with the repeat expansions definitions, and associat...
#!/usr/bin/env python3 # TODO: # - option to only extract given files # - automatically link textures/materials to models # - option to merge a gameobject's multiple models # - option to clobber existing files import sys import os import traceback import subprocess import argparse from io import BytesIO from ...
import random import itertools import collections #OZNAKE #zapis karte: (stevilo, znak) znaki = ['KARA', 'KRIZ', 'SRCE', 'PIK'] stevila = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] oznake_slike = { 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9', 10: '1...
from parlaparser.data_parsers.base_parser import PdfParser from parlaparser import settings from enum import Enum from collections import Counter from datetime import datetime, timedelta import logging import re class ParserState(Enum): META = 1 TITLE = 2 RESULT = 3 CONTENT = 4 VOTE = 5 PRE_TIT...
import logging import json from webcandy import util from flask import ( g, Blueprint, render_template, jsonify, request, url_for ) from werkzeug.exceptions import NotFound from typing import Optional from webcandy.definitions import ROOT_DIR, DATA_DIR from .models import User from .extensions import auth, db fro...
import rospy import actionlib from math import radians import numpy as np import scipy.signal import time import dynamic_reconfigure.client from robot_localization.srv import SetPose from pyquaternion import Quaternion as qt from std_srvs.srv import Empty from gazebo_msgs.msg import ModelState from geometry_msgs.msg ...
import os, sys import numpy as np import time import argparse import traceback import glob import trimesh import math import shutil import json import open3d as o3d from tqdm import tqdm import ctypes import logging from contextlib import closing import multiprocessing as mp from multiprocessing import Pool sys.path...
from common import * # https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py # resnet18 : BasicBlock, [2, 2, 2, 2] # resnet34 : BasicBlock, [3, 4, 6, 3] # resnet50 : Bottleneck [3, 4, 6, 3] # # https://medium.com/neuromation-io-blog/deepglobe-challenge-three-papers-from-neuromation-accepte...
#!/usr/bin/env python3 """Common library for working with numerical vectors and matrices. This module provides functions for operating one-dimensional sequences (vectors) and two-dimensional collections (matrices) of numbers. Examples include calculating dot and cross products and finding the optimal assignment in a ...
# -*- coding:utf-8 -*- """ """ import re import time import numpy as np import pandas as pd from lightgbm import LGBMRegressor, LGBMClassifier from sklearn.impute import SimpleImputer from sklearn.metrics import log_loss, mean_squared_error from sklearn.model_selection import train_test_split from sklearn.preprocessi...
from ..constants import ORG from ..converter import KnowledgePostConverter from knowledge_repo.utils.files import read_text_lines import re def dict_to_yaml(x): yaml = [] for key, value in x.items(): if type(value) == list: yaml += f'{key}:\n' for v in value: ya...
import os import sys import numpy as np from glob import glob from skimage.io import imread from skimage.transform import resize import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers import tensorflow_addons as tfa from tensorflow.keras.utils import to_categorical from tensorflow.ke...
import logging import sys import time import requests from transifex.native.consts import (KEY_CHARACTER_LIMIT, KEY_DEVELOPER_COMMENT, KEY_OCCURRENCES, KEY_TAGS) TRANSIFEX_CDS_HOST = 'https://cds.svc.transifex.net' TRANSIFEX_CDS_URLS = { '...
import os import numpy as np import matplotlib.image as mpimg def listdir_nohidden(path: str, jpg_only=False) -> list: """ returns an alphabetically sorted list of filenames of the unhidden files of a directory optionnal arg : jpg_only. Set on True for only .jpg or .JPG """ if jpg_only: ret...
""" Open compressed files transparently. """ __all__ = ["xopen", "PipedGzipWriter", "PipedGzipReader", "__version__"] import gzip import sys import io import os import bz2 import time import stat import signal import pathlib from subprocess import Popen, PIPE from ._version import version as __version__ try: i...
import gdb import re import gdb.printing class PuTTYMpintPrettyPrinter(gdb.printing.PrettyPrinter): "Pretty-print PuTTY's mp_int type." name = "mp_int" def __init__(self, val): super(PuTTYMpintPrettyPrinter, self).__init__(self.name) self.val = val def to_string(self): ...
# -*- coding: utf-8 -*- # # Copyright (c) 2015 Netheos (http://www.netheos.net) # # 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 req...
""" USAGE:- For FILE mode: python extract_timestamps.py -f <WAV_FILE_PATH> -a <AGGRESSIVENESS_LEVEL> Ex: python extract_timestamps.py -f tts_modi_exp/resampled_16000/PM_Modi/PM_Modi_addresses_the_Nation_on_issues_relating_to_COVID19_PMO.wav -a 1 -------------------------------------------------------------------...
""" Copyright (c) 2018 <NAME> <<EMAIL>> 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 limitation the rights to use, copy, modify, merge, publish, distribut...
from .Beamline import StructuredBeamline import numpy as np from scipy.constants import c from re import findall # lengths: mm # quad strength: T/m # bend angles: deg # Need to handle elements that can have different number of parameters depending on mode class BeamlineParser(object): """ Class that will par...
__author__ = "dwapstra" import io import re import time import logging from unicon.bases.routers.services import BaseService from unicon.core.errors import SubCommandFailure from unicon.eal.dialogs import Dialog, Statement from unicon.logs import UniconStreamHandler, UNICON_LOG_FORMAT from unicon.plugins.generic.ser...
import numpy as np from sklearn.model_selection import train_test_split import seaborn as sns from sklearn.neural_network import MLPRegressor from sklearn.ensemble import ( AdaBoostRegressor, GradientBoostingRegressor, RandomForestRegressor) from sklearn.linear_model import Lasso, OrthogonalMatchingPursuit from roo...
import os import string import random import sys import logging import json import datetime import gevent import websocket from locust import HttpLocust, TaskSet, task, events, Locust from threading import Timer import time logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) logger.info('INIT'...