text stringlengths 3.07k 22.1k |
|---|
import os
import abc
from abc import ABCMeta
import torch
import pandas as pd
import numpy as np
import torch.utils.data as data
class DataPrefetcher():
def __init__(self, loader, stop_after=None):
self.loader = loader
self.dataset = loader.dataset
self.stream = torch.cuda.Stream()
... |
# pylint: disable=invalid-name, ungrouped-imports
"""
Numba tools
This is a colection of functions used for numba functions
that work for targets cpu as well as cuda
"""
from __future__ import absolute_import, division, print_function
__all__ = [
"cuda",
"ctype",
"ftype",
"WHERE",
"myjit",
"... |
# Twisted Imports
from twisted.internet import reactor, defer, task
from twisted.internet.protocol import Factory
from twisted.python import log
# Package Imports
from ..machine import Machine, Stream, Property, ui
from ..util import now
from ..protocol.basic import QueuedLineReceiver
__all__ = ["HCube"]
class LineR... |
#!/usr/bin/env python3
# --------------------------------------------------------------------------- #
# The MIT License (MIT) #
# #
# Copyright (c) 2022 <NAME> <<EMAIL>> #
# ... |
import pandas as pd
import numpy as np
import riskparityportfolio as rp
import cvxpy as cp
from typing import Union
from sklearn.cluster import KMeans
from pypfopt.efficient_frontier import EfficientFrontier
from pypfopt import risk_models
from dl_portfolio.logger import LOGGER
from dl_portfolio.cluster import get_... |
#!/usr/bin/env python3
#
# Copyright 2014 <NAME>
#
# 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 ag... |
# Copyright 2020 <NAME>
#
# 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... |
# -*- coding: utf-8 -*-
import json
import unittest
import networkx as nx
import py2cytoscape.util.util_dataframe as df_util
from py2cytoscape.data.cyrest_client import CyRestClient
def pp(dict_data):
print(json.dumps(dict_data, indent=4))
class CyRestClientTests(unittest.TestCase):
def setUp(self):
... |
# -*- coding: utf-8 -*-
# Copyright 2017 Kakao, Recommendation Team
#
# 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... |
"""
The main game module.
Contains:
the main function, which is the entry point for the game, and
the AlienInvaders class which handles the game logic.
In order for the AlienInvaders attributes and methods to be accessible
across all game modules, an instance of the class is passed to the initializers
of some ... |
# <NAME>, 83597 (Projeto "Palavra GURU", 1ano: 1sem.)
"""
Valor booleano da gramatica
(Funcoes que definem a gramatica. Sao utilizadas listas para definir a posicao das vogais/consoantes/ditongos)
"""
def artigo_def(n):
return (n == 'O' or n == 'A')
def vogal_palavra(n):
return (n == 'E' or artigo_def(n))... |
from data import *
from layers.modules import MultiBoxLoss
from ssd import build_ssd
import os
import sys
import time
import argparse
import re
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.optim as optim
import torch.backends.cudnn as cudnn
import torch.nn.init as init
import tor... |
import paddle
if paddle.version.major == '2':
PP_v2 = True
from paddle.nn import functional as F
else:
PP_v2 = False
import numpy as np
from paddle import fluid
from paddle.fluid import dygraph
def kp2gaussian(kp, spatial_size, kp_variance: np.ndarray) -> np.ndarray:
"""
Transform a keypoint into ... |
"""
Script could be used as a template for preparing the image-beam data structure required to train
the modified ResNet on beam or blockage prediction. NOTE: script might need modification based on the
dataset you generated and where it is saved. PLEASE READ THROUGH.
"""
import numpy as np
import h5py as h5
import pic... |
"""
This module provides functions for sampling from the posteriors of various
regression models. The supported models are specified in the
REGRESSION_MODEL_NAMES constant.
"""
import pymc3 as pm
import theano.tensor as tt
from timeit import default_timer as timer
from data.preprocessing.format import numpy_to_datafr... |
#!/usr/bin/python3
"""
Driver for a trinamic tmc5130-bob on a raspberry pi using SPI.
This code is only raspberry pi specific because it uses pigpio, the vast majority of the code will work over any spi driver.
This used the 5160 example code (http://blog.trinamic.com/2018/02/19/stepper-motor-with-tmc5160/) as initia... |
import numpy as np
import matplotlib
default_backend = matplotlib.rcParams['backend']
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from pathlib import Path
from mushroom_rl_benchmark.utils import get_mean_and_confidence
from mushroom_rl.core import Core
from mushroom_rl_benchmark.core.logger import BenchmarkL... |
import sys
from pywebcachesim import parser, database, runner, get_task
import yaml
from emukit.examples.gp_bayesian_optimization.single_objective_bayesian_optimization import GPBayesianOptimization
from emukit.core import ParameterSpace, ContinuousParameter
from copy import deepcopy
import numpy as np
from sklearn.lin... |
# IMPORTS
# Imports from the standard library
from collections import OrderedDict
import json, sys, time, argparse, copy
# Imports from basic additional libraries
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
# Pytorch imports
import torch
from torch import nn, optim
import torch.nn.functi... |
"""Methods for integration of interactive DICOM plots within notebooks.
TODO:
* Continue to *pragmatically* improve this to make the visualization controls
and the information shown more similar to that in full-featured DICOM viewers.
"""
import collections
import os
import tempfile
from typing import Any, DefaultD... |
#!/usr/bin/env python
# encoding: utf-8
"""
MongoDB databases for storing references to mosaic image products (at the
stack, block and mosaic level).
The databases are backed by the Mo'Astro ImageLog API. Most of the additional
methods provided for each database are to preserve backwards compatibility.
These subclasse... |
#!/usr/bin/env python
from centralized_tester import *
import curses
import threading
import sys
class CentralizedTesterRun (threading.Thread):
def __init__(self, send_rate, send_count, name1, name2):
self.test = CentralizedTester(send_rate, send_count, name1, name2)
threading.Thread.__init__ ( s... |
import pandas as pd
import numpy as np
from sklearn.svm import SVR
from sklearn.model_selection import RandomizedSearchCV, GridSearchCV
from sklearn.ensemble import RandomForestRegressor
from sklearn.tree import DecisionTreeRegressor
from sklearn.linear_model import LinearRegression
from sklearn.neighbors import KNeig... |
"""Runtime for AVMP.
"""
__copyright__ = "Copyright (C) 2021 <NAME>"
__license__ = "Apache License"
import os
import socket
import logging
from datetime import datetime, timedelta
from avmp.core.models import App
from avmp.core.exceptions import MissingConfiguration
from avmp.utils.logging_utils import logging_setup... |
# -*- coding: utf-8 -*-
from functools import wraps
from datetime import datetime
import os
import re
from mailpy.view import MailView
from mailpy.response import TextMailResponse
from mailpy.exceptions import MailViewError
from mailpy.contrib.filelock import FileLock, FileLockTimeout
from mailpy.contrib.pelican.api i... |
import torch
import torch.nn as nn
from torch.nn import init
import numpy as np
import functools
from torch.optim import lr_scheduler
from transformers.optimization import get_linear_schedule_with_warmup
class Identity(nn.Module):
def forward(self, x):
return x
def get_norm_layer(norm_type='instance'):
... |
#!/usr/bin/env python3
import numpy as np
import tensorflow as tf
import pandas as pd
import continuous_mountain_car_evaluator
# This class is a bare version of tfp.distributions.Normal
class Normal:
def __init__(self, loc, scale):
self.loc = tf.convert_to_tensor(loc, dtype=tf.float32)
self.scale =... |
import datetime
import pytz
from flask import Blueprint, request, redirect, url_for, flash, session, current_app
from flask_login import login_required, current_user
from oauthlib.oauth2.rfc6749.errors import InvalidGrantError
from requests_oauthlib import OAuth2Session
from werkzeug.routing import RequestRedirect
fr... |
import numpy as np
import pandas as pd
from collections import namedtuple
import matplotlib.pyplot as plt
from typing import List, Union, Tuple
from pegasusio import MultimodalData, UnimodalData
from anndata import AnnData
from matplotlib.axes import Axes
def _transform_basis(basis: str) -> str:
if basis == "tsne... |
from typing import Optional
import rowordnet as rwn
import spacy
from mlconjug import mlconjug
from rowordnet import RoWordNet
from util.tools import unique, process_pair, get_cross_synset_pairs, get_synset_pairs
def generate_rwn_synonyms(wordnet: RoWordNet, word: str) -> list:
"""
Generates all synonyms of... |
import h5py
import cv2
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from skimage import exposure
from scipy.io import loadmat
try:
_range = xrange
except NameError:
_range = range
# overlay the image and its ground truth mask
def overlay(image, mask):
"""Overlap Origin... |
"""
Defines Solver, a class used to wrap various numerical optimizers for finding parameters such that an ansatz circuit is a solution to a target unitary.
"""
import sys
import numpy as np
import scipy as sp
import scipy.optimize
from . import utils
from .gatesets import *
from .logging import Logger
try:
from q... |
from __future__ import unicode_literals
import json
import mock
import time
from base64 import b64encode
from copy import deepcopy
from unittest import TestCase
from oauthlib.common import urlencode
from oauthlib.oauth2 import TokenExpiredError, OAuth2Error
from oauthlib.oauth2 import MismatchingStateError
from oauthl... |
import sys
import dask
import dask.dataframe as dd
from distributed import Executor
from distributed.utils_test import cluster, loop, gen_cluster
from distributed.collections import (_futures_to_dask_dataframe,
futures_to_dask_dataframe, _futures_to_dask_array,
futures_to_dask_array, _stack, stack)
imp... |
# coding=utf-8
import os
import numpy as np
import matplotlib.pyplot as plt
from example.cbnu.utils import get_interval
from scipy.signal import find_peaks
import pandas as pd
from collections import OrderedDict
import seaborn as sns
sns.set()
PRE = 0.1
POST = 0.1
def remove_nan(array):
return array[~np.isnan(a... |
import numpy as np
import pandas as pd
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
#algorithms
from sklearn.linear_model import LogisticRegression
from sklearn.cluster import KMeans
#evaluation
from sklearn.model_selection import ... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 31 12:15:28 2019
@author: RickFu
https://github.com/rickfu415/heatConduction
https://github.com/NelisW/heatConduction
see also Amar2006:
https://repository.lib.ncsu.edu/bitstream/handle/1840.16/2847/etd.pdf
http://web.engr.uky.edu/~acfd/egr537-lctrs.pdf
"""... |
from __future__ import division, print_function
import os, sys
import ROOT
from PhysicsTools.NanoAODTools.postprocessing.framework.postprocessor import PostProcessor
from PhysicsTools.NanoAODTools.postprocessing.framework.datamodel import Collection, Object
from PhysicsTools.NanoAODTools.postprocessing.framework.event... |
"""
##################################################################################################
# Copyright Info : Copyright (c) <NAME> @ Hikvision Research Institute. All rights reserved.
# Filename : spin_transformation.py
# Abstract : Implementations of the spin transformation
# Current ... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
# -*- coding: utf-8 -*-
"""
# @Time : 2019/5/24
# @Author : Jiaqi&Zecheng
# @File : utils.py
# @Software: PyCharm
"""
import os
import json
from pattern.text.en import lemma
from nltk.stem import WordNetLemmatizer
VALUE_FILTER = ['what', ... |
# coding=utf-8
#
"""
Copyright (c) 2020, <NAME>. All rights reserved.
license: BSD 3-Clause License, see LICENSE for more details.
"""
import os
from waflib.Node import exclude_regs as DEFAULT_PATH_EXCLUDES
from waflib import Utils as wafutils
from zm.pyutils import maptype, stringtype
from zm.utils import toList,... |
from docassemble.webapp.core.models import MachineLearning
from docassemble.webapp.db_object import db
from sqlalchemy import or_, and_
import re
import codecs
import cPickle as pickle
import datetime
import os
import yaml
import json
import sys
from pattern.vector import count, KNN, stem, PORTER, words, Document
from ... |
import pygame, random, thorpy
import parameters
import numpy as np
from pygame.math import Vector2
class SmokeGenerator(object):
current_id = 0
def __init__(self, samples, n, opac=None, mov=1, grow=0.5, prob=0.2, i=2,
color=None, alpha0=255, size0=None, smoothscale=False,
... |
#!/usr/bin/env python
import rospy
import sys
import moveit_commander
import moveit_msgs.msg
import geometry_msgs.msg
import actionlib
from control_msgs.msg import GripperCommandAction, GripperCommandGoal
from control_msgs.msg import GripperCommand
from math import pi
from std_msgs.msg import String
from moveit_comma... |
""" Server IO
This module is basically a high level interface to the central server.
The module contains three communication classes: 1) The
ClientNodeProtocol provides an interface from the Node to the central
server, 2) The ClientUserProtocol provides an interface for users/
researchers and finally 3) The ClientCon... |
"""
Script file: apis.py
Created on: Feb 25, 2021
Last modified on: Mar 28, 2021
Comments:
Django API endpoint definition
"""
import json
import cv2
import numpy as np
from http import HTTPStatus
from pathlib import Path
from base64 import b64encode, b64decode
from uuid import uuid4
from subprocess import call
f... |
######################################################################################################################
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. #
# ... |
# coding=utf-8
"""
This package contains customizable gym environments that wrap
simulations.
"""
from copy import deepcopy
from typing import Optional, Dict, List, Callable, Any
import numpy as np
from gym import spaces
from .base_env import BaseSimEnv
from . import observation as obs, reward_functions as rf
from .a... |
import numpy as np
from lib.utils import noise_validator, RMSELoss, selfCrossEntropy
from lib.utils import selfLatentLoss, get_activaton, selfVLoss, MyDataset, CvaeDataset
# import tensorflow as tf
import sys
import math
import scipy
import scipy.io
import logging
import torch
import torch.nn as nn
from torch.autograd... |
import time
from itertools import product
from dataclasses import dataclass
from distance import hamming
import numpy as np
from tensorforce.environments import Environment
from RNA import fold
@dataclass
class RnaDesignEnvironmentConfig:
"""
Dataclass for the configuration of the environment.
Default... |
from django.http import JsonResponse, HttpResponseBadRequest
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth.models import User
from django.contrib.sites.shortcuts import get_current_site
from django.utils.functional import SimpleLaz... |
"Contains functions for candidate searching and map matching"
from itertools import product
from logging import debug
from typing import Optional, Iterable, List, Tuple
from openlr import FRC, LocationReferencePoint
from ..maps import shortest_path, MapReader, Line
from ..maps.a_star import LRPathNotFoundError
from ..... |
from datetime import datetime, timedelta
import json
import unittest
import requests
from flight_tables.heathrow_parsing import extract_batch_heathrow, extract_flight_heathrow, fetch_heathrow_data
class SampleData(object):
def __init__(self):
self.raw_flight_1 = json.loads(r'''{"flightIdentif... |
import os
import sys
import time
import pygame
import subprocess
from pygame.locals import *
from utils import *
import RPi.GPIO as GPIO
os.putenv('SDL_VIDEODRIVER', 'fbcon') # Display on piTFT
os.putenv('SDL_FBDEV', '/dev/fb1')
os.putenv('SDL_MOUSEDRV', 'TSLIB') # Track mouse clicks on piTFT
os.putenv('SD... |
# import numpy as np
# from sklearn.compose import ColumnTransformer
import pytest
import numpy as np
import pandas as pd
from sklearn.pipeline import make_pipeline
from sklearn.exceptions import NotFittedError
from sklearn.preprocessing import StandardScaler
from sklearn.compose import ColumnTransformer
from skorec... |
import torch.nn.functional as F
import torch.nn as nn
import numpy as np
import torch
from torch.autograd import Variable
class FocalLoss(nn.Module):
def __init__(self, gamma=2):
super().__init__()
self.gamma = gamma
def forward(self, logit, target):
target = target.float()
max... |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... |
from typing import IO
import struct
import decimal
import uuid
import datetime
# Primitives
# Long
def decode_long(src: IO[bytes]) -> int:
byte = src.read(1)[0]
n = byte & 0x7F
shift = 7
while (byte & 0x80) != 0:
byte = src.read(1)[0]
n |= (byte & 0x7F) << shift
shift += 7
... |
# This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... |
#!/usr/bin/env python
# coding: UTF-8
# Copyright (c) 2017-2018 <NAME>
from __future__ import print_function
import os
import sys
import json
import argparse
import collections
def get_line_rank_and_metadata(options):
rank = None
metadata = dict()
counter = 0
for line in options.input:
line = line.strip()
if... |
import os
import glob
from pathlib import Path
from typing import Callable, List, Tuple
import numpy as np
import tifffile as tif
from torch import Tensor
from torch import distributed
from torch.utils.data import Dataset as DatasetBase
import torchvision as tv
from .utils import ISPRSSubset, filter_images
# classes... |
from __future__ import annotations
import asyncio
import json
import os
from pathlib import Path
from socket import timeout, gaierror, gethostbyname
from typing import Optional, Tuple, TYPE_CHECKING, Any
from discord import TextChannel
from discord.errors import NotFound
from websockets import WebSocketCommonProtocol... |
import sys
import numpy as np
from ..util import tiling_2d as tiling
from ..scores.cd import cd, cd_text
from skimage import measure # for connected components
from math import ceil
from scipy.signal import convolve2d
from copy import deepcopy
from ..scores import score_funcs
# score doesn't have to just be predicti... |
from flask import render_template, redirect, url_for, flash, request
from werkzeug.urls import url_parse
from flask_login import login_user, logout_user, current_user
from flask_wtf import FlaskForm
from wtforms.fields.html5 import DateField
from wtforms import StringField, IntegerField,PasswordField, BooleanField, Sub... |
# coding=utf-8
# Copyright 2022 The HuggingFace Inc. team.
#
# 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... |
"""
Library for connection to SSH servers.
Support multiple sessions per server, including batch console sessions and interactive sessions.
"""
import asyncio
import functools
import json
import re
import asyncssh
from tosh.tasks import task
_connections = {}
_connections_locks = {}
@task('Connecting to {pos[0]}... |
import en_core_web_sm
import numpy as np
import nltk
from nltk.corpus import stopwords
import pandas as pd
import re
import string
from textstat import textstat
from textatistic import Textatistic
from typing import List, Mapping, Any
STOPWORDS = stopwords.words("english")
PUNCTUATION = list(string.punctuation)
POS_TA... |
from __future__ import annotations
from asyncio import Task, sleep
from typing import TYPE_CHECKING, List, Optional, Union
# Internal imports
from .enums import SortType
from .errors import HTTPError
from .message import Message
if TYPE_CHECKING:
from .embed import SendableEmbed
from .file import File
fr... |
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from PIL import Image
import matplotlib.pyplot as plt
#transform PIL images into tensors
import torchvision.transforms as transforms
import torchvision.models as models
#to deep copy ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 12 14:32:32 2017
@author: <NAME> <<EMAIL>>
"""
import importlib
import os
import re
import sys
import subprocess
from pathlib import Path
from cffi import FFI
from .common import libexts, debug, warn
from .parser import parse
from .fortran_wrapper... |
import os
import glob
import re
import time
import tkinter as tk
import tkinter.filedialog
import tkinter.messagebox
from tkinter import ttk
APP_NAME = 'regnamer'
REG_NAME = os.path.join(os.path.dirname(__file__), 'regexp.txt')
class App(tk.Tk):
def __init__(self, parent):
tk.Tk.__init__... |
#===============================================================================
# Imports
#===============================================================================
from evn.path import (
format_dir,
PathMatcher,
)
from evn.util import (
ConfigList,
ConfigDict,
)
#============================... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 3 05:17:11 2021
@author: timur
"""
import requests
import folium
import webbrowser
import os
import json
from shapely.geometry import Point
from shapely.geometry.polygon import Polygon
def get_ways(values_clusters, name_column,go_back = False)... |
#! python3
import datetime, inspect, logging, os, subprocess, shutil
g_ToolkitVersion = 'v2.7.0'
def GetToolkitVersion():
return g_ToolkitVersion
gStartTime = 0
def StartTimer():
global gStartTime
gStartTime = datetime.datetime.now()
LogInfo("Timer Started {}".format(gStartTime.strftime('%Y-%m-%d %H:%M:%S')))
... |
# -*- coding: utf-8 -*-
# Copyright © 2021 Wacom 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
#
# Unle... |
#! /usr/bin/python
# -*- coding: utf-8 -*-
__author__ = "<NAME>"
__license__ = "Apache 2"
__version__ = "2.0.0"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL> or <EMAIL>"
__project__ = "LLP - MicroPheno"
__website__ = "https://llp.berkeley.edu/micropheno/"
import argparse
import os
import os.path
import sys
from boo... |
from wfnsympy import WfnSympy
from symgroupy import Symgroupy
import numpy as np
def _get_key_symgroup(label, center, central_atom, connectivity, multi, connect_thresh):
group_key = label.lower()
center_key = ' '.join(['{:10.8f}'.format(n) for n in center]) if center is not None else None
connectivity_key... |
from time import sleep
from typing import List
from typing import Set
from typing import Tuple
from typing import Dict
from typing import Any
from typing import Iterable
import time
import logging
import sys
from dao.wallet import Wallet
from graph.abs_transaction_retriever import AbsTransactionRetriever
from graph.bi... |
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 1 11:03:00 2018
@author: Kaai
"""
import random as rnd
import numpy as np
import pandas as pd
from collections import Counter
# %%
# read in data to train and test tree
df_test = pd.read_csv(r'train.csv', header=None)
df_train = pd.read_csv(r'test.csv', header=None)
... |
import numpy as np
import torch
import pandas as pd
import torch.utils.data as data
from sklearn.decomposition import PCA
from sklearn.model_selection import TimeSeriesSplit
from datetime import datetime
from os import path, listdir
'''**********************************************************************************... |
import math
def fvsphere():
"""formule volume sphere"""
print("4/3*pi*r**3")
def vsphere(r):
"""volume sphere"""
print(4 / 3 * math.pi * r ** 3)
def fpcercle():
"""formule périmetre cercle"""
print("2*pi*r")
def pcercle(r):
"""périmetre cercle"""
print(2 * mat... |
'''
Shared utility functions.
'''
import hashlib
import inspect
import logging
import os
import requests
from collections import defaultdict
from eliot.stdlib import EliotHandler
def rreplace(s, old, new, occurrence):
'''Convenience function from:
https://stackoverflow.com/questions/2556108/\
rreplace-h... |
import math
import numpy as np
from ax import Experiment
from baselines import nDS, computeHV2D
from .member import Member
from .member import Mutation
from .member import Recombination
from .member import ParentSelection
class SHEMOA:
"""
Succesive Halving Evolutionary MultiObjective Algorithm
:param p... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any, Dict, List, Optional
import magnum as mn
import habitat_sim
from habitat.sims.habitat_simulato... |
# REACTIVE NAVIGATION - EXPERIENCE REPLAY
# Developed by: <NAME>
#
# This file contains all classes used to create and manage the Experience Replay
# (a queue of experiences) used by Deep Q-Learning during the agent training
#
# More specifically, it contains:
# * STATE: A definition of a state as understood by our s... |
import gpytorch
import numpy as np
import torch
import torch.nn as nn
from torch.distributions import Categorical
from utils.memory import Memory
from utils.umodel import GradUGPModel
def magic_box(x):
return torch.exp(x - x.detach())
class PGDiceBase:
def __init__(self, id, env, hp, utility, mooc, other_u... |
import logging
import re
import sanic
from sanic.response import HTTPResponse, StreamingHTTPResponse, json, raw, stream, text
from internals.sanic import SpotilavaBlueprint, SpotilavaSanic
from internals.spotify import should_inject_metadata
logger = logging.getLogger("Routes.Tracks")
tracks_bp = SpotilavaBlueprint... |
#!/usr/bin/env python3
# -*-coding:utf-8 -*-
# =============================================================================
"""
@Author : <NAME>
@File : bag_filter_image.py
@Date created : 2022/01/31
@Maintainer : <NAME>
@Email : <EMAIL>
"""
# =====================================... |
"""Build neural net architecture with keras library and save best model."""
import argparse
import hashlib
import random
import time
from keras.models import Sequential
from keras.layers import Dense, MaxPooling1D, Activation, Convolution1D, Flatten, Dropout
from VirClass.VirClass.load_ncbi import get_gids
from VirCla... |
"""
Copyright (c) 2010, Cambridge Silicon Radio Ltd.
Written by <NAME> <<EMAIL>>
"""
from bintools.elf.exception import *
from bintools.dwarf.enums import DW_OP
class Instruction(object):
def __init__(self, addr, opcode, operand_1=None, operand_2=None):
self.addr = addr
self.opcode = opcode
... |
"""
Modul for tildeling av stjerner
"""
# Discord Packages
import discord
from discord.ext import commands, tasks
# Bot Utilities
from cogs.utils.defaults import easy_embed
import asyncio
import codecs
import json
import os
from pprint import pformat
class Poeng(commands.Cog):
"""
Klasse for tildeling av s... |
from gym.spaces import Space
import numpy as np
import torch
import torch.nn as nn
from brains.i_brain import IBrain
from tools.configurations import LSTMCfg
class LSTM(IBrain):
def __init__(self, input_space: Space, output_space: Space, individual: np.ndarray, config: LSTMCfg):
super().__init__(input_s... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from dafne.modeling.tta import OneStageRCNNWithTTA
from detectron2.utils.colormap import colormap
from detectron2.structures import PolygonMasks
import argparse
import atexit
import bisect
import glob
import multiprocessing as mp
import os
import ti... |
from datapackage_pipelines_playground.common import (get_config, temp_file, set_config,
get_service_account_json_file_path,
debug, os_system, os_system_generator)
import os, uuid, random, time, subprocess
from flas... |
import itertools as it
from typing import List
import numpy as np
import torch
from fairseq.data import Dictionary
try:
from flashlight.lib.sequence.criterion import (CpuViterbiPath,
get_data_ptr_as_bytes)
from flashlight.lib.text.decoder import (LM, Criterio... |
import random
import torch
import torch.nn as nn
import numpy as np
from open3d import *
def distance_squre(p1,p2):
tensor=torch.FloatTensor(p1)-torch.FloatTensor(p2)
val=tensor.mul(tensor)
val = val.sum()
return val
def show_point_cloud(points: np.ndarray, rgd=None):
assert points.ndim == 2
... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import logging
logger = logging.getLogger(name=__name__)
def plot_metrics(evaluator, full_trace=True, burnin=None,
x='iteration'):
df = evaluator.get_metrics()
df['variable:metric'] = df['variable']+':'+df['me... |
from process.data_helper import *
TRAIN_DF = []
TEST_DF = []
class WhaleDataset(Dataset):
def __init__(self, mode, fold_index='<NIL>', image_size=(128,256),
augment = None,
is_pseudo = False,
is_flip = False):
super(WhaleDataset, self).__init__()
... |
import os
import json
import sys
from django.views import View
from django.shortcuts import render
from django.db.models import signals
from django.http import JsonResponse
from django.contrib.gis.geos import GEOSGeometry
from django.contrib.auth.mixins import UserPassesTestMixin, LoginRequiredMixin
from django.contrib... |
# pylint: disable=duplicate-code
#The GOST cryptographic functions.
#
#Author: <NAME> (c) 2020
#License: MIT
"""
The GOST hash-based message authentication code functions.
The module implementing the calculating the HMAC message authentication code
in accordance with R 50.1.113-2016. The module includes the 'R50111... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.