text
stringlengths
3.07k
22.1k
import sys from xml.etree.ElementTree import parse from os.path import isdir, join from glob import iglob from datetime import datetime, timedelta # syspol reference file_ext = '.tsk' DEFAULT_TIMEDELTA = timedelta(weeks=1) DEFAULT_DATETIME_FMT = '%Y-%m-%d %H:%M:%S' XPATHSEP = '/' XPATH_MATCH_PREFIX = '.{0}'.format(XP...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Module for node definition in grid. """ from copy import deepcopy import uuid import numpy as np from catplot.grid_components import extract_plane import catplot.descriptors as dc class GridNode(object): """ Abstract base class for other node. Parameters:...
import bpy import os import math import random import sys import json from mathutils import Vector #Hide Splash Screen on Startup bpy.context.preferences.view.show_splash = False scene = bpy.context.scene dirname=os.path.dirname filepath = dirname(os.path.realpath(__file__)) + "\\" def ReadData(filename): try: ...
import os import sys import traceback import tempfile from pathlib import Path from typing import Optional import json import requests import pandas as pd from pandas.core.frame import DataFrame import torch.multiprocessing as mp import lightwood from lightwood.api.types import ProblemDefinition, JsonAI from lightwood...
""" Copyright 2018 <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, ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """csiread example: view the contents of a packet Note: If the csi file is stored in HDD instead of SSD, it will take a little longer to read it for the first time. """ from timeit import default_timer import csiread def stringify(array, space=':'): return ...
# pyrest runner # import logging import sys import requests import urllib3 from os import path from flask import json from test_steps import test_logger, eq, ok urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) logging.basicConfig(level=logging.DEBUG, stream=sys.stdout) ''' --------------- TEST...
from discord.ext import commands from discord.utils import find import asyncio import logging import re from time import strftime, localtime, time from threading import Event from utils import Config, permission_node from .utils import isUp, getProc, serverStart, getcrashreport, parsereport, formatreport log = logging...
import argparse import math import numpy as np import os import re import sys import utils WORD_EMBEDDING_LENGTH = 50 DURATION_IDX = 50 OLD_POST_IDX = 51 AM_INDEX = 51 LM_INDEX = 52 POST_IDX = 53 FRAME_PERIOD = 0.01 def set_of_processed_file_names(directory_to_search, remove_extension=False, extension='.npz'): ...
# coding: utf-8 # /*########################################################################## # # Copyright (c) 2016-2018 European Synchrotron Radiation Facility # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to d...
# Base on the code: https://github.com/facebookresearch/Adversarial-Continual-Learning import torch import numpy as np import torch.nn as nn import torchvision.models as models def compute_conv_output_size(Lin,kernel_size,stride=1,padding=0,dilation=1): return int(np.floor((Lin+2*padding-dilation*(kernel_size-1)-...
""" DNN評価値関数による、MCTSプレイヤーの実装 局面評価をバッチにまとめて、別プロセスで処理 """ import random from typing import Dict, Optional, List, Tuple import queue import multiprocessing from logging import getLogger import time logger = getLogger(__name__) import numpy as np import scipy.special import chainer import chainer.functions as F from ....
# coding: utf-8 # 2021/5/16 @ tongshiwei import traceback import warnings from .segment import seg from .tokenization import tokenize, link_formulas from .parser import Parser __all__ = ["is_sif", "to_sif", "sif4sci"] def is_sif(item): r""" Parameters ---------- item Returns ------- whe...
#!/usr/bin/env python3 import os.path import tensorflow as tf import helper import warnings from distutils.version import LooseVersion import project_tests as tests # Check TensorFlow Version assert LooseVersion(tf.__version__) >= LooseVersion('1.0'), 'Please use TensorFlow version 1.0 or newer. You are us...
import os from os import DirEntry from pathlib import Path import re from collections import defaultdict from dataclasses import dataclass from itertools import chain from enum import Enum from typing import Optional, Dict, List, Sequence, Set from .config_files import ConfigFiles class GroupType(Enum): must_pro...
#!/usr/bin/env python # # Copyright 2011, Google Inc. # 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 # notice, this list...
#!/usr/bin/env python # coding: utf-8 # In[7]: import keras import cv2 import os import glob import random import numpy as np import pandas as pd import cmder # slipt one video to multiple segments. def splitVideo(path: str, video: str, split: int) -> str: video_name = video.split(".")[0] newdir = path + v...
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- from flask import Blueprint, flash, make_response, request, redirect from flask import render_template, url_for from flask import session as login_session from oauth2client.client import flow_from_clientsecrets from oauth2client.client import FlowExchangeError import vie...
from flask import Blueprint from flask import request, jsonify, abort from app import app, db from app.utils.articles import parse_markdown, get_articles_from_db from app.utils.database import get_all_zhuanlan, get_page_view_by_path, get_page_view_count_by_path, rtn_friends from app.config import DOMAIN_PRE, PREFIX fro...
# encoding: utf8 __author__ = "<EMAIL>" """ Deep Learning implementation for image segmentation. """ import sys import numpy as np from functools import reduce from copy import copy from prepare import set_trainability, get_gan, get_discriminator, get_generator, get_data, get_masks from keras.callbacks import ModelCh...
# From http://www.hs.uni-hamburg.de/DE/Ins/Per/Czesla/PyA/PyA/pyaslDoc/aslDoc/unredDoc.html import numpy as np import scipy.interpolate as interpolate def unred(wave, flux, ebv, R_V=3.1, LMC2=False, AVGLMC=False): """ Deredden a flux vector using the Fitzpatrick (1999) parameterization Parameters ...
import sys import threading import cmd import chess from chess import polyglot import tables import os __location__ = os.path.realpath( os.path.join(os.getcwd(), os.path.dirname(__file__))) logfile = open(os.path.join(__location__, 'input.log'), 'w') ENGINE_NAME = 'simple UCI chess engine' AUTHOR_NAME = '<NAME>'...
# imports from datetime import datetime, timedelta from flask import (Flask, flash, g, redirect, render_template, url_for) from flask_bcrypt import check_password_hash from flask_login import (LoginManager, current_user, login_required, login_user, logout_user) from flask_w...
# code brought in part from https://github.com/microsoft/human-pose-estimation.pytorch/blob/master/lib/models/pose_resnet.py from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import torch import torch.nn as nn import torch.nn.functional as F from co...
# -*- coding: utf-8 -*- """ Created on Tue Mar 07 08:33:14 2017 @author: mstelmach """ ''' Lookup tables are created to be modified rarely if ever. Models here will be referenced by data in other apps. ''' from django.db import models from django.contrib.gis.db import models from django.shortcuts import reverse # d...
"""keymaster Integration.""" import fileinput from homeassistant.core import callback from homeassistant.helpers import config_validation as cv, entity_platform import logging import os from .const import ( ATTR_NAME, ATTR_CODE_SLOT, ATTR_ENTITY_ID, ATTR_NODE_ID, ATTR_USER_CODE, CONF_ALARM_LEVE...
#!/usr/bin/python # -*- coding: utf-8 -*- from bs4 import BeautifulSoup import requests import re import sqlite3 import sys, getopt import datetime import csv import argparse import random logo = ''' ___ _ _ ___ _ _ ___ _ ___ _ _____ ___ ___ _ ___ ___ ___ | __| | /_\ / __| || | _ ) /_\ / __| ...
from builtins import range import sys sys.path.insert(1, "../../../") import h2o from tests import pyunit_utils from h2o.estimators.glm import H2OGeneralizedLinearEstimator import numpy as np def test_beta_constraints_gaussian(): # binomial h2o_data = h2o.import_file(pyunit_utils.locate("smalldata/glm_test/g...
# coding=utf-8 from gevent import Greenlet from gevent.queue import Queue from collections import defaultdict from utils import dummyCoin, greenletPacker, getKeys from ..commoncoin.thresprf_gipc import serialize, serialize1, deserialize, combine_and_verify verbose = 0 from utils import makeCallOnce, \ makeBroadca...
import numpy as np from numerical_eqs.utils import SimTime def basicStep ( x, t, vf, dt ): '''Euler step, but using derivative at middle point of dt ''' dt2 = dt/2.0 tmid = t + dt2 w = x + dt2 * vf( t, x ) return x + dt * vf( tmid, w ) def step ( x, t, vf, dt ): '''Roughly estimate the future po...
import argparse import os.path from src import c_stuff_sack from src import py_stuff_sack from src import stuff_sack def header(header, level=0): underlines = ['=', '-', '^', '"'] if level < 0 or level >= len(underlines): raise ValueError('Level ({}) out of range (0, {})'.format(level, len(underlines))) ...
""" Redis 内置的 Lua 解释器加载了以下 Lua 库: base table string math debug cjson cmsgpack 其中 cjson 库可以让 Lua 以非常快的速度处理 JSON 数据,除此之外,其他别的都是 Lua 的标准库。 """ import time import uuid import math import random import redis connect = redis.Redis() class FrequencyRequest: _digest = None __lua__ = """ local key = KEYS[1] ...
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use ...
import os import numpy as np import h5py import random from PIL import Image import tensorflow as tf from meta import Meta tf.app.flags.DEFINE_string('data_dir', './data', 'Directory to SVHN (format 1) folders and write the converted files') FLAGS = tf.app.flags.FLAGS class ExampleReader(o...
import os, sys root_dir = os.path.dirname(os.path.abspath(__file__)) external_dir = os.path.join(root_dir, 'externals') sys.path.insert(0, root_dir) sys.path.insert(1, os.path.join(external_dir, 'PyTorch-NEAT')) sys.path.insert(1, os.path.join(external_dir, 'pytorch_a2c_ppo_acktr_gail')) import json import argparse im...
import torch import torch.nn as nn from torch.distributions import Normal as NormalDistribution # from .. import framework as fm from ..op import framework as fm from omnibelt import InitWall, unspecified_argument import omnifig as fig from .layers import make_MLP ################# # region General ####...
import argparse import time import typing import pandas as pd import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt plt.style.use('bmh') import torch from torch import nn import torch.nn.functional as F import torch.optim as optim import os import sys import datetime sys.path....
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ A module for searching for spectral line metadata in a remote database. A Simple Line Access (SLA) service allows a client to search for metadata describing atomic and molecular transitions that can result in spectral line emission and absorption. Th...
import tensorflow as tf from .basic_ops import * """This script defines 3D different multi-head attention layers. """ def multihead_attention_3d(inputs, total_key_filters, total_value_filters, output_filters, num_heads, training, layer_type='SAME', name=None): """3d Multihead scaled-dot-product atten...
# Unit test for the CLIEditor # Description: # This file validates that each function belonging to the CLIEditor # class behaves as intended # Course: CSCI 420 - Software Engineering # Authors: <NAME> # Date: November 21, 2020 ########################################################################## # Impo...
# *************************************************************** # Copyright (c) 2020 Jittor. Authors: <NAME> <<EMAIL>>. All Rights Reserved. # This file is subject to the terms and conditions defined in # file 'LICENSE.txt', which is part of this source code package. # ************************************************...
from pickle import load from shutil import rmtree from numpy import arange, genfromtxt, where from numpy import concatenate as concat from numpy import argsort, array import plotly.graph_objs as go from wonambi.trans import montage, timefrequency from wonambi.trans import concatenate, select, math from bidso.utils impo...
# Python Chatroom Client # Made by womogenes. # Imports first, always. import socket import json import hashlib import _thread import sys import os import time import tkinter as tk from datetime import datetime # Encryption libraries.= import rsa import pyaes # ExTeRnAl ImPoRtS!? import client_ui import Mining #...
from flask import session, request, send_from_directory, Flask, render_template from flask_socketio import SocketIO, join_room, leave_room from flask_session import Session from flask_compress import Compress from flask_httpauth import HTTPBasicAuth from werkzeug.security import generate_password_hash, check_password_h...
import math from typing import Optional import torch from torch import nn from torch.nn import TransformerDecoder, MultiheadAttention, LayerNorm from torch.nn.init import xavier_uniform_ from torch.nn.modules.transformer import TransformerDecoderLayer from code_transformer.configuration.transformer_lm_decoder import ...
from flask_wtf import FlaskForm from flask_login import current_user from wtforms import StringField, BooleanField, SubmitField, SelectField, IntegerField, DecimalField, SelectMultipleField from wtforms import FieldList, FileField, Form, FormField, MultipleFileField, RadioField, validators, widgets, TextField from wtf...
import re import pandas as pd from tqdm import tqdm from typing import List, Dict, Tuple, Optional import logging from .base import Preprocessor ### Original source code from ### https://appsrv.cse.cuhk.edu.hk/~pjhe/Drain.py class DrainLogCluster: def __init__(self, log_template: List[str] = [], log_ids: List[int] = ...
from tkinter.ttk import * import tkinter as tk from tkinter import * import cv2 from PIL import Image, ImageTk import os import numpy as np from utils.align_custom import AlignCustom from utils.face_feature import FaceFeature from utils.mtcnn_detect import MTCNNDetect from utils.tf_graph import FaceRecGraph import argp...
from apps.projects.models import Project, ProjectPhases from apps.sepa.sepa import SepaDocument, SepaAccount from django.conf import settings from django.utils import timezone from django.db import models from django.utils.translation import ugettext as _ from django_extensions.db.fields import ModificationDateTimeFiel...
import argparse from pathlib import Path from typing import Tuple import numpy as np import torch from torch.utils.data import DataLoader from data.datasets import get_dataloaders from data.eval_metrics import evaluate from model.net import get_model from utils.conf import Conf from utils.saver import Saver from data...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/1/25 7:18 PM # @Author : 573v3n # @Contact : <EMAIL> # @Site : # @File : main.py # @Software: PyCharm import colorsys import cv2 import numpy as np import collections import os import time def canConnect(x1,y1,x2,y2,imageMatrix): ''' :...
from __future__ import unicode_literals import binascii import sys import base64 import inspect import mimetypes from six import BytesIO from django.forms.fields import FileField from django.utils.translation import ugettext_lazy as _, ugettext from django.core.files.uploadedfile import InMemoryUploadedFile from dja...
import sys,os from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter import matplotlib.pyplot as plt import matplotlib.colors as colors import numpy as np import tracer_interpreter as ti import pdb def truncate_colormap(place,size,res,colormap...
# -*- coding: utf-8 -*- from functools import partial import numpy as np import pytest from celerite2 import backprop, driver from celerite2.testing import get_matrices pytest.importorskip("celerite2.pymc4") try: import aesara import aesara.tensor as tt from aesara.compile.mode import Mode from aes...
from pytorch_loss import LogTaylorSoftmaxV3 from torch.nn import ELU import torch.nn as nn import torch import torch.nn.functional as F import torchvision class EluTaylorSoftmax(nn.Module): """ 用于替代通常Softmax,使用Elu与TaylorSoftmax的组合,将非线性部分由 指数转化为多项式,使用ELU保证单调性。 """ def __init__(self, dim=1, ...
#!/usr/bin/env python3 from enum import Enum from io import StringIO from jsonargparse_tests.base import * from jsonargparse import ArgumentParser class DeprecatedTests(unittest.TestCase): def test_ActionEnum(self): class MyEnum(Enum): A = 1 B = 2 C = 3 pars...
import numpy as np import torch from torch import nn from torch.autograd import Variable from torchpcp.modules.Layer import Layers from torchpcp.modules.TransformNet import ( InputTransformNet, FeatureTransformNet ) class Conv1DModule(Layers): def __init__(self, in_channels, out_channels, ...
""" Functions that give information about clips or mathematical helpers. """ __all__ = ['get_depth', 'get_plane_size', 'get_subsampling', 'get_w', 'is_image', 'scale_value'] from mimetypes import types_map from os import path from typing import Optional, Tuple, TypeVar, Union import vapoursynth as vs from . import f...
import rebound import numpy as np from rebound.interruptible_pool import InterruptiblePool import multiprocessing as mp import time import sys import os import shutil import random import subprocess as sb import threading def generate_orb_elements(semi): ecc = np.abs(np.random.normal(0,0.3)) incl = np.abs(np.r...
""" Martins, Pascoal and Santos deviation path algorithm. """ from heapq import heappush, heappop from itertools import count import networkx as nx # Modified from networkx/algorithms/simple_paths.py: class PathBuffer(object): """Heap priority queue to add and remove paths in sorted order """ def __init...
import numpy as np import torch from ase import units class MDUnits: """ Basic conversion factors to atomic units used internally: fs2atu (time): femtoseconds to atomic time units eV2Ha (energy): electron Volt to Hartree d2amu (mass): Dalton to atomic mass units angs2bohr (leng...
from urllib import parse from urllib.parse import quote import requests import xlrd import os import piexif from PIL import Image import uuid import json def help(): print("help ------------------- 帮助选项(查看文档详细信息)") print("sc [cho] --------------- 搜索数据库信息") print("de [cho] [name] -------- 删除数据库信息") print("img [file...
#!/usr/bin/python3 from os import listdir, walk, rename, makedirs, getcwd, remove from os.path import isfile, isdir, join, dirname, basename, splitext, exists, realpath, normpath from shutil import copy, copyfile, move, rmtree import subprocess import logging import argparse import yaml import csv import sys import re ...
# Copyright 2018 Rackspace, US 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...
import os from collections import OrderedDict import config import file_utils def _print_group_headers(type, real_type): return [ f'#include "{real_type}.h"' ] if type == 'any' else [] def _print_methods(classname, type, vpi, card, real_type=''): content = [] if type in ['string', 'value', 'delay']: ...
# Copyright 2019 The Forte Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
# Copyright 2022 Deep Learning on Flink 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/licenses/LICENSE-2.0 # # Unless required by applicable law ...
from django.contrib.auth.models import User from django.contrib.postgres.fields import ArrayField from django.contrib.postgres.fields import JSONField from django.db import models from django.db.models import Q, UniqueConstraint from treebeard.mp_tree import MP_Node # CURRICULUM DOCUMENTS ###########################...
# -*- coding: utf-8 -*- """ Functions to delineate catchments. """ import numpy as np import pandas as pd from gistools.vector import kd_nearest, convert_lines_to_points from gistools.util import load_geo_data from shapely.geometry import box ##################################################### #### MFE REC streams n...
import sys import os.path as path from rdflib import Namespace, XSD, RDF, RDFS, OWL from rdflib.term import Variable, URIRef, BNode, Literal from rdflib.plugins.sparql.parser import parseQuery from rdflib.plugins.sparql.parserutils import prettify_parsetree from rdflib.plugins.sparql import prepareQuery from rdflib.pat...
#!/usr/bin/env python3 # samtoolscount_chrompara_distr.py """SAMtools count distributed by regions This app performs a SAMtools count via the following implementation: - Index file is optional and will be created if missing - Sorted bam file is specified as input, but the case where a bam is not sorted is handled...
# -*- coding: utf-8 -*- """Universal Notifications Sample usage: WSNotification(item, receivers, context).send() """ import importlib import logging import re from email.utils import formataddr from django.conf import settings from django.contrib.contenttypes.models import ContentType from django.contrib.sites.m...
# Copyright (C) 2019 The Dagger 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/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in w...
import collections import dataclasses import re from typing import Tuple, Sequence, List, Optional DeletionMatrix = Sequence[Sequence[int]] @dataclasses.dataclass(frozen=True) class TemplateHit: index: int name: str aligned_cols: int sum_probs: float query: str hit_sequence: str indices_query: List[int] indic...
import ast import logging from typing import List, Set from grimp.application.ports.importscanner import AbstractImportScanner from grimp.domain.valueobjects import DirectImport, Module from grimp import exceptions logger = logging.getLogger(__name__) class NotAnImport(Exception): pass class ImportScanner(Abs...
#!/usr/bin/env python import rospy import argparse import os import sys import glob import subprocess import time import termios import atexit """ Plays any bag file in the current directory, directory passed, and also existing behavior of passed filename (absolute or relative). """ # TODO test relative paths work fo...
from flask import render_template, request, Flask, redirect, url_for from drone import drone from cloud import cloud from block import block from cloud import cloudtxnlistbefore from cloud import transactioncountbefore from cloud import cloudtxnlistafter from cloud import transactioncountafter from blockcha...
import os import uuid from typing import Any, List, Optional, Tuple import environs from marshmallow.validate import Range from scripts.utils.models import BasicAuthUser from .utils.environ_parsers import basicauth_parser from .utils.exceptions import NoClusterConfigError env = environs.Env() env.add_parser("basica...
#!/usr/bin/env python3 import gym from gym.utils.play import play from gym.spaces import Box import random import vizdoomgym import time import sys import uuid import numpy as np import random import os import torch import torchvision import cv2 import scipy.ndimage as ndimage from torch import nn from torch.utils.dat...
# Copyright 2018 DeepMind Technologies Limited. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by ...
from __future__ import absolute_import, annotations, unicode_literals from collections import ChainMap from copy import deepcopy import inspect import logging import os import sys from typing import Any, List, Tuple import pyconfig import yaml from ultron8.config import smart from ultron8.exceptions.config import C...
""" Numba functions for sim module """ from __future__ import absolute_import, print_function, division import numpy as np import numba as nb import math from cddm.conf import U16,U8,F,I, NUMBA_TARGET, NUMBA_PARALLEL , NUMBA_CACHE, NUMBA_FASTMATH #this is so simple that it is faster to compute in cpu mode @nb.vect...
import os import threading import string from random import * from .config import Configurator from .helpers import uuid from von_agent.nodepool import NodePool from von_agent.wallet import Wallet from von_agent.agents import _BaseAgent from von_agent.agents import Issuer as VonIssuer from von_agent.agents import Ve...
import sys import numpy as np from pathlib import Path np.set_printoptions(threshold=sys.maxsize) def to_openfoam(im, path='', voxel_size=1, label_boundaries=True): r""" Save the image as an instruction file for OpenFoam to build an equivalent hexahedral mesh with (optionally) defined boundaries. Par...
import subprocess,os import numpy as np import mygis from bunch import Bunch global last_precip last_precip = -1 sfcvarlist = ["TP_GDS4_SFC", "CP_GDS4_SFC", "2T_GDS4_SFC","SSHF_GDS4_SFC","SLHF_GDS4_SFC","Z_GDS4_SFC","BLH_GDS4_SFC","SSRD_GDS4_SFC","STRD_GDS4_SFC", "SKT_GDS4_SFC"] gard_sfc_var = ["precip_total","precip...
from netCDF4 import Dataset, MFDataset import logging LOGGER = logging.getLogger("PYWPS") def set_basic_md(resource): """ basis meta data :param resource: netCDF file where basic meta data should be set """ import sys from datetime import datetime as dt py_version = sys.version creati...
"""Defines Builder for creating DeepA2 datasets from Entailment bank data.""" from __future__ import annotations import dataclasses import logging import pathlib import random from typing import List, Dict, Union, Any import zipfile import datasets # import jinja2 import pandas as pd from tqdm import tqdm # type: ...
import torch import torch.nn as nn import torch.nn.functional as F from model.backbone.Res2Net import res2net50_v1b_26w_4s from model.backbone.pvtv2 import pvt_v2_b2 from model.refineUnet import RefineUNet class BasicConv2d(nn.Module): def __init__(self, in_planes, out_planes, kernel_size, stride=1, padding=0...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
import random import numpy as np import pandas as pd import gym from gym import spaces import math # Default parameters for default MG EMS environment. # days range DEFAULT_DAY0 = 0 DEFAULT_DAYN = 10 # Balancing market prices DEFAULT_MK_PRICE = list(pd.read_csv('AESO_price.csv', index_col=None, skiprows=4)...
import numpy as np import skimage.morphology as morph import skimage.feature as feature import skimage.measure as measure from scipy import ndimage ### calculation of (maximum) reconstruction volume size ### along z axis def calc_zsize(x, y): return x+y ### calculation of number of voxels in the ### reconstru...
import os import random import numpy as np import torch import torch.nn as nn import torchvision import torchvision.transforms as transforms from torch.utils.data import DataLoader, Dataset device = torch.device("cuda" if torch.cuda.is_available() else "cpu") n_ch = 3 im_sz = 32 class AverageMeter(object): """...
import numpy as np import cv2 from misc import find_bottom, find_long_edges, split_edge_seqence, \ norm2, vector_cos, vector_sin, split_long_edges def norm2(x, axis=None): if axis: return np.sqrt(np.sum(x ** 2, axis=axis)) return np.sqrt(np.sum(x ** 2)) def cos(p1, p2): return (p1 * p2).sum()...
import norm.config as config from sqlalchemy import Column, Integer, String, Text, exists, and_ import json import logging import traceback logger = logging.getLogger(__name__) class Version(config.Model): """ Version lambdas """ __tablename__ = 'versions' id = Column(Integer, primary_key=True,...
import os from six.moves import urllib import tempfile import numpy as np import pandas as pd import tensorflow as tf from matplotlib import pyplot as plt # Examine software versions print(__import__('sys').version) print(tf.__version__) print(tf.keras.__version__) ### For downloading data ### # Storage directory ...
from typing import AsyncIterator, TypeVar, List, AsyncIterable import uritemplate import dateutil.parser from aiogithub.helpers.typing import is_list_type_hint, get_list_element_hint T = TypeVar('T') class BaseObject(dict): """Base class for all data objects""" @staticmethod def _get_key_mappings(): ...
import numpy as np from google.cloud import vision import datetime import io import os import re SKIPWORDS = ['time', 'date'] ENDWORDS = ['total', 'balance', 'amount'] STOPWORDS = ['visa', 'price you pay', 'debit', 'date', 'credit', 'subtotal', 'tax', 'coupons', 'btotal'] BLACKLIST_WORDS = ['register', 'cashier', 'tha...
#!/usr/bin/env python3 import sys from pathlib import Path from typing import Optional from phantom_brave import * verbose = False def dbg(s: str) -> None: if verbose: print(' ' + s) def _add_item_to_category(cat_name: str, item_class_name: str, start_dat: StartDatArchive) -> None: cat = start_...
import torch import numpy as np import typing import json import os from functools import partial from .. import Chem from .. import corruption_dataset from .. import molecule_representation as mr from .. import vocabulary from .summary import JointModelSummary from . import joint_network from . import action_repre...
from __future__ import print_function ''' Tools to analyse the local many-body density matrix (multiplet structure). ''' try: from builtins import range except: pass import numpy as np from scipy.linalg import logm import h5py def get_rho_histogram(rho, S=None, L=None, J=None, num_ev=0, Rpr_list=None): ...