text stringlengths 3.07k 22.1k |
|---|
# coding=utf-8
"""
This module is used to implement the Expression class.
The expression class parses an expression from a DCR graph and is able to interpret that
"""
import numbers
from enum import Enum, auto
class Expression(object):
"""
Boolean expression that represents a guard
"""
compare_operato... |
"""
Find repeating patterns in sequences
<NAME>, Feb 6, 2016 - Feb 7, 2016
Reference:
Detecting a repeating cycle in a sequence of numbers
http://stackoverflow.com/questions/8672853/detecting-a-repeating-cycle-in-a-sequence-of-numbers-python
"""
__version__ = "1.0.2" # linear ranges
import re
from logging import debug... |
import sys, os
from datetime import datetime
import shutil
import tensorflow as tf
import numpy as np
import logging
import tensorflow_datasets as tfds
import pandas as pd
import Data_augmentation
import seaborn as sns
sns.set_theme(style="darkgrid")
from sklearn.metrics import mean_absolute_error, mean_squared_error, ... |
# Copyright 2017 Sidewalk Labs | https://www.apache.org/licenses/LICENSE-2.0
"""Library for modeling generative typed bayesian networks.
Each model consists of multiple networks, one for each type of input data.
For instance, a person model might have a different network for persons of
each household type. This allow... |
#!/usr/bin/env python
# Filename: plot_air_tem.py
"""
introduction: plot the time series of air temperature
authors: <NAME>
email:<EMAIL>
add time: 29 May, 2019
"""
import sys,os
from optparse import OptionParser
import rasterio
import numpy as np
# import pandas as pd # read and write excel files
HOME = os.path.ex... |
# torch
import torch
import torch.nn as nn
# built-in
import functools
# project
import eerie
class OneDCNN(torch.nn.Module):
def __init__(self, use_bias=False):
super(OneDCNN, self).__init__()
# Parameters of the model
use_bias = False
eps = 2e-5
n_channels = 16
n_... |
"""
# Spice Format Netlisting
"Spice-format" is a bit of a misnomer in netlist-world.
Of the countless Spice-class simulators have been designed the past half-century,
most have a similar general netlist format, including:
* Simulation input comprises a file-full of:
* (a) Circuit elements, arranged in somethi... |
#!/usr/bin/env python
# Copyright (c) 2011, <NAME>, TU Darmstadt
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# not... |
"""
===============================================
vidgear library source-code is deployed under the Apache 2.0 License:
Copyright (c) 2019 <NAME>(@abhiTronix) <<EMAIL>>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may ob... |
#!/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.
import math
import os
import torch
import torch.distributed as dist
import numpy as np
from torchvision.datasets.utils... |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from astropy.stats import sigma_clip
import numpy.ma as ma
from astropy.io import ascii
fin = 'j0600_gcorr.ecsv'
print('reading in {}'.format(fin))
t = ascii.read(fin)
# reject ones with large errors
t = t[t['Uncertainty']<... |
"""Module containing constants and helper functions for dealing with keys.
"""
# Author: <NAME>
# Created: 12-Aug-2019
from sys import platform
import curses
from typing import Optional
# Some simple helper functions
def get_ascii_from_char(char: str) -> int:
"""Function that converts ascii code to charac... |
import sys
import limix
from limix.core.covar import LowRankCov
from limix.core.covar import FixedCov
from limix.core.covar import FreeFormCov
from limix.core.gp import GP3KronSumLR
from limix.core.gp import GP2KronSum
import scipy as sp
import scipy.stats as st
from limix.mtSet.core.iset_utils import *
import numpy a... |
import json
from .exceptions import *
class _Enum:
def __init__(self, values):
for item in values.items():
self.__dict__[item[0]] = item[1]
class JSONable:
def __init__(self, params):
if self._is_json(params):
params = json.loads(params)
self.__dict__.update(... |
import os
import json
from posixpath import basename, join
from copy import copy, deepcopy
from io import BytesIO
import numpy as np
from time import time,strftime
# Action names
__all__ = [] # type: List[str]
# Action methods
ALL_ACTIONS = [] # type: List[Callable[Any, Any]]
def cache(action):
"""
Decorator... |
import tkinter
from functools import partial
from pathlib import Path
dialog_y=None
dialog_x=None
class __Dialog(tkinter.Toplevel):
def __init__(self, message, buttons:list = None, choices: list = None, **kwargs):
"""
inputfield: bool = False, loginfield: bool = False
inputfield = False
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
__metaclass__ = type
# (c) 2017, Ansible by Red Hat, inc
#
# This file is part of Ansible by Red Hat
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Pu... |
#
# This file is part of LiteDRAM.
#
# Copyright (c) 2020-2021 Antmicro <www.antmicro.com>
# SPDX-License-Identifier: BSD-2-Clause
from migen import *
class ModeRegister:
"""RPC Mode Register encoding (RPC has only 1 mode register)"""
def __init__(self):
self.cl = Signal(3)
# TODO: in LP... |
# coding=utf-8
# Copyright 2021 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... |
import pygame, sys, time, random, math
pygame.init()
size = width, height = 550, 400
screen = pygame.display.set_mode(size)
###
### Fonctions diverses
###
def collisionSourisRect(rect):
return (pygame.mouse.get_pos()[0] > rect.left and pygame.mouse.get_pos()[0] < rect.right) and (pygame.mouse.get_pos()[1] > rect.... |
import pandas as pd
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
from skimage.transform import resize
import itertools
from sklearn.metrics import confusion_matrix,roc_auc_score, roc_curve, auc, precision_recall_curve, average_precision_score, f1_score
import seaborn as sns
import scipy
from... |
""" Quicker and even dirtier code to compute the MIP verification for
the min-dist problem
"""
import numpy as np
import gurobipy as gb
import utilities as utils
import full_lp
from domains import Domain
import time
def looper(start, max_val):
current = start
while current <= max_val:
yield curr... |
import numpy as np
import os
import shutil
import wfdb
import keras
from keras.models import load_model
from keras.layers import Dense
from keras.models import Model
from keras.callbacks import ModelCheckpoint
from keras.optimizers import SGD
import os.path
import tensorflow as tf
from load_samples import l... |
import sys
import numpy as np
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
from statsmodels.tsa.seasonal import seasonal_decompose
import argparse
import csv
from operator import add
import datetime
shape_i = 0
baseline_range = {'start':3, 'end':24}
crisis_range = {'start':24}
#{{{ def get... |
#################################################################################
# Copyright (c) 2011-2013, Pacific Biosciences of California, Inc.
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are me... |
"""
Parser
====================================
The KiCad parser. The parser downloads the KiCad files that were previously saved to a pickle file by the crawler and
parses them using the realthunder kicad parser. It will create an sqlite database, that can then be searched by the
flask search app.
"""
import argparse... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import requests
import random
import sys
from collections import OrderedDict
from . __version__ import (__title__,__description__,__url__,__version__,__build__,__author__,__author_email__,__license__,__copyright__,__mascot__)
BASE_URL = "https://free.currencyconverterapi... |
# Copyright 2015 TellApart, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... |
# Copyright (c) 2021 Open Risk (https://www.openriskmanagement.com)
#
# 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, co... |
# rules.py - pre-insertion rules
"""Rules applying before insertion.
Impoverishment, Obliteration, Fission, Fusion, CopyHead, AddFeatures, Metathesis
"""
import collections
from itertools import chain, islice
import operator
from . import contexts
from . import features
from . import meta
from . import tools
from .... |
from flask import render_template
from flask import request, jsonify
from flask import Blueprint
import os
import shutil
import traceback
from flask import make_response, send_file
from .server.table_utils import prepare_data, prepare_incremental_data
from .server.data_container import all_data
from ..fastgit import ... |
# -*- coding: utf-8 -*-
"""
Test set for the initial Lowland class.
"""
from biosim.landscape import Island, Desert, Highland, Lowland, Water
from biosim.animal import Herbivore, Carnivore
from biosim.simulation import BioSim
import pytest
"""
Tests of classes in landscape.py. Check if classes behaves as expected
""... |
"""
This module contains information about the way the cluster expansion is implemented in the package.
"""
import functools
import operator
import warnings
import numpy as np
from pycce.sm import _smc
try:
from mpi4py import MPI
mpiop = {'imul': MPI.PROD,
'mul': MPI.PROD,
'prod': M... |
# A small helper class to house functions needed by KeplerMapper.visualize
import numpy as np
from sklearn import preprocessing
import json
from collections import defaultdict
def init_color_function(graph, color_function=None):
# If no color_function provided we color by row order in data set
# Reshaping to ... |
# coding=utf-8
# Copyright 2022 The TensorFlow datasets Authors and the HuggingFace datasets, DataLab Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/li... |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import os
import cv2
from tqdm import tqdm
from joblib import Parallel, delayed
from skimage import measure
def load_images(path, n_jobs=12, rgb=False, uCT=False):
"""
Loads multiple images from directory and stacks them int... |
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#--------------------------------------------------------------------------
from enum i... |
from plyfile import PlyData, PlyElement
import open3d as o3d
from pyobb.obb import OBB
import numpy as np
import os
from scipy.spatial import ConvexHull, convex_hull_plot_2d
from scipy.spatial.transform import Rotation as R
import matplotlib.pyplot as plt
import argparse
import utils
def obb_calc(filename, gravity=np.... |
# Thanks to @AvinashReddy3108 for this plugin
"""
Audio and video downloader using Youtube-dl
.yta To Download in mp3 format
.ytv To Download in mp4 format
"""
import asyncio
import logging
import math
import os
import re
import shutil
import time
from telethon.tl.types import DocumentAttributeAudio
from youtube_dl i... |
# Gravity Simulation Project
# ----------------------------------------------------------------------------------------------------------------------
# This script is responsible for simulating the gravity.
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import os
import cv2
# Video frames' res... |
import httpx
import aiohttp
import asyncio
import discord
import io
import json
import logging
import os
import re
from discord.ext import commands
from discord import app_commands
from functools import partial
from itertools import filterfalse
from pathlib import Path
from textwrap import shorten
from youtube_dl impo... |
import sys
from abc import ABC
from enum import Enum
from typing import Any, Dict, List, Optional, Set, Union
import numpy as np
from sympy import Symbol, symbols
from PartSegImage.image import Spacing
from ..algorithm_describe_base import AlgorithmDescribeBase, AlgorithmDescribeNotFound, AlgorithmProperty
from ..ch... |
from typing import Any
import numbers
import dynet as dy
from xnmt import batchers, param_collections
from xnmt.modelparts import bridges, transforms, scorers
from xnmt.transducers import recurrent
from xnmt.persistence import serializable_init, Serializable, bare, Ref
class Decoder(object):
"""
A template class... |
# -*- coding: utf-8 -*-
import sys
import os
import os.path as osp
import yaml
from easydict import EasyDict
import logging
import datetime
import subprocess
cfg_file = osp.join(osp.dirname(__file__), 'depth_from_video_in_the_wild_config.yaml')
if not osp.exists(cfg_file):
print('cwd: {}'.format(os.ge... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import unittest
from datetime import datetime
from tempfile import NamedTemporaryFile
import pytest
from csvimporter import CsvImporter
from pytz import timezone
FIXTURES_DIR = os.path.abspath('tests/fixtures')
@pytest.mark.parametrize('epoch_timestamp,date_s... |
import csv
import copy
import math
import re
class ID3Solver:
most_label_value = ''
gain_method = ''
max_depth = ''
def __init__(self, label, gain_method, max_depth):
self.most_label_value = label
self.gain_method = gain_method
self.max_depth = max_depth
# calcula... |
from . import __version__ as VERSION
import json
import logging
import click
from tabulate import tabulate
import datetime, timeago, dateutil.parser
from shipami.core import ShipAMI
logging.basicConfig()
logger = logging.getLogger(__name__)
state_colors = {
'available': 'green',
'pending': 'yellow',
'f... |
"""R interface
For this to work, `manage.py rsandbox` must have been ran.
On first import it builds a command like the following:
/path/to/timeoutwrap 1s proot -b bound_file... -r /path/to/sandbox -w /path/to/namespace /usr/bin/R --slave --vanilla
--no-readline -e code
In order:
- Invoke timeoutwrap: a wrapper aroun... |
# ==============================================================================
# This file demonstrates a bokeh applet. The applet has been designed at TUM
# for educational purposes. The structure of the following code bases to large
# part on the work published on
# https://github.com/bokeh/bokeh/tree/master/exampl... |
"""Create your views here."""
import os
from datetime import date, datetime
from typing import Union
from django.contrib import messages
from django.core.files.storage import default_storage
from django.core.mail import send_mail
from django.http import HttpResponse, HttpResponsePermanentRedirect, HttpResponseRedirect... |
# fmt: off
from .utils import pandas_hdf5_handler
from .trcluster import dask_controller
import h5py
import skimage as sk
import pandas as pd
import numpy as np
import os
from matplotlib import pyplot as plt
class regionprops_extractor:
def __init__(self,headpath,segmentationdir,intensity_channel_list=None,props=... |
#!/usr/bin/env python3
import json
import os
import requests
import sys
import time
from config import *
import config
def translate_for_github(content):
if not content:
return None
for hlvl in range(1, 7):
content = content.replace('h{0}.'.format(hlvl), '#' * hlvl)
content = content.... |
#!/usr/bin/env python3
"""Manages page redirects for the Godot documentation on ReadTheDocs. (https://docs.godotengine.org)
Note that RTD redirects only apply in case of 404 errors, and to all branches and languages:
https://docs.readthedocs.io/en/stable/user-defined-redirects.html.
If this ever changes, we need to re... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
from __future__ import division
from __future__ import print_function
import time
import pickle
import threading
from packaging import version
from flask import Flask, request
from flask_socketio import SocketIO
from packaging.specifiers import ... |
# coding:utf-8
import logging
import os
import torch
from pathlib import Path
import numpy as np
import pytorch_lightning as pl
from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint
from pytorch_lightning.utilities import rank_zero_only, rank_zero_info
from .utils import save_json
logger = logging.get... |
"""Function from R-base that can be used as verbs"""
from typing import Any, Iterable, List, Mapping, Sequence, Tuple, Union
import numpy
from pandas import Categorical, DataFrame, Series
from pipda import register_verb
from pipda.utils import CallingEnvs
from ..core.contexts import Context
from ..core.types import A... |
import os
import time
import json
import sqlite3
import threading
from pathlib import Path
from abc import ABC, abstractmethod
from dictdb.SqliteThreadWork import SqliteThreadWork
class StorageException(Exception):
pass
class StorageReadOnlyException(StorageException):
pass
class SharedStorageConnectionExceptio... |
"""
create_python_project.info
~~~~~~~~~~~~~~~~~~~~~~~~~~
Implement base info class
Info instance are element used to keep track of information contained in scripts
:copyright: Copyright 2017 by <NAME>, see AUTHORS.rst for more details.
:license: BSD, see :ref:`license` for more details.
"""
... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import abc
import numpy as np
from astropy.modeling.fitting import LevMarLSQFitter
from ._dualbeam_utils import HalfWaveModel, QuarterWaveModel
from ..logger import logger
__all__ = ['compute_theta', 'reduced_chi2', 'dualbeam_polarimetry']
_retarder... |
import logging
import traceback
import six
from string import digits
import os
import pandas as pd
from arcproject.waterquality import classes
from . import wqt_timestamp_match as wqt
def convert_wq_dtypes(df): # TODO check to see if the wq_from_file function can do this
"""
Converts all the strings in dataframe... |
#!/usr/bin/env python
# coding: utf-8
# In[2]:
import zipline
from zipline.api import future_symbol, set_commission, set_slippage, schedule_function, date_rules, time_rules, continuous_future, order_target
from datetime import datetime
import pytz
import matplotlib.pyplot as plt
import pyfolio as pf
import p... |
# This program
# a) performs data cleaning process to remove missing attribute values present in the database.
# b) calculates probability of being breast cancer of an imaginary patient
# by evaluating his/her sample results provided as command-line argument.
import re
from sys import argv as arguments
data_file ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# vi: ts=4 sw=4
'''
:mod:`SciAnalysis.XSAnalysis.Result - Class for extracting results from xml files
================================================
.. module:: SciAnalysis.XSAnalysis.Result
:synopsis: Extracting results from xml files
.. moduleauthor:: Dr. <NAME> <<EMAIL>... |
"""
Utility class for manipulating Siemens SVS DICOM files
"""
import os
import struct
import re
import warnings
import nibabel.nicom.csareader as csareader
import nibabel.nicom.dicomwrappers as dcmwrapper
import numpy as np
import json
from autovps.transform import Transform
from autovps.dataset import svsdata
cla... |
from intuitlib.client import AuthClient
from intuitlib.enums import Scopes
from quickbooks import QuickBooks
from quickbooks.objects.customer import Customer
from quickbooks.objects.invoice import Invoice
from quickbooks.objects.department import Department
from quickbooks.objects.item import Item
from quickbooks.objec... |
# -*- coding: utf-8 -*-
"""
Functions to compute fluxes of standard radio sources, the Sun, Venus,
Jupiter and Saturn. The brightness of the Galactic background emission
is also provided.
The origin of the data is given in the documentation for ``radio_flux``,
``planet\_brightness``, ``get\_planet\_flux``, and
``gala... |
"""
dataset_loader模块实现了许多 DataSetLoader, 用于读取不同格式的数据, 并返回 `DataSet` ,
得到的 :class:`~fastNLP.DataSet` 对象可以直接传入 :class:`~fastNLP.Trainer` 和 :class:`~fastNLP.Tester`, 用于模型的训练和测试。
以SNLI数据集为例::
loader = SNLILoader()
train_ds = loader.load('path/to/train')
dev_ds = loader.load('path/to/dev')
test_ds = loader.... |
import setcreds
import openai
import mergedeep
import random
import copy
_diags = 0
def diag(msg, level=5):
if _diags >= level:
print(f"***{msg}")
def run_game(scenes, start_scene_id, diagnostics = False, talk_engine="davinci", question_engine="curie",
npc_talk_max_tokens=64):
global _diags
_... |
from skimage import io
import math
import csv
import os
import sys
import random
import matplotlib.pyplot as plt
# from mpl_toolkits.mplot3d import Axes3D
def write_csv(path, list_of_columns, list_of_names=None):
with open(path, 'w', newline='') as csvfile:
writer = csv.writer(csvfile, delimiter=',', qu... |
from math import acos, pi, sin, cos, sqrt
import numpy as np
from numpy.random import uniform
from pwtools import atomic_data, _flib
from pwtools.crys import cc2cell, volume_cc, Structure
from pwtools.num import fempty
class RandomStructureFail(Exception):
def __init__(self, msg):
self.msg = msg
def __... |
import numpy as np
import scipy
from scipy.linalg import sqrtm
from tqdm import tqdm
from .utils import fill_doc
from .base import Connectivity, EpochConnectivity
@fill_doc
def vector_auto_regression(
data, times=None, names=None, model_order=1, l2_reg=0.0,
compute_fb_operator=False, model='dynamic',... |
#
# Sudoku object module.
#
# This module contains various Sudoku entities such as node,
# row, col, box, and last but not the least the entire board.
# The strategy logic is teased out of this module entirely.
#
import re
import abc
class ValueException(Exception):
def __init__(self, value):
self.value ... |
# coding: utf-8
import json
import argparse
import sys
import os
import random
from raw_data_loader import RawDataLoaderBase, SLUDataLoader, StanfordDataLoader, TourSGDataLoader, SMPDataLoader
from data_generator import DataGeneratorBase, MiniIncludeGenerator, VanillaDataGenerator
from data_statistic import raw_data_st... |
import os
os.environ["OPENBLAS_NUM_THREADS"] = "1"
os.environ["MKL_NUM_THREADS"] = "1"
os.environ["NUMEXPR_NUM_THREADS"] = "1"
from os.path import join
from functools import partial
import numpy as np
import pandas as pd
import torch
from PIL import Image
from torch.utils.data import DataLoader
from torch.utils.data... |
from __future__ import division, print_function
import sys
import argparse
import time
import numpy as np
from numpy import inf
import emcee
from bumps.cli import load_model, load_best
from bumps import initpop
from bumps.dream import stats, views
import matplotlib.pyplot as plt
class Draw(object):
def __init__... |
"""
This web app is completly programmed by --> *** <NAME> *** <-- at backend and most of frontend
Enjoy this as this is created by me for only practicing purposes to test my skills and to learn new things
Feel free to upgrade it and upload to github but take this project with name of orignal developer
Login/signup pag... |
import os
from PIL import Image
from django.conf import settings
from django.core.files.base import ContentFile
from django.core.files.storage import get_storage_class
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.functional import LazyObject
from phonenumber_field.... |
import time
from cached_property import cached_property
import libkloudtrader.performance as performance
import libkloudtrader.parts as parts
import pandas
__all__ = ['Backtest']
class StatEngine(object):
def __init__(self, equity_fn):
self._stats = [i for i in dir(performance) if not i.startswith('_')]... |
import keras
import numpy as np
from celluloid import Camera
from keras.models import Sequential
from keras.layers.core import Dense
from keras import backend as K
from keras.models import load_model
import os
import random
import vectorizer
import matplotlib
import matplotlib.pyplot as plt
import matplotli... |
# Copyright (c) 2016 Codethink Limited
#
# 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 wri... |
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
import imutils
from cv2 import cv2
import pickle
def angle_to90(img):
imgproc = (img!=0).astype(int)
rows,cols = imgproc.shape
ptA, ptB = (None, None), (None, None)
idx = 0
while ptA == (None, None... |
"""Utility functions provided to policies and rules during execution."""
import time
from typing import Any, Dict, Union, Sequence, Set
import os
import boto3
_RESOURCE_TABLE = None # boto3.Table resource, lazily constructed
FIPS_ENABLED = os.getenv('ENABLE_FIPS', '').lower() == 'true'
FIPS_SUFFIX = '-fips.' + os.get... |
"""Modified from https://github.com/CSAILVision/semantic-segmentation-pytorch"""
import os
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.functional as F
from scipy.io import loadmat
from torch.nn.modules import BatchNorm2d
from inference.segmentation import resnet
# constants
ARCH_ENCODER =... |
import numpy as np
import torch
import torch.optim as optim
import torch.nn.functional as F
from models import ActorNetwork, CriticNetwork
from collections import deque, namedtuple
import random
import copy
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
eps = np.finfo(np.float32).eps.item()
... |
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
from ._registry import register_model
def knn(x, k):
inner = -2*torch.matmul(x.transpose(2, 1), x)
xx = torch.sum(x**2, dim=1, keepdim=True)
pairwise_distance = -xx - inner - xx.transpose(2, 1)
idx = pai... |
#!/usr/bin/python
#-*- coding: UTF-8 -*-
#
# @file: phoenix_cresql_gen.py
#
# 生成 hbase phoenix 数据库创建语句文件
#
# @version:
# @create: 2019-03-13
# @update: 2019-03-15
#
#######################################################################
import os, sys, stat, signal, shutil, inspect, commands, time, datetime
import y... |
import functools
import math
from sys import float_info
import ConfigSpace as cs
import ConfigSpace.hyperparameters as csh
import numpy as np
from deephyper.search import util
from skopt import Optimizer as SkOptimizer
from skopt.learning import (
ExtraTreesRegressor,
GradientBoostingQuantileRegressor,
Ra... |
import pyredner
import torch
import math
import redner
import os
import torch.nn.functional as F
# Use GPU if available
pyredner.set_use_gpu(torch.cuda.is_available())
radius = 1.5*math.sqrt(2)
radius2 = 0.8*math.sqrt(2)
light_intensity = 100.0
path = "results/shadow_art/"
camera_file = "cameras.xml"
step = "step_6_... |
import copy
import warnings
import numpy as np
import networkx as nx
import itertools as it
def mean_error_metric(resp_learned, resp_gt, error_mat):
"""Average an error metric (learned wrt. GT) across all demonstration path
This metric is used by Choi and Kim, 2012 in
Nonparametric Bayesian Inverse R... |
import os
import argparse
from datetime import datetime
import jinja2
from peewee import SqliteDatabase, DatabaseError
from playhouse.reflection import (
generate_models,
)
from pandas import DataFrame
"""
Create a CanDIG-Server Database Snapshot Report.
usage: python snapshot_stats.py [-h] [--markdown] [--html... |
""" This script will test the submodules used by the scattering module"""
import os
import numpy as np
import torch
import pytest
from kymatio.scattering2d import Scattering2D
from kymatio.backend.fake_backend import backend as fake_backend
from torch.autograd import gradcheck
backends = []
try:
if torch.cuda.i... |
'''
module for training SEDflow
'''
import os
import h5py
import numpy as np
def load_data(train_or_test, version=1, sample='toy', params='props', cuts=None, whiten=False, flux_space=False):
''' load training or test data
'''
assert train_or_test in ['train', 'test']
x_all, y_all = _load_... |
from __future__ import print_function, division, absolute_import
import sys
# unittest only added in 3.4 self.subTest()
if sys.version_info[0] < 3 or sys.version_info[1] < 4:
import unittest2 as unittest
else:
import unittest
# unittest.mock is not available in 2.7 (though unittest2 might contain it?)
try:
... |
import paddle
import numpy as np
from paddle import nn
from bert_seq2seq.paddle_model.transformers import BertModel, BertTokenizer
from bert_seq2seq.paddle_model.transformers.bert.modeling import BertSeq2Seq
import paddle.nn.functional as F
from tqdm import tqdm
from paddle.io import Dataset
tokenizer = BertTokenizer... |
from argparse import ArgumentParser, RawTextHelpFormatter
from inspect import signature
from typing import (
Any,
Awaitable,
Callable,
Coroutine,
Dict,
List,
Optional,
Sequence,
Tuple,
Type,
Union,
)
__all__ = (
# commander_app
'Command',
'command',
'CommandH... |
from sklearn.kernel_approximation import (RBFSampler,Nystroem)
from sklearn.ensemble import RandomForestClassifier
import pandas
import numpy as np
import random
from sklearn.svm import SVC
from sklearn.metrics.pairwise import rbf_kernel,laplacian_kernel,chi2_kernel,linear_kernel,polynomial_kernel,cosine_similari... |
# coding:utf-8
#https://books.agiliq.com/projects/django-admin-cookbook/en/latest/action_buttons.html
from django.contrib import admin
from .models import AmisRenderList, AmisRenderApp
from django.utils.html import format_html
from django.urls import path
from django.http import HttpResponse,HttpResponseRedirect
from... |
from __future__ import print_function, division
import os
import datetime
import sys
import pandas as pd
import psycopg2 as db
from nilmtk.measurement import measurement_columns
"""
MANUAL:
WikiEnergy is a large dataset hosted in a remote SQL database. This
file provides a function to download the dataset and save it... |
from asyncio import AbstractEventLoop, get_event_loop
from random import choice, randint
from re import search
from typing import Any, Tuple, Union
from urllib.parse import quote, urlencode
from aiohttp import ClientSession
from .classes import Colour, Filters, Image, MinecraftIcons
from .errors import BadRequest, Fo... |
# Copyright (C) GRyCAP - I3M - UPV
#
# 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.