text
stringlengths
3.07k
12.6k
"""Utility functions for CLI commands.""" from os.path import expanduser from types import FrameType from typing import Any, Callable, Iterator, Optional, Sequence, Type, Union import functools import itertools import logging import pathlib import re import sys import warnings from click.core import ParameterSource fr...
# -*- coding: utf-8 -*- # # Twitter画像ダウンローダー # from lib.UserHandle import UserHandle from lib.DBQueue import DBQueue from lib.Clawler import Clawler from lib.Saver import Saver from lib.config import PathConfig from datetime import datetime import time, threading, logging endReq = False #終了リクエスト with open(PathConfig.P...
""" Contains classes for retrieving data from file (or wherever it's stored) """ from abc import ABC, abstractmethod from dataclasses import dataclass from pathlib import Path from typing import List, Union import h5py import numpy as np import pandas as pd from pandas.core.frame import DataFrame @dataclass class Re...
import glob import os import logging import subprocess import click from rich.console import Console from rich.markdown import Markdown from hint_cli import repo, config_manager from hint_cli.format import format_for_stdout from markdown import parser logger = logging.getLogger(__name__) conf = None def print_mar...
""" Copyright [2019-2020] EMBL-European Bioinformatics Institute 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 ...
#!/usr/bin/env python3 '''Animates distances and measurment quality''' from rplidar import RPLidar import matplotlib.pyplot as plt import numpy as np import matplotlib.animation as animation import RPi.GPIO as GPIO import time import pygame from freenect import sync_get_depth as get_depth import numpy as np import sys...
# Copyright 2018 Gehtsoft USA LLC # Licensed under the license derived from 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://fxcodebase.com/licenses/open-source/license.html # Unless required by ap...
''' Define the Layers ''' import torch.nn as nn import torch from transformer.SubLayers import MultiHeadAttention, PositionwiseFeedForward __author__ = "<NAME>" class EncoderLayer(nn.Module): ''' Compose with two layers ''' def __init__(self, d_model, d_inner, n_head, d_k, d_v, dropout=0.1): super(E...
import sys import numpy as np import pandas as pd import pickle import re import nltk from nltk.corpus import stopwords from nltk.stem.wordnet import WordNetLemmatizer from nltk.tokenize import word_tokenize nltk.download('punkt') nltk.download('stopwords') nltk.download('wordnet') from sqlalchemy import create_engi...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Dec 8 17:07:19 2019 @author: nmei """ import numpy as np import pandas as pd from scipy import stats def resample_ttest(x,baseline = 0.5,n_ps = 100,n_permutation = 10000,one_tail = False, n_jobs = 12, verbose = 0): """ http:...
# -*- coding: utf-8 -*- # Copyright (c) 2020. Distributed under the terms of the MIT License. import itertools from dataclasses import dataclass from math import sqrt from typing import List, Dict from monty.json import MSONable import plotly.graph_objects as go from vise.analyzer.plot_band_dos import plotly_sanitiz...
from distutils.command.config import config from typing import Callable from unicodedata import name import robosuite as suite from robosuite.wrappers import GymWrapper from robosuite.wrappers import GymWrapperRGBD import stable_baselines3 as sb3 from stable_baselines3.common.vec_env import SubprocVecEnv, VecNormalize,...
import torch import torch.optim as optim from itertools import count import argparse from os.path import join from agent import NSQ from policy import PolicyNet from game import VFGGAME from explorer import Explorer from util import logger from train_new import MACHINE_LABEL_DIR_HOLDOUT, CLASSIFIER_ROOT_HOLDOUT from ...
#!/usr/bin/env python import rospy from std_msgs.msg import String from os import system import tf2_msgs.msg import roslib import cmath as math import geometry_msgs.msg as msgs import turtlesim.srv from darwin_gazebo.darwin import Darwin shoulder_coord = (0.0, 0.0, 0.0) hand_coord = (0.0, 0.0, 0.0) elbow_coord = (0.0...
from argparse import ArgumentParser import os, sys import cv2 import numpy as np import pandas as pd import torch import pytorch_lightning as pl from pytorch_lightning import Trainer, loggers from torchsummary import summary import torch.nn.functional as F sys.path.append('../../loaders/pytorch_lightning/') from data...
import os import csv from collections import OrderedDict from statistics import mean from typing import List def print_hota(d : dict): """Print HOTA fancy way Args: d (dict): HOTA dictionnari in extract_dict list """ upper_line : str = "||" down_line : str = "||" for i,key in enumerate(d.keys...
from django.db import models from django.contrib.auth.models import PermissionsMixin, AbstractBaseUser, BaseUserManager from django.conf import settings UPLOAD_DIRECTORY_PROFILEPHOTO = 'images_profilephoto' UPLOAD_DIRECTORY_ID_CARD_PHOTO = 'images_idcardphoto' class CustomUserManager(BaseUserManager): """ Cus...
""" Author: <NAME> October 29, 2016 Description: Classes and functions to perform basic network abstraction and plotting """ from numpy import pi as pi class network(object): """Class for one dimension network (i.e. a matching network).""" element_array=[] def __init__(self): self.ZP2...
## ## Various utility methods. ## import os, shutil, glob, time, sys, platform, subprocess # ------------------------------------------------------------------ # Windows specific paths. nuget_dir = 'C:/nuget' devenv_dir = 'C:/Program Files (x86)/Microsoft Visual Studio 14.0/Common7/IDE' def set_log_tag(t): glo...
import pygame from pygame.locals import * import sys import random def ball_animation(): global ball_speed_x, ball_speed_y, player_score, opponent_score, score_time ball.x += ball_speed_x ball.y += ball_speed_y if ball.top <= 0 or ball.bottom >= screen_height: pygame.mixer.Sound...
from flask import Blueprint, request, flash, render_template, redirect, url_for, abort from project.users.forms import RegisterForm, LoginForm, EmailForm, PasswordForm from project.models import User from project import db, app from itsdangerous import URLSafeTimedSerializer, BadData from sqlalchemy.exc import Integrit...
#!/usr/bin/python3 import glob import os import re import sys from hashlib import sha1 from stat import S_IREAD, S_IRGRP, S_IROTH from typing import Union, Collection, Match, Dict, Optional, Tuple, Any, Set had_errors = False source_files: set[str] = set() generated_files: set[str] = set() def multisubst(mappings: ...
#!/usr/bin/env python import socket import sys import hashlib import threading from threading import Lock import time import matplotlib matplotlib.use('Agg') import numpy as np import matplotlib.pyplot as plt import otherfunc #globally defined host = [] path = [] tcps = [] port = 80 chunkSize = 10240 #10KB chunks = [...
""" <Policy Iteration> Author: <NAME> (<EMAIL>) Affiliation: University of Pennsylvania """ import numpy as np import seeding def policy_iter(env, discount, threshold, T=5000): V = np.zeros(env.snum) policy = np.random.choice(env.anum, env.snum) np_random, _ = seeding.np_random(None) p_stable = False trans_di...
import pandas as pd from ase import Atoms from dscribe.descriptors import SOAP import numpy as np import sys from ARS import * def func(data, a, b,c,d,e,f,g,h,i,j): return a*np.sin(b*data[0]+c)+ d + e*data[1]**3 + f*data[1]**2 + g*data[1] + h*data[2]**3 + i*data[2]**2 + j*data[2] def func2(data, a, b,c,d,g,j): ...
from pprint import pprint alphabet = {"a":0,"b":0,"c":0,"d":0,"e":0,"f":0,"g":0,"h":0,"i":0,"j":0,\ "k":0,"l":0,"m":0,"n":0,"o":0,"p":0,"q":0,"r":0,"s":0,"t":0,"u":0,"v":0,\ "w":0,"x":0,"y":0,"z":0} alphaFrecuency = {"a":0,"b":0,"c":0,"d":0,"e":0,"f":0,"g":0,"h":0,"i":0,"j":0,\ "k":0,"l":0,"m":0,"n":0,"o":0,"p":0,"q":...
#!/usr/bin/env # -*- coding: utf-8 -*- # Copyright (C) CENATAV, DATYS - All Rights Reserved # Unauthorized copying of this file, via any medium is strictly prohibited # Proprietary and confidential # Written by <NAME> <<EMAIL>>, March 2017 import os import sys from ctypes import ( cdll, # c/c++ types declarat...
############################################################################################## # Created by <NAME> at 2018-12/18 # MIT License # Contain definition of different layer ############################################################################################## import math import numpy as np...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Sep 29 16:47:23 2019 @author: achakrab """ import requests import os import sys from pyspark import SparkContext import json import os import pandas as pd import numpy as np from os import path from PIL import Image import numpy as np import shutil ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json import re import time import redis import requests import traceback localRedis = redis.StrictRedis(host='redis', port=6379, decode_responses=True) download_url_template = "https://raw.githubusercontent.com/{:s}/{:s}/package.json" npm_search_url_template = 'htt...
from enum import IntEnum from blatann.nrf.nrf_types import * from blatann.nrf.nrf_dll_load import driver import blatann.nrf.nrf_driver_types as util from blatann.nrf.nrf_events.generic_events import BLEEvent class GapEvt(BLEEvent): pass class GapEvtAdvReport(GapEvt): evt_id = driver.BLE_GAP_EV...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import division, print_function, absolute_import import string import random from itertools import chain import networkx as nx import pickle import Levenshtein letters = list(string.ascii_lowercase) def out(G): for n in sorted(G) : print(n, G....
import time import torch from torch import nn import tqdm import numpy as np from matplotlib import pyplot as plt from ContentLoss.ResNetLoss import ResNetLoss from ContentLoss.VGGLoss import VGGLoss from Metric.PSNR import PSNR import Metric.pytorch_msssim as torch_SSIM def write_log_for_SRGAN(db_valid_PSNR_SSIM, ...
#!/usr/bin/env python #SETMODE 777 #----------------------------------------------------------------------------------------# #------------------------------------------------------------------------------ HEADER --# """ :author: username :synopsis: A one line summary of what this module does. ...
#!/usr/bin/python3 # Compare two directories (maybe only a subdirectory of them) and add # GitHub annotations where they're different. import argparse import difflib import io import itertools import os.path import sys def annotate_file(output, path, severity, message): print( f'::{severity} file={path},t...
""" The MIT License (MIT) Copyright (c) 2017 <NAME> """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import sys import numpy as np import scipy as scp import logging import torch import torch.nn as nn import torch.nn.functional as F from to...
from base import BaseExpert import numpy as np class TrueExpert(BaseExpert): """docstring for TrueExpert""" def __init__(self, oracle): super(TrueExpert, self).__init__(oracle) def label(self, data, y=None): if y is None: raise Exception("True labels are missing") else...
""" Heap is a binary tree-based data structure, can be implemented using a list. There are 2 types of heaps: - Max-Heap: The key representing the root must be greatest among the keys which present at all of its children. The same rule applies for all the subtrees. - Min-Heap: The key representing the root must be small...
import pytest from pandagg import Mappings from pandagg.document import InnerDocSource, DocumentSource from pandagg.mappings import Text, Long, Date, Keyword, Object, Nested from pandagg.node.mappings import Boolean class User(InnerDocSource): id: int = Long(required=True) signed_up: str = Date() userna...
# # Copyright 1993-2019 NVIDIA Corporation. All rights reserved. # # NOTICE TO LICENSEE: # # This source code and/or documentation ("Licensed Deliverables") are # subject to NVIDIA intellectual property rights under U.S. and # international Copyright laws. # # These Licensed Deliverables contained herein is PROPRIETAR...
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. # Copyright (c) 2022 NVIDIA Corporation. 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:/...
from functools import partial from itertools import product from keras import backend as K import tensorflow as tf def dice_coefficient(y_true, y_pred, smooth=1.): y_true_f = K.flatten(y_true) y_pred_f = K.flatten(y_pred) intersection = K.sum(y_true_f * y_pred_f) return (2. * intersection + smooth)...
#!/usr/bin/python3 """ Start VLC on a remote host and send commands """ import re import os import sys import time import shlex import base64 import atexit import shutil import logging import tempfile import argparse import subprocess import http.client try: from pyftpdlib.authorizers import DummyAuthorizer ...
#! /usr/bin/env python3 """This script demonstrates Aboleth's imputation layers.""" import logging import tensorflow as tf import numpy as np from sklearn.datasets import fetch_covtype from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score, log_loss, confusion_matrix from sklea...
from __future__ import annotations import ast from collections import deque from contextlib import suppress from functools import partial from pathlib import Path from typing import Callable, Iterator, NamedTuple, Tuple, Type, TypeVar, Union import astroid from .._stub import EXTENSION, StubFile, StubsManager T = ...
# -*- coding: utf-8 -*- import typing import cv2 import numpy as np from cv2 import hconcat, vconcat from tqdm import tqdm def callback_colors(image): image = image.flatten().tolist() print(f"White: {image.count(255)}") print(f"Black: {image.count(0)}") def constrain_type(patch: np.ndarray) -> np.ndarr...
import pandas as pd from pathlib import Path from pp.log import logger from inspect import signature #from types import MappingProxyType from collections import OrderedDict #SERVICES DIRECTORY SERVICES = {} #SERVICE KEYS # type, number of selections possible OPTION_FIELD_SINGLE_COL_ANY = (None, 1) OPTION_FIELD_MULT...
import project_pythonDB import pymysql def menu_select_1(): # User is shown first # 15 cities in world database print('='*60) print('| ' + '{:3s}'.format('ID') + ' | ' + '{:16s}'.format('Name') + ' | ' + '{:16s}'.format('District') + ' | ' + '{:12s}'.format('Population') ...
# SPDX-FileCopyrightText: 2020 <NAME> <<EMAIL>> # # SPDX-License-Identifier: Apache-2.0 import copy from typing import List, Tuple, Union, Optional, Iterator, Dict from codeprep.util import is_python_3_6_and_higher, to_literal_str, to_non_literal_str # TODO this class should be frozen class Merge(object): def ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Feb 6 10:16:35 2017 @author: alec """ import re import os import glob from collections import OrderedDict, namedtuple """This module defines functions for preprocessing texts and splitting sentences.""" def preprocess(report): """Preprocesses a ...
#Testing out the hashing function! #Import necessary libraries import hashlib; import struct; import datetime; # STEP 1, Create a Hash Function and necassry tools. def hashMe(s): #Encode our string and then pass through SHA256, SHA256 takes only unicode parse = s.encode(); # Name Hash as our sha256 algorithm, an...
# Based on https://github.com/facebookresearch/CPC_audio/blob/zerospeech/cpc/dataset.py # Copyright (c) Facebook, Inc. and its affiliates. # Originally released under the MIT license. import numpy as np from pathlib import Path from random import shuffle import time import torch from torch.multiprocessing import Pool f...
import typer from . import _typerpatch import json from typing import List, Optional from textwrap import fill from enum import Enum from lunr.index import Index from simconnect import SimConnect import os import re app = typer.Typer() thisdir = os.path.dirname(__file__) with open(os.path.join(thisdir, 'scvars.json'...
import sys from contextlib import contextmanager from pyvmmonitor_core import compat from pyvmmonitor_core.callback import Callback try: # Optional dependency: if greenlets are available check that properties aren't changed # when out of the main coroutine (the idea being that properties belong to main obje...
import os import random import sys import traceback import urllib import asyncpraw import discord import urlextract from discord.ext import commands from utils.channelUtils import is_nsfw_allowed from utils.configManager import BotConfig, RedditConfig from utils.log import log def credit_embed(post): ...
import marshmallow import datetime import uuid import bson import yaml import rapidjson import decimal from bson.raw_bson import RawBSONDocument from typing import Any, Union, Mapping, List, Dict, Callable, Optional from ._mimetype import MimeType, MimeTypeTolerant EncoderType = Callable[[Any], bytes] DecoderType = ...
# -*- coding: utf-8 -*- # Copyright (c) 2015, <NAME> and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.utils import cint from tailorpad.custom_folder.custom_manufacturing import make_stock_entry from frappe.model.document import Documen...
""" Solving MsPacman-ram-v0 environment Author: <NAME>(<EMAIL>) """ import gym import numpy as np import tensorflow as tf #learning parameters y = .95 #gamma e = 0.1 #random selection epsilion memory_size = 1000 num_episodes = 2000 env_features = 128 #128 bytes of atari console's RAM train_batch_size = 64 random_thre...
#!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as np import pandas as pd import os from os import listdir from os.path import isfile, join, getsize, dirname from collections import Counter, OrderedDict import shutil import warnings import h5py import pickle import gc import random import time import mat...
# -*- coding: utf-8 -*- # import tensorflow as tf def new_variable(name, shape, weight_decay=0.001, init=tf.contrib.layers.xavier_initializer(), forced_gpu=None): if forced_gpu is not None: with tf.device('/gpu:%d'%forced_gpu): regularizer = tf.contrib.layers.l2_regularizer(...
import numpy as np import cv2 import json ''' Set the color profile for the current light setting. run this file then press amd hold the r,b,g or y key to change the colors. to quit press and hold the q key ''' cap = cv2.VideoCapture(0) img = np.zeros((1, 500, 3), np.uint8) cv2.namedWindow('image', cv2.WINDOW_NORMAL...
from . import register_model, Model from .. import nvic from .. import native from ..globs import debug_enabled from unicorn import UC_HOOK_BLOCK from unicorn.arm_const import UC_ARM_REG_PC import sys from ..handlers import add_func_hook, remove_func_hook import importlib from ..exit import do_exit DEFAULT_TIMER_RELOA...
'''Utils for managing wpa supplicant files. ''' import os import glob import logging from shutil import copyfile from . import util logger = logging.getLogger(__name__) def set_ap_path(path): Wpa.ap_path = path def connect(ssid, verify=False): return Wpa(ssid).connect() and (not verify or verify_ssid(ssid))...
import collections import logging import copy import sys if __name__ == '__main__': import utils else: from . import utils logger = logging.getLogger('curate-bids') class TreeNode(collections.MutableMapping): """ Represents a single node (Project, Session, Acquisition or File) in the Flywheel hie...
import datetime def getIntensityDatasets(ChartDataset): return { 'U3': ChartDataset(), 'U2': ChartDataset(), 'U1': ChartDataset(), 'AT': ChartDataset(), 'TR': ChartDataset(), 'Test': ChartDataset() } def getFreshLastIntensityData(): return { 'U3...
#!/usr/bin/env python3 # encoding: utf-8 # # Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved. # # This file is part of ewm-cloud-robotics # (see https://github.com/SAP/ewm-cloud-robotics). # # This file is licensed under the Apache Software License, v. 2 except as noted # otherwise in the LIC...
import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable from torch.utils.data import DataLoader from torch.utils.data import sampler import copy import torchvision.datasets as dset import torchvision.transforms as T import numpy as np import timeit class ChunkSampler(sampl...
# Copyright (c) 2019. Partners HealthCare, Harvard Medical School’s # Department of Biomedical Informatics, <NAME> # # Developed by <NAME> and <NAME>, based on contributions by: # <NAME>, <NAME>, # <NAME>, <NAME> and other members of Division of Genetics, # Brigham and Women's Hospital # # Licensed under the Apa...
# purpose: distinguish lncRNA from the cRNA # 1. Design a model # 2. Construct loss & optimizer # 3. Training loop: # - forward pass (call model to predict) # - backward pass (calculate autograd) # - update weights import numpy as np import torch from Bio import SeqIO from torch import utils import matplotlib.pyplot a...
## @file test_All.py # @author <NAME> # @brief This file is the test file. from Set import * from MoleculeT import * from CompoundT import * from ReactionT import * import pytest class TestSet: def setup_method(self, method): self.setA = Set([1, 2, 3, 4, 5]) self.setB = Set([5, 4, 3, 2, 0]) self.setC = Set...
from plugin import Plugin from collections import defaultdict from decorators import bg_task import aiohttp import logging import json import re log = logging.getLogger("discord") class Platform: def __init__(self, name, db_name=None): self.name = name self.db_name = db_name or name def coll...
""" PyTorch implementation of Capsule Networks Dynamic Routing Between Capsules: https://arxiv.org/abs/1710.09829 Author: <NAME> University: Università degli Studi di Torino, Department of Computer Science """ import torch import time import numpy as np import torchvision.utils as vutils import torch.nn.functional a...
# -*- coding:utf-8 -*- import h5py import numpy as np import os import config class DataPreprocessing: def __init__(self): self.chosung = 19 self.jungsung = 21 self.jongsung = 27 self.hangul_length = 67 def decompose_as_one_hot2(self, in_char): one_hot = [] if o...
import math from _remote import ffi, lib from manager import PluginBase import util def getObjColor(obj, config, player, allies): p = obj.props # enemies if p.ownertype == lib.OWNERTYPE_ENEMY: if p.damage > 0: return config.enemy elif p.hitboxdamage == 0: return c...
''' API entry point for conversion from MARC to Linked Data ''' import logging from collections import defaultdict import warnings import zipfile import functools from versa import I, VERSA_BASEIRI, ORIGIN, RELATIONSHIP, TARGET, ATTRIBUTES from versa import util from versa.driver import memory from amara3.inputsourc...
from os import environ from flask import Flask, render_template, url_for, jsonify, make_response, request, session from spacy import en as SpacyModel from google.cloud import language as GoogleModel from watson_developer_cloud import AlchemyLanguageV1 alchemy_language = AlchemyLanguageV1(api_key='PUT_YOUR_OWN_KEY')...
import turtle import sys from SNAKE import Snake_Main from SNAKE import SETUP_SNAKE_AI from SNAKE import SETUP_SNAKE_NEURAL from BreakoutGamev03 import Breakout_Main from BreakoutGamev03 import SETUP_BREAKOUT_AI from BreakoutGamev03 import SETUP_BREAKOUT_NEURAL from PacMan import PacMan_Main from PacMan import SETUP_...
import os import re import time from absl import app from absl import flags from glob import glob import torch import tensorflow as tf from torch.utils.data import DataLoader from torchvision.datasets import CIFAR10, CIFAR100 from torchvision.transforms import ToTensor from torchvision import transforms from self_sup...
# coding=utf-8 # date: 2019/1/21, 14:18 # name: smz import numpy as np import tensorflow as tf from sklearn.utils import shuffle from FNN_skills.modules.model import ModelV1 from FNN_skills.configration.options import opts def split_data(data, ratios, batch_size): ratio1, ratio2, ratio3, ratio4 = ratios.split("...
import csv import logging import pickle from time import perf_counter import math import scipy from ensemble_compilation.graph_representation import AggregationType from ensemble_compilation.spn_ensemble import read_ensemble, logger from evaluation.utils import parse_query, all_operations_of_type, save_csv ...
class AST(object): VALUE_METHODS = [] def search(self, value): pass def _get_value_method(self, value): # This will find the appropriate getter method # based on the passed in value. for method_name in self.VALUE_METHODS: method = getattr(value, method_name, Non...
# Copyright (C) 2007-2020, <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, publi...
# -*- coding: utf-8 -*- from typing import Iterable, List, Tuple, Type import logging import re import datetime import pytz import requests from hour_usage import HourUsage _TZ_LONDON = pytz.timezone('Europe/London') _UTC_NOW = datetime.datetime.now(pytz.utc) _LONDON_NOW = _TZ_LONDON.normalize(_UTC_NOW) logger = log...
import numpy as np import pandas as pd from scipy.stats import randint as sp_randint from sklearn.pipeline import Pipeline from sklearn.preprocessing import OneHotEncoder from sklearn.compose import ColumnTransformer from sklearn.model_selection import RandomizedSearchCV from sklearn.ensemble import RandomForestClassif...
import docx import time from src.common import defines as dv from src.common import configVars as cv from src.common import stringHelpers as strHlprs from src.cmdInterface import cmdProgressBar class DocxExporter: """Class to generate the output acronym document""" def __init__(self, acro_dict_handl...
# Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. # Copyright 2019 The fiowebviewer Authors. All rights reserved. import numbers import pytest from fiowebviewer.engine import ( models, ) ROUNDING_RANGE = models.ROUNDING_RANGE @pytest.mark.parametrize("percen...
import sys from pathlib import Path from pandas import DataFrame, read_csv global yes def load_file(input_path: str) -> DataFrame: """ Function that loads and cleans file :param input_path: :return: DataFrame with processes and path to origin file """ with open(input_path, encoding="utf8") a...
from __future__ import absolute_import import numpy as np import os import pytest from mirdata import guitarset, utils from tests.test_utils import DEFAULT_DATA_HOME TEST_DATA_HOME = 'tests/resources/mir_datasets/GuitarSet' TRACK = guitarset.Track('03_BN3-119-G_solo', data_home=TEST_DATA_HOME) def test_track_basi...
import numpy as np import json import copy import random """ This is Step 2 in the seq2seq pipeline. Input: dtype. Basically use the (context, scenario, utt) to create a series of templates (x) and utt(y). For test and valid data, we will only create the template from dgpt-m greedy approach. """ dtype = "train" #te...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Clone an MT19937 RNG from its output # # The internal state of MT19937 consists of 624 32-bit integers. # # For each batch of 624 outputs, MT permutes that internal state. By permuting # state regularly, MT19937 achieves a period of 2**19937, which is Big. # # Each tim...
import json import boto3 from boto3.session import Session import datetime # Copyright 2015 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at...
# -*- coding: utf-8 -*- # Copyright 2017 <NAME> # # 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, p...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Detect same images and try to merge metadatas before deleting duplicates""" import PIL.Image as Image import PIL.ImageChops as ImageChops import sys import os import pyexiv2 import datetime import logging #Handler for merging properties def handler_mergeList(a, b): ...
import pytest import configparser import os import pydbhub.dbhub as dbhub CONFIG = ''' [dbhub] # dbhub.io Api key api_key = YOUR_DBHub.io_API_KEY_Here # The owner of the database to query db_owner = justinclift # The name of the database # - https://dbhub.io/justinclift/Join%20Testing....
__author__ = '<NAME>' __email__ = '<EMAIL>' import json from django.db import models from xanderhorkunspider.models import Website from xanderhorkunspider.models import Page from xanderhorkunspider.models import Loading from xanderhorkunspider.dao import WebsiteDao from xanderhorkunspider.dao import PageDao from xan...
from django.shortcuts import render,redirect from django.contrib.auth import login,authenticate from django.contrib.auth.decorators import login_required from django.contrib import messages from django.conf import settings from django.core.mail import send_mail from .forms import * def landing(request): return ren...
import html import re from dataclasses import dataclass, replace from typing import Any, Callable, Iterable, List, Match, Optional, TypeVar from .model import ( AnkiNote, Cloze, ClozePart, CodeBlock, CodeInline, Math, RoamBlock, RoamColonCommand, RoamCurlyCommand, RoamPart, ) OptionalFormatter = Callable[[An...
""" Facebook small world experiment-1 Number of different ways in which two people are connected Author: <NAME> (www.mohitchawla.in) """ import random as rand INFINITY = float("Inf") #flag to enable trace trace_enabled = True def trace(string): """ Enable to print trace statements set trace_enabled flag...
'''Rubik2Cube.py ''' #<METADATA> QUIET_VERSION = "0.1" PROBLEM_NAME = "Rubik2Cube" PROBLEM_VERSION = "0.1" PROBLEM_AUTHORS = ['<NAME>'] PROBLEM_CREATION_DATE = "18-OCT-2019" PROBLEM_DESC=\ '''This is the 2X2X2 Rubiks Cube. Modified from EightPuzzle.py ''' # Sides F = 0 B = 1 U = 2 D = 3 L = 4 R = 5 #Adjacencies ADJAC...
from hylite import HyLibrary import numpy as np from scipy.spatial.qhull import ConvexHull from tqdm import tqdm def polynomial(data, degree = 1, method='div'): """ Detrend an image data array using a polynomial fit and np.polyfit( ... ). *Arguments*: - data = numpy array of the format image[x][y][b...