text
stringlengths
3.07k
12.6k
from functools import lru_cache import numpy as np from .geometry import Circle, Point, Rectangle def bbox_center(region): """Return the center of the bounding box of an scikit-image region. Parameters ---------- region A scikit-image region as calculated by skimage.measure.regionprops(). ...
from cv2 import cv2 import time import pyautogui import numpy as np import mss from os import listdir # from run import getBackgroundText import torch from random import randint # example_captcha_img = cv2.imread('images/example.png') model = torch.hub.load('./captcha', 'custom', "captcha/bomb_captcha.pt", source='lo...
from datetime import datetime import xml.etree.ElementTree as ET import unicodedata as ud import enchant import re from stdnum import isbn from stdnum import exceptions # ----------------------------------------------------------------------------- def preprocessISBNString(inputISBN): """This function normalizes a g...
import numpy as np import cv2 from enum import Enum class Models(Enum): ssd_lite = 'ssd_lite' tiny_yolo = 'tiny_yolo' tf_lite = 'tf_lite' def __str__(self): return self.value @staticmethod def from_string(s): try: return Models[s] except KeyError: ...
import math from typing import Optional, Union, Tuple, List import numpy as np import torch import torch.nn.functional as F from torch import Tensor from torch_geometric.utils.num_nodes import maybe_num_nodes from torch_scatter import scatter, segment_csr, gather_csr from torch_scatter.utils import broadcast import ...
# coding=utf-8 # Copyright 2022 The Google Research 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 applicab...
#!/usr/bin/env python3 import argparse import png import numpy as np import csv from matplotlib import pyplot as plt # map a scalar value to a color from a colormap def map_to_color(scalar, colormap): if scalar is None: return None # search in list to find scalar lo = int(0) hi = int(colormap....
################################################################################ # This software was developed by the University of Tennessee as part of the # Distributed Data Analysis of Neutron Scattering Experiments (DANSE) # project funded by the US National Science Foundation. # # See the license text in license.t...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from...
import json import maya import pandas as pd import numpy as np import matplotlib.pyplot as plt days = { 0:'monday', 1:'tuesday', 2:'wednesday', 3:'thursday', 4:'friday', 5:'saturday', 6:'sunday' } NEWLINE = '\n' SPACE = ' ' COLON = ':' def day(t): # where t means unformatted time ...
from urllib.parse import quote,unquote from estring.consts import greece_md,greece_upperch from estring.estring import is_int_str,is_float_str import re from efuntool.ebooltool import blor_rtrn_first from efuntool.etypetool import is_number ##### def rplc(s,d): for k in d: s = s.replace(k,d[k]) return(...
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2021 <NAME> <<EMAIL>> # # Distributed under terms of the MIT license. """ """ import os import base64 import json import dash_html_components as html import dash_core_components as dcc from dash.dependencies import Input,Output,State fr...
#!/usr/bin/python3 # File: test_state.py # Authors: <NAME> - <NAME> # email(s): <<EMAIL>> # <<EMAIL>> """ This Module Defines Unittest for models/state.py. Unittest classes: TestAmenity_instantiation TestAmenity_save TestAmenity_to_dict """ import os import models import unittest from datetime i...
# This file is part of fionautil. # http://github.com/fitnr/fionautil # Licensed under the GPLv3 license: # http://http://opensource.org/licenses/GPL-3.0 # Copyright (c) 2015-6, <NAME> <<EMAIL>> import itertools from functools import reduce import sys import fiona import fiona.transform try: from shapely.geometr...
#!/usr/bin/env python # # Copyright 2011-2015 Splunk, 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...
# coding: utf-8 """ FRITZ!Box SmartHome Client ~~~~~~~~~~~~~~~~~~~~~~~~~~ """ from __future__ import print_function, division import re import time import json import socket import click from .fritz import FritzBox @click.group() @click.option('--host', default='169.254.1.1') # fritzbox "emergency" IP @c...
import os from pyscf.pbc.gto import Cell from pyscf.pbc.scf import KRHF from pyscf.pbc.tdscf import KTDHF from pyscf.pbc.tdscf import krhf_slow_gamma as ktd import unittest from numpy import testing import numpy from test_common import retrieve_m, retrieve_m_hf, assert_vectors_close, tdhf_frozen_mask class DiamondT...
import os import cv2 import numpy as np import torch import imageio from torchvision import transforms from .colmap_utils import * import pdb def load_img_list(datadir, load_test=False): with open(os.path.join(datadir, 'train.txt'), 'r') as f: lines = f.readlines() image_list = [line.strip() for l...
""" Multivariate loc_scale priors for convolutional layers """ from numbers import Number import torch.distributions as td import torch import math from .base import Prior from . import distributions __all__ = ('ConvCovariance', 'FixedCovNormal', 'FixedCovLaplace', 'FixedCovDoubleGamma', 'FixedCovGenNorm') class P...
# # Copyright 2018-2021 <NAME> # 2019 <NAME> # 2015-2016 <NAME> # # ### MIT license # # 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 withou...
import logging import os from ftplib import FTP import time class SPSConnectionException(Exception): def __init__(self): pass class SPSLib: ## The Constructor # @param client {FTP} An FTP client to be used as the connection # @param default_destination {string} Path to where the files are aut...
import time import argparse import numpy as np from sklearn.metrics import confusion_matrix import cv2 from models import TSN from transforms import * import pycuda.driver as cuda from PIL import Image from streaming import streaming import os def make_ucf(): index_dir = '/cmsdata/hdd2/cmslab/haabibi/UCF101CL...
# RT TTS - Voiceroid from aiofiles import open as async_open from aiohttp import ClientSession import asyncio HEADERS = { 'authority': 'cloud.ai-j.jp', 'accept': 'text/javascript, application/javascript, */*; q=0.01', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, lik...
import os import sys import numpy as np import torch import argparse import _pickle as pkl import matplotlib.pylab as plt import seaborn as sea sea.set_style("whitegrid") from matplotlib.offsetbox import OffsetImage, AnnotationBbox from random import uniform from .Protein import Protein from .Complex import Complex f...
from __future__ import print_function import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms from torch.optim.lr_scheduler import StepLR from mnist_demo.models.model import Net from mnist_demo.models.dataset import MyMN...
import os import typing from contextlib import suppress from pathlib import Path from qtpy.QtWidgets import QDialog, QFileDialog, QGridLayout, QPushButton, QStackedWidget from PartSegCore.io_utils import SaveBase from .algorithms_description import FormWidget from .custom_load_dialog import IORegister, LoadRegisterF...
# toImpr remove import? from Skill import the_skill class Hero: def __init__(self, name, type_): self.name = name self.type_ = type_ self.level = 1 self.EXP = 0 self.__HP = 5 # self.__STR = 2 # self.__AGI = 1 # self.__INT = 1 ...
#! /usr/bin/env python3 # coding: UTF-8 """ Script: outil.py Auteur: remy Date: 14/03/2018 """ import outil import copy # Fonctions def gagne(entrepot): """ Vérifie si le puzzle décrit par l”entrepot est résolu ou non (c’est à dire que toutes les caisses ont été placées sur des cibles) et renvoie la répon...
import json import matplotlib.style as style import numpy as np import pandas as pd import pylab as pl def make_rows(cngrs_prsn): """Output a list of dicitonaries for each JSON object representing a congressperson. Each individaul dictionary will contain information about the congressperson as well as inf...
import io import os import re from collections import namedtuple from pathlib import PurePath, PurePosixPath, PureWindowsPath DigestEntry = namedtuple('DigestEntry', ['digest', 'flag', 'path']) class DigestError(Exception): pass class DigestParserError(DigestError): pass class DigestFormatError(DigestEr...
from datetime import datetime, timedelta import rumps rumps.debug_mode(True) # Icon font: # https://fonts.google.com/icons?selected=Material%20Icons%3Atimer config = { 'app_name': "MenubarTimer", 'app_icon': 'menubar-icon.png', 'button_until': "Start timer until ", 'button_add_five': "Add 5 mins to ti...
import re from collections import Counter from difflib import unified_diff from typing import List, Optional, Tuple, Union from bx_django_utils.dbperf.query_recorder import SQLQueryRecorder from bx_django_utils.stacktrace import StacktraceAfter def counter_diff(c1, c2, fromfile=None, tofile=None): def pformat(co...
# -*- coding: utf-8 -*- from __future__ import division import bz2 from datetime import datetime import os import pickle import numpy as np import torch from tqdm import trange from agent import Agent from utils import initialize_environment from memory import ReplayMemory from test import test from parsers import pa...
import pandas as pd from Bio import SeqIO from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.cluster import KMeans from sklearn.decomposition import PCA from sklearn.manifold import TSNE from sklearn.cluster import MeanShift from sklearn import preprocessing import matplotlib.pyplot as plt import...
import re from datetime import datetime, timedelta, timezone from typing import Dict, List, Optional from urllib.parse import unquote import semver # type: ignore from dateutil import parser from gitlab.v4.objects import ( # type: ignore Project, ProjectIssue, ProjectMergeRequest, ProjectTag, ) from ...
#!/usr/bin/env python # -*- coding: UTF-8 -*- import datetime from django import template from django.template import Library from django.template import resolve_variable from django.core.exceptions import ObjectDoesNotExist from html2text import html2text as h2t from intranet.org.models import Scratchpad register...
"""ETL code for the addon_aggregates dataset""" from pyspark.sql import SparkSession import pyspark.sql.functions as fun import click MS_FIELDS = [ "client_id", "normalized_channel", "app_version", "locale", "sample_id", "profile_creation_date", ] ADDON_FIELDS = [ "addons.addon_id", "...
#!/usr/bin/env python3 # Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma de # Barcelona (UAB). # # This work is licensed under the terms of the MIT license. # For a copy, see <https://opensource.org/licenses/MIT>. """A client for benchmarking the CARLA server.""" import argparse import lo...
#!/usr/bin/env python3 # Copyright (c) 2008-9 Qtrac Ltd. All rights reserved. # This program or module 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, either version 2 of the License, or # version 3 of the Lic...
# Authors: <NAME> and Elnaz # # Program that calculates the APD for a single cell in the grid by passing its # transmembrane potential over the time as input. # # This program also works with multiple AP's ! import sys import subprocess import time import numpy as np def forwarddiff(y, h): n = len(y) res = ...
import pytest from pytest import approx from salamanca import ineq as iq def test_gini_to_std(): obs = iq.gini_to_std(0.5) exp = 0.95387 assert obs == approx(exp, abs=1e-5) def test_std_to_gini(): obs = iq.std_to_gini(0.95387) exp = 0.5 assert obs == approx(exp, abs=1e-5) def test_theil_t...
#!/usr/bin/python # # Copyright 2022 DeepMind Technologies 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 a...
""" Original code from PyObjC-Cocoa See: https://bitbucket.org/ronaldoussoren/pyobjc/ AppKit helpers. Exported functions: * runEventLoop - run NSApplicationMain in a safer way * stopEventLoop - stops the event loop or terminates the application * callAfter - call a function on the main thread (async) """ # Use cocoa...
### Code from https://github.com/budzianowski/PyTorch-Beam-Search-Decoding/blob/master/decode_beam.py import operator import torch import torch.nn as nn import torch.nn.functional as F from queue import PriorityQueue from itertools import count device = torch.device("cuda" if torch.cuda.is_available() else "cpu") SOS_...
# -*- coding: utf-8 -*- """Concurrent streams and account polling using gevent. demonstrates usage of oandapyV20: - streaming prices - streaming events - account polling - restart of a greenlet in case of an exception For gevent details check: http://sdiehl.github.io/gevent-tutorial/ For REST-API V20 check: http://de...
import torch import torch.nn as nn import torch.nn.functional as F from collections import OrderedDict import math from torch.autograd import Variable __all__ = ['NUFNet', 'nufnet8', 'nufnet16','nufnet33','nufnet50'] def conv3x3(in_planes, out_planes, stride=1): """3x3 convolution with padding""" return nn.Co...
# call this script with `python -m evaluation.evaluate_poselines_globalaction` import numpy as np from numpy.core.fromnumeric import sort import pandas as pd import datetime import torch import pickle from torch.functional import norm from tqdm import tqdm from . import eval_utils from compoelem.config import config f...
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
#!/usr/bin/env python3 """scapy-dhcp-listener.py Listen for DHCP packets using scapy to learn when LAN hosts request IP addresses from DHCP Servers. Copyright (C) 2018 <NAME> https://jcutrer.com/python/scapy-dhcp-listener License Dual MIT, 0BSD Extended by jkulawik, 2020 """ from __future__ import print_function fro...
import sys PY2 = sys.version_info < (3,) if PY2: # Python 2 is not happy with our package having the same name, we need dynamic import import importlib try: # try old sklearn first, we are on python 2 sklearn_ft_base = importlib.import_module("sklearn.feature_selection.base") except Im...
# -*- coding: utf-8 -*- ## @package som_cm.som # # Implementation of SOM. # @author tody # @date 2015/08/14 import os import numpy as np import matplotlib.pyplot as plt from som_cm.np.norm import normVectors ## SOM parameter. class SOMParam: # @param h image grid size. # @param L0...
# Copyright 2020 Open Climate Tech Contributors # # 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 agr...
from PyQt5.QtCore import Qt, pyqtSignal from PyQt5.QtWidgets import (QWidget, QCheckBox, QLineEdit, QGroupBox, QVBoxLayout, QLabel) from PyQt5.uic import loadUi from msc import ES2Collection, ES2ValueType from msc import ES2Transform, ES2Color, Vector3, Quaternion class ClickableLabel(QLabel): mousePressed = pyq...
import json import logging import traceback from urllib.request import urlopen, Request from uniswap.uniswap import UniswapV2Client import os from web3 import Web3 import time from datetime import datetime import math logger = logging.getLogger(__name__) ACC = 'xxx' PRIVATE_KEY = 'xxx' API = 'xxx' NETWORK = 'https:/...
from camera.camera_object_detection_data import CameraObjectDetectionData import numpy import dataclasses import datetime import json from utils.dict import remove_null_keys import uuid from io import BytesIO from typing import List, Callable, Optional from camera.camera_recording import CameraRecording from loggers i...
import requests from urllib import request, parse import io import dnnlib import dnnlib.tflib as tflib import pickle import numpy as np from projector import Projector from PIL import Image import re import base64 from io import BytesIO import boto3 import uuid img_res = 256 def find_nearest(arr, val): "Element ...
from datetime import datetime import os.path import functools import collections import copy import re import time import logging import numpy as np import tensorflow as tf from train_common import get_global_step, get_lr_and_max_steps, get_ops, run_op import prune_algorithm.prune_common as pc logging.basicConfig(l...
import random import pkg_resources from .interface import Interface class Bullshit: """This class is used to control the game status.""" def __init__(self): self.running = False self.active_players = 0 def get_player_names(self,players): """Asks for the names of all players.""" ...
"""Test ThroughputReporter""" import pytest @pytest.fixture def klass(): """Return CUT.""" from agile_analytics import ThroughputReporter return ThroughputReporter def test_title(klass): """Ensure the title gets set.""" r = klass( title="Weekly Throughput" ) assert r.title == "W...
import json import pickle from abc import ABC, abstractmethod from threading import Lock from typing import Any import portalocker from .dicttree import NOTSET, query_tree, update_tree class NamespaceDriver(ABC): @abstractmethod def query(self, key: str) -> Any: pass @abstractmethod def key...
#!/usr/bin/python # ~~~~~============== HOW TO RUN ==============~~~~~ # 1) Configure things in CONFIGURATION section # 2) Change permissions: chmod +x client.py # 3) Run in loop: while true; do ./client.py; sleep 1; done from __future__ import print_function import sys import socket import json import time impo...
#!/usr/bin/env python # coding: utf-8 # In[19]: # %load get_nextstrain_data.py ### https://github.com/tomasMasson/covid-19-Annotations-on-Structures.git #!/usr/bin/env python3 import json import requests from utils.sm_annotations import Annotation import matplotlib.colors as mcolors def parse_json(input_file): ...
# 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 2021 <NAME> # # import random import os # import sys from optparse import OptionParser from PIL import Image """ if "darwin" in sys.platform: os.system("clear") elif "win" in sys.platform: os.system("cls") elif "linux" in sys.platform: os.system("clear"...
""" 此页面用于爬取雪球网单支股票数据 Created by CSDN梦栖,2020-05-22 """ # 导库 import os from bs4 import BeautifulSoup import requests import csv message = '即将开始处理...' # 获取源数据 def get_source_data(source_file_path): stock_id_list = [] with open(source_file_path, 'r', encoding='utf-8') as fp: reader =...
import automox_console_sdk as automox from automox_console_sdk.api import DevicesApi from automox_console_sdk.api import GroupsApi from automox_console_sdk.models import ServersIdBody, ServerGroupCreateOrUpdateRequest from getpass import getpass import ldap from ldap.controls import SimplePagedResultsControl import re ...
from JumpScale import j class Avahi(): # def __init__(self): # raise RuntimeError("should not init auto") # j.system.platform.ubuntu.checkInstall(["avahi-utils"],"avahi-browse") def _servicePath(self, servicename): path = "/etc/avahi/services" if not j.system.fs.exists(path=p...
import re import itertools EXAMPLES1 = ( ('19-exemple1.txt', 79), ) EXAMPLES2 = ( ('19-exemple1.txt', 3621), ) INPUT = '19.txt' def read_list(fn): beacons = list() with open(fn) as f: while match := re.match(r'--- scanner (\d+) ---', f.readline()): num = int(...
import multiprocessing import pickle import random import sys from collections import defaultdict from math import ceil, sqrt import numpy as np from scipy.stats import norm, skewnorm from tqdm import tqdm sys.path.append('..') import features INCOME_SECURITY = { 'employee_wage': 0.8, 'state_wage': 0.9, ...
#!/usr/bn/env python3 import requests,json import traceback def loginCCNU(username="",passwd="",suffix=""): errmessage = None try: url = "http://10.220.250.50/0.htm" payload = {"DDDDD":"%s"%username, "upass":"%s"%passwd, "suffix":"%s"%suffix, "0MKK...
import sys sys.path.append("..") from engineering_tool.electrics import * def Power_Electric(): voltage_DC = 15 # Volt DC current_DC = 2.5 # Amp DC voltage_AC1P = 225.5 # Vrms 1 Phase current_AC1P = 5.5 # Amp 1 Phase PF_AC1P = 0.8 # Power factor voltage_AC3P = 225.5 # Vrms...
import cv2 import os import numpy as np from sys import argv from lib import sauvola, linelocalization, pathfinder from WordSegmentation import wordSegmentation, prepareImg from time import time as timer from SamplePreprocessor import preprocess from DataLoader import Batch from Model import Model def draw_line(im, p...
import pyrebase from datetime import datetime import firebase_admin from firebase_admin import db, credentials import pandas as pd import tabulate import time Config = { "apiKey": "<KEY>", "authDomain": "firestore-4dc04.firebaseapp.com", "databaseURL": "https://firestore-4dc04.firebaseio.com", "proje...
# -*- coding: utf-8 -*- import tensorflow as tf import numpy as np import skimage.io as io import skimage.transform as transform from os.path import join import vfn.network as nw import argparse import json import time global_dtype = tf.float32 global_dtype_np = np.float32 batch_size = 200 def overlap_ratio(x1, y1, ...
import os import json import torch import pickle from torch.utils.data import DataLoader from model import KGEModel from dataloader import TrainDataset from dataloader import BidirectionalOneShotIterator from classifier import ClassifierTrainer, LTTrainer, NoiGANTrainer import numpy as np from sklearn.metrics import ac...
import torch from torch.utils.data import DataLoader import pathlib import os import numpy as np import dataset from criteria import cal_criteria, bbrebuild def loss_from_log(train_name): with open('../logs/log_%s.txt' % train_name) as f: lines = f.readlines() val_loss = [] train_loss...
# Copyright (c) 2018 NVIDIA Corporation from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import math import numpy as np import python_speech_features as psf import resampy as rs import scipy.io.wavfile as wave def get_speech_features_from_file(filename, num_fe...
import numpy as np import math def grid_reading(key, table): _key = sorted(key) order = [key.index(i) for i in _key] print(list(key)) #print(_key) print('Порядок использования столбцов:', order) m = table.shape[0] res = '' for j in order: for i in range(m): res += ta...
""" Copyright (c) Dell Inc., or its subsidiaries. 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 """ import csv import dataclasses...
#!/usr/bin/python import cv2 import os import subprocess import numpy as np face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_default.xml') face_cascade_alt = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml') face_cascade_alt2 = cv2.CascadeClassifier('haarcascades/haarcasc...
from abc import ABC, ABCMeta, abstractmethod, abstractproperty from torch.nn import Module, MSELoss, Linear from torch.optim import Adam import torch from torch.autograd import Variable import torch.nn.functional as F from torch import FloatTensor import os import matplotlib as mpl import torch.nn as nn mpl.use('Agg')...
import logging import os import shutil import sys import tempfile import click import numpy as np import tensorflow as tf import tensorflow_hub as hub from word_embeddings import embeddings def non_zero_tokens(tokens): """Receives a batch of vectors of tokens (float) which are zero-padded. Returns a vector of t...
''' MIT License Copyright (c) [2018] <NAME> (<EMAIL>). Universidad de Alcalá. Spain 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...
# -*- coding: utf-8 -*- import imageio import matplotlib.pyplot as plt import numpy img = imageio.imread('Z:/DRPI/questoes_aula/sat_map3.tif') dim = img.shape col = dim[1] lin = dim[0] def histogram(img, s, rgb): """ Função que desenha os histogramas :param img: A imagem :param s: ...
__author__ = 'sibirrer' from astrofunc.LensingProfiles.nfw import NFW from astrofunc.LensingProfiles.nfw_ellipse import NFW_ELLIPSE import numpy as np import numpy.testing as npt import pytest class TestNFW(object): """ tests the Gaussian methods """ def setup(self): self.nfw = NFW() d...
# -*- coding: utf-8 -*- """ Created on Fri Mar 1 11:52:48 2019 This is the module for evaluation metrics @author: Cheng """ # -*- coding: utf-8 -*- """ Created on Sat Mar 2 21:31:32 2019 @author: cheng """ import numpy as np from scipy.spatial.distance import directed_hausdorff def get_classified_errors(test_pred...
from numpy import array, compress, zeros import wx from wx.lib.mixins.listctrl import ListCtrlAutoWidthMixin from spacq.interface.list_columns import ListParser """ Embeddable, generic, virtual, tabular display. """ class VirtualListCtrl(wx.ListCtrl, ListCtrlAutoWidthMixin): """ A generic virtual list. """ ma...
# by protago90 from tictactoe.board import BoardAPI from abc import abstractmethod from typing import Callable, List, Optional, Tuple import random import time class PlayerAPI(): SIGNS = BoardAPI.SIGNS # TicTacToe's board hardcoded signs NAP = 0 ID = 'none' def __init__(self, sign: str) -> None: ...
from typing import Union, Iterable, Coroutine, Callable from inspect import isfunction, ismethod, isroutine, iscoroutine, signature, _empty import discord from .. import errors from .. import utils # Class Command class Command: def __init__(self, _function: Union[Callable, Coroutine], name: str = None, aliases: ...
# -*- coding: utf-8 -*- """ Created on Sat Mar 13 11:40:13 2021 @author: Mayur """ """ Product class has all functinality related to adding/removing/displaying products """ class Product: name = "" price = 0 def __init__(self): self.all_products = [] def reset(self): self.all_...
import numpy as np import matplotlib.pyplot as plt # 常量 pi = 3.1415926 # 声波属性 A = 0.01 u = 343 v = 40000 _lambda = u / v w = 2 * pi * v k = 2 * pi / _lambda T = 2 * pi / w rho = 1.293 # 悬浮物件的尺度 R = 0.005 # 两点换算为距离 def r(x0, y0, x1=0, y1=0): return np.sqrt((x0 - x1) ** 2 + (y0 - y1) ** 2) # 波运算函数 def wave(x1...
import collect_array as ca import collect_device as cd import collect_gen as cg import collect_id as ci from processing import collect_loop as cl def print_dict_sorted(mydict): keys = sorted(mydict) entries = "" for key in keys: value = mydict[key] entries += "'" + key + "': " + value.__...
# Authors: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # # License: BSD (3-clause) import math import numpy as np from scipy import linalg from scipy.fftpack import fft, ifft import six def _framing(a, L): shape = a.shape[:-1] + (a.shape[-1] - L + 1, L) strides = a.strides + (a.strides[-1],) return np.l...
import numpy as np from torchinfo import summary import pickle import torch import datetime def weights_init(m): if isinstance(m, torch.nn.Linear): torch.nn.init.normal_(m.weight,mean=0.0, std=0.00001) #m.bias.data.fill_(0) if isinstance(m, torch.nn.Conv2d): torch.nn.init.normal_(m.wei...
from django.db import models from django.utils import timezone from accounting.models import LedgerAccount, LedgerEntry class MembershipLevel(models.Model): """Descriptor for membership costs and privileges. :param name: Name of membership level. :param cost: Cost of this membership level. :param pe...
## import os import numpy as np import argparse import shutil import torch import torch.nn as nn import torch.nn.functional as F from torch import optim import torch.utils.data as data_utils from dataset import Polygon3DSample from network import ImplicitNet, LossFunction from common_tools.utils import read_json, dra...
""" Helper functions for recipy tests. """ # Copyright (c) 2016 University of Edinburgh. import os import os.path import re import shutil try: from ConfigParser import SafeConfigParser except: from configparser import SafeConfigParser from integration_test import database from integration_test import enviro...
from typing import Dict, List, Tuple, no_type_check import jmespath # import turvallisuusneuvonta.csaf.core.rules.mandatory.acyclic_product_ids as acy_product_ids # import turvallisuusneuvonta.csaf.core.rules.mandatory.consistent_product_status as con_pro_sta import turvallisuusneuvonta.csaf.core.rules.mandatory.defi...
# -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import, division from alchemist.db import session from alchemist.conf import settings from importlib import import_module from alchemist.db.query import Query from sqlalchemy.orm.util import has_identity from sqlalchemy.ext.declarative import cls...
"""Main script for controlling the calculation of the IS spectrum. Calculate spectra from specified parameters as shown in the examples given in the class methods, create a new set-up with the `Reproduce` abstract base class in `reproduce.py` or use one of the pre-defined classes from `reproduce.py`. """ # The start ...