text
stringlengths
3.07k
12.6k
#! /usr/bin/env python """ This script plots the stacked contribution of each atom type to a given MO. You can also group together the contribution of a set of atoms (for example that form a ligand). Usage: plot_dos.py -ligand 2 3 -emin -5.0 -emax 2.0 When you use the ligand flag you imply that some atom kinds, in th...
import numpy as np import pandas as pd from q_learning_tabular.q_table import QTable from matplotlib import pyplot as plt def smooth_plot(all_rewards, smoothed_rewards,title): plt.figure(2, figsize=(12, 6)) plt.clf() plt.title(title) plt.xlabel("Epsiode") plt.ylabel("Total Reward") plt.plot(a...
import json from typing import Mapping, Sequence from django.contrib.auth.models import AnonymousUser from django.contrib.sessions.middleware import SessionMiddleware from django.db import models from graphene.test import Client from backend.model.TutorialRelatedModel import FAKE_UUID from graphery.schema import sche...
# pylint: disable=invalid-name # pylint: disable=too-many-arguments """ Generate Foucaugrams (Foucault Knife Edge images) for lens testing. Documentation and examples are available at <https://lenstest.readthedocs.io> """ import numpy as np import matplotlib.pyplot as plt import lenstest.lenstest __all__ = ('foucaul...
import os import numpy as np from easydict import EasyDict as edict __C = edict() cfg = __C # Dataset options # __C.DATASET = edict() __C.DATASET.SOURCE = 'SYNTHIA' __C.DATASET.TARGET = 'Cityscapes' __C.DATASET.VAL = 'Cityscapes' __C.DATASET.DATAROOT_S = '' __C.DATASET.DATAROOT_T = '' __C.DATASET.DATAROOT_VAL = '' _...
# -*- coding: utf-8 -*- from __future__ import absolute_import # Import Python libs import contextlib import errno import logging import os import shutil import subprocess import time # Import salt libs import salt.utils import salt.modules.selinux from salt.exceptions import CommandExecutionError, FileLockError, Mi...
import unittest import warnings import z3c.testsetup from z3c.testsetup.util import got_working_zope_app_testing from z3c.testsetup.tests.test_testsetup import get_basenames_from_suite from z3c.testsetup.tests import cave GOT_WORKING_ZOPE_APP_TESTING = got_working_zope_app_testing() class TestTestGettersAndCollector...
#!/usr/bin/env python3 """ Checks your images after manual labeling for: - Unlabeled images - Images with two bounding boxes - Blank text files Change image_dir to the directory you want to check """ import os import hashlib import imghdr import re import select import sys # Run on a specific image dir (if no arg sp...
import tushare as ts import threading import time import os import sys sys.path.append("..") from api.data import StockApi from stock_financial.comm_funcs import get_redis_client from stock_financial.comm_funcs import get_config from stock_financial.comm_funcs import except_handle def push_code_queue(redis_conn, qu...
"""This module contains the general information for FirmwareComputeStoragePack ManagedObject.""" from ...ucscentralmo import ManagedObject from ...ucscentralcoremeta import UcsCentralVersion, MoPropertyMeta, MoMeta from ...ucscentralmeta import VersionMeta class FirmwareComputeStoragePackConsts(): INT_ID_NONE = ...
import copy import csv import inspect import tempfile from collections import OrderedDict from functools import partial, wraps from types import GeneratorType def immutable(func): """ Decorator for wrapper "builder" functions. These are functions on the Query class or other classes used for building quer...
""" Say you have a neural network `f` that takes as input a vector. Consider the task of estimating M = E[f(x)] where x ~ N(0, I) Some ideas for approximating M: 1. (Naive) \hat M = f(0) 2. (Monte Carlo) \hat M = \frac{1}{N} \sum_i^N f(x_i), x_i ~ N(0, I) 3. (Convolution) \hat M = \hat f (0) where \hat f is a conv...
""" Messages module """ from datetime import timedelta import datetime # Kaira import from kaira.signing import dumps as signing_dumps from kaira.signing import loads as signing_loads from kaira.cookie import CookieManager from kaira.wrapper import ContextManager DEBUG = 10 INFO = 20 SUCCESS = 25 WARNING = 30 ERROR...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ About: Test the distributed MEICA locally (without any networking). """ import argparse import csv import math import sys import time import numpy as np sys.path.insert(0, "../") from pyfastbss_core import pyfbss from pyfastbss_testbed import pyfbss_tb import mei...
from docx.api import Document from app.models import Lesson as Lesson_model from app import db from app.googlecalendar import add_lesson class Lesson: def __init__(self, name, for_whom, lesson_type, classroom): self.name = name self.for_whom = for_whom self.lesson_type = lesson_type ...
import os import torch import torchvision.utils as tvutils # ------------------------------------------------------ # -----------Reformulate degradation kernel------------- def normkernel_to_downkernel(rescaled_blur_hr, rescaled_hr, ksize, eps=1e-10): blur_img = torch.rfft(rescaled_blur_hr, 3, onesided=False) ...
import os import random import smart_open import pandas as pd import click N_POSITIVE = 99684 N_NEGATIVE = 996941 N_TOTAL = N_POSITIVE + N_NEGATIVE POSITIVE_RATIO = N_POSITIVE / N_TOTAL def read_submission(file, ordered): df = pd.read_csv(file) columns = df.columns.values if ordered: assert len(...
#!/usr/bin/env python # encoding: utf-8 """ file_sorter.py Sort a variant file based on position or rank score. Created by <NAME> on 2005-05-31. Modified by <NAME> on 2014-01-14. """ from __future__ import print_function from __future__ import unicode_literals import sys import os import argparse from tempfile i...
"""[Tic Tac Toe Game implentation] Structure: [Main]: [The game is created as a loop inside the main function. inside the Main function there is an object of class in addtion to a set of seperate functions] [Class]: ...
import pprint from typing import Optional, List, Tuple, Set, Dict import numpy as np import pandas as pd from geopy.distance import geodesic from overrides import overrides from sklearn.impute import SimpleImputer from sklearn.pipeline import make_pipeline from sklearn.preprocessing import FunctionTransformer from py...
import gzip import logging import pickle import time from pathlib import Path from typing import Any, Dict, List, Optional import numpy as np import pandas as pd import sqlalchemy as sa import torch from sklearn import metrics from pagnn.utils import StatsBase, evaluate_validation_dataset from .args import Args log...
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # ----------- # SPDX-License-Identifier: MIT # Copyright (c) 2021 <NAME> # uuid : 8077014c-b978-11eb-aa40-875c86851247 # author: <NAME> # email : <EMAIL> # date : 2021-05-20 # ----------- """ The `validate` command is used to analyze the Markdown files in the system fo...
""" Author: <NAME> Organization: Spatial data infrastructure Rhineland-Palatinate, Germany Contact: <EMAIL> Created on: 21.01.20 """ from django.http import HttpRequest from service.models import Metadata, Organization, Layer, FeatureType from service.filters import ChildLayerFilter, FeatureTypeFilter from service.ta...
from __future__ import division import numpy as np import warnings from menpo.base import Vectorizable, MenpoMissingDependencyError from menpo.transform import Transform, Translation, Rotation def align_2d_3d(points_3d, points_image, image_shape, focal_length=None, distortion_coeffs=None): try: ...
# -*- coding: utf-8 -*- import sys, os, time, re sys.path.append(os.path.abspath("..")) from lib import preload from wikipedia import * """ linkedPages =========== Override function linkedPages to support subpage linking. """ def extractLinkedPages(content, page, withImageLinks=False): """ This function extr...
import os from typing import List, Tuple import pandas as pd from .settings import RESULTS_PATH class Group: """ Models a group of people willing to visit the Santa's Workshop """ def __init__(self, num: int, days: List[int], size: int): self.num = num # id of the group self.days = d...
from tokenize import tokenize, untokenize, COMMENT,NL,NEWLINE from efdir import fs from io import BytesIO import estring.estring as eses import re import elist.elist as elel # tokenize.NL # Token value used to indicate a non-terminating newline. # The NEWLINE token indicates the end of a logical line of Python code; ...
import sqlite3 as sql import os import xml.etree.cElementTree as ET import time users = ( "CREATE TABLE IF NOT EXISTS users (" "u_id integer PRIMARY KEY," "u_name text NOT NULL" ");" ) nodes = ( "CREATE TABLE IF NOT EXISTS nodes (" "n_id integer PRIMARY KEY," "u_id integer NOT NULL," "l...
from osgeo import gdal, ogr, osr import pandas as pd import numpy as np import geopandas as gpd from shapely.geometry import Point """ """ class StreamGrid(object): ''' StreamGrid class designed to read in stream grids and create a dataframe. ''' def __init__(self,path): self.path = path ...
from __future__ import annotations from typing import Optional, Set, List from puzzle import Puzzle from solver import BfsSolver # difficulty constants IMPOSSIBLE = 'impossible' TRIVIAL = 'trivial' EASY, MEDIUM, HARD = 'easy', 'medium', 'hard' # constant for the set of letters used LETTERS = "abcdefghijklmnopqrstuv...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_mpris ---------------------------------- """ import imp import os import sys import threading import time import pytest from scarlett_os.internal.gi import Gio, GLib, GObject # DBUS_SESSION_BUS_ADDRESS = os.getenv("DBUS_SESSION_BUS_ADDRESS") DBUS_SESSION_BUS_A...
import math from entity import Entity, Actor, Item from game_map import GameMap from engine import Engine from render_order import RenderOrder from equipment_types import EquipmentType from components.ai import BaseAI from components.equipment import Equipment from components.fighter import Fighter from components.con...
import binascii import cStringIO import hashlib import os import struct class PKCS1Error(RuntimeError): ''' Base class for PKCS1 encoding/decoding errors. Error of this or derived classes should be caught by the calling code and then a generic error message should be returned to the caller. '''...
#!/usr/bin/python ################################################################################################################### ### This code is developed by HighEnergyDataScientests Team. ### Do not copy or modify without written approval from one of the team members. ############################################...
#!/usr/bin/env python3 import sys import os import time import shutil from optparse import OptionParser from rgbmatrix import RGBMatrix, RGBMatrixOptions from matrixdemos.scripts.get_file import get_file from subprocess import Popen, DEVNULL from matrixdemos import DATA_PATH from PIL import Image BOLD = '\033[1m' ENDC...
#!/usr/bin/env python # Copyright (c) 2022 Oxford Robotics Institute (ORI), University of Oxford # # This work is licensed under the terms of the MIT license. # For a copy, see <https://opensource.org/licenses/MIT>. import json import time import carla from edr.edr_sensor import EDRSensor from ..core.utilities impo...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # 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,...
from django.http import HttpResponse from django.http.response import JsonResponse from airone.lib.acl import ACLType, ACLObjType from airone.lib.http import http_get, http_post, render from airone.lib.http import check_permission from airone.lib.profile import airone_profile from airone.lib.log import Logger from en...
# 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 numpy as np from scipy.io import wavfile import pyreaper import pandas as pd import re import vsq4_writer import phonetic_symbol def EWMA_Outlier_Check(target,ewm_span): # 指数加重移動平均外れ値修正 target = pd.Series(target) ewm_mean = target.ewm(span=ewm_span).mean() ewm_std = target.ewm(span=ewm_span).std() return n...
import numpy as np from scipy.special import loggamma as lgamma from scipy.linalg import solve_triangular from ..utils.math_utils import subsets class BGe: """Ported to Python from the R version by <NAME> and <NAME> :footcite:`kuipers:2014`. """ def __init__(self, *, data, maxid): self.maxi...
"""BioGRID RDBMS model definition.""" from sqlalchemy.orm import relationship from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String, Float, Text, ForeignKey from ebel.manager.rdbms.models import object_as_dict Base = declarative_base() class Biogrid(Base): """Cl...
#!/usr/bin/env python3 import sys assert sys.version >= '3.3', 'Please use Python 3.3 or higher.' import argparse import logging import os import ssl import json import asyncio import aiohttp import aiohttp.server from urllib.parse import urlparse, parse_qsl from aiohttp.multidict import MultiDict def constant_time...
# -*- coding: utf8 -*- import os import sys import click from itertools import chain from operator import itemgetter from glob import glob from .utils import buildVoca, transReview from .utils import readJson from ..utils import pkdump, recordTime from .. import config from .cold import generateColdUser from .sentiOu...
"""Main landshark commands.""" # Copyright 2019 CSIRO (Data61) # # 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 applic...
import datetime from dataclasses import dataclass from logging import getLogger from typing import Any, Callable from dhis2 import Api from django.utils import dateparse, timezone logger = getLogger(__name__) @dataclass(frozen=True) class Dhis2Relation: """ describe a m2m relation from an object model to so...
#!/usr/bin/env python3 from pathlib import Path import re import cmd import sys from functools import wraps class DebugShell(cmd.Cmd): intro = 'Welcome to the debug shell.\n- Type help or ? to list commands.\n' prompt = '(debug) ' def parse_args(method): @wraps(method) def wrapper(self,args...
import time import torch from torch.utils.data import Dataset, DataLoader from data import LJspeechDataset, collate_fn_synthesize from wavenet import Wavenet from wavenet_iaf import Wavenet_Student from torch.distributions.normal import Normal import librosa import os import argparse parser = argparse.ArgumentParser(...
import os import sys import json import datetime import numpy as np import skimage.draw from os import listdir from xml.etree import ElementTree from numpy import zeros from numpy import asarray from numpy import expand_dims from mrcnn.model import load_image_gt from mrcnn.utils import compute_ap from mrcn...
import inspect import os import typer from alembic.config import Config as AlembicConfig from alembic.config import command as alembic_command from magnet.cli.errors import handle_error app = typer.Typer() def command(func): wrapped = handle_error(func) return app.command()(wrapped) @command def show_ale...
import datetime import logging import os from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import gui.utils from gui.template_view.info_view.base import InfoView logger = logging.getLogger(__name__) def get_values_sorted_after_key(d: dict): return [value for key, value in sorte...
import json import numpy as np import matplotlib.pyplot as plt def vec_cross(x, y): """Calculates the cross product of the last dimensions of x and y.""" xT = x.T yT = y.T return np.array([xT[1]*yT[2]-xT[2]*yT[1], xT[2]*yT[0]-xT[0]*yT[2], xT[0]*yT[1]-xT[1]*yT...
import ast import configparser import logging import os.path import subprocess from abc import ABC, abstractmethod from typing import Dict, Iterator, NamedTuple, Type from common import directories, file_utils from common.commands.base import ArxivBatchCommand from common.compile import get_output_files from common.ty...
from queue import Queue from concurrent.futures import ThreadPoolExecutor import threading import time from flask import Flask, request import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output, State from traceback import print_exc import requests as...
#!/usr/bin/env python3 # # -*- coding: utf-8 -*- """ Implementation of mkdfa.pl for python 3 """ import sys import os import shutil import tempfile import re import codecs import subprocess JULIUS_BIN = os.path.dirname(os.path.abspath(__file__)) if sys.platform == 'win32': CMD_MKFA = JULIUS_BIN + '/mkfa.exe' ...
import pytest import numpy as np from rio_color.utils import to_math_type from rio_color.operations import ( sigmoidal, gamma, saturation, simple_atmo, parse_operations, simple_atmo_opstring, ) @pytest.fixture def arr(): return to_math_type( np.array( [ ...
#!/usr/bin/env python # # See top-level LICENSE file for Copyright information # # -*- coding: utf-8 -*- """ This script examines a set of files and indicates which do and which do not have sufficient calibs """ import argparse from pypeit import defs from IPython import embed def parser(options=None): parser = a...
import math import mesh_tensorflow as mtf import tensorflow.compat.v1 as tf # helpers def default(val, d): return val if val is not None else d # simple linear layer def linear(x, dim_out, scope = 'linear', bias = True): with tf.variable_scope(scope): *_, dim_in = x.shape w_init_stdev = 1 / ...
import typing import requests from bs4 import BeautifulSoup from rest_framework import decorators, response, status from debisapi.utils import get_payload from v1 import authentication RESULTS_URL = ( "http://debis.deu.edu.tr/OgrenciIsleri/Ogrenci/OgrenciNotu/index.php" ) @decorators.api_view(["GET"]) @authent...
import tensorflow as tf from tensorflow.keras.models import Model from tensorflow.keras.layers import Input, Lambda, Dense, Embedding import numpy as np dim = 3 t_q = 5 t_kv = 7 mbs = 2 q = np.random.normal(size=(mbs, t_q, dim)).astype(np.float32) v = np.random.normal(size=(mbs, t_kv, dim)).astype(np.float32) k = np...
import numpy as np from time import time from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer from sklearn.decomposition import NMF, LatentDirichletAllocation from sklearn.datasets import fetch_20newsgroups LEARNING_OFFSET = [1.1, 2.0, 5.0, 10.0, 20.0, 50.0, 100.0, 200.0] BATCH_SIZE = [2, 4, 8...
import numpy as np import pylab as plt from lib.numpy_pack import packArray,unpackArray from lib.decomposer import * from lib.YearPlotter import YearPlotter import matplotlib.pyplot as plt from ipywidgets import interact, interactive, fixed, interact_manual import ipywidgets as widgets class recon_plot: """A cla...
import pytest TEST_CONTENT = """ import pytest @pytest.mark.parametrize( ('a', 'b'), ( (1, 1), (1, 2), (1, 3), (1, 4), ) ) def test_a(a, b): assert b in (1, 4) """ @pytest.mark.parametrize("option_name", ("--select-...
import pygame import os import time import neat import visualize import pickle from objects.bird import * from objects.tube import * from objects.base import * pygame.font.init() programIcon = pygame.image.load('images/bird2.png') pygame.display.set_icon(programIcon) pygame.display.set_caption("AI Pinky Bird") sfon...
import argparse import sys from modes import ecb_enc, ecb_dyc, cbc_enc, cbc_dyc, cfb_enc, cfb_dyc, ofb_enc, ofb_dyc from sparkle import sparkle_enc, sparkle_dec from xoodyak import xoodyak_enc, xoodyak_dec from util import read_file_bytes, write_file_bytes, xor_all def parser(): des = """This is the homework of <NAME...
#External libs import ast import boto3 import json import sys import os from botocore.exceptions import ClientError #Establish our boto resources client = boto3.client('lambda') session = boto3.session.Session() region = session.region_name ec2Client = boto3.client('ec2') def import_config(lambda_name, alias=False): ...
from body import Body from legs import Legs from mounth import Mounth from touchSense import TouchSense from brain import Brain import pickle from kivy.graphics import * name = 'scarabBob' icon = 'scarabBob.png' """ touch right walk right touch up walk up touch left walk left touch down walk do...
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
# Copyright 2014-2020 <NAME> <<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 obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
#!/usr/bin/python3 import json with open('./function.json', 'r') as inf: funcStructure = json.load(inf) inf.close() # Output Generated Simuulation Code outf = open('./gen-sim.py', 'w') outf.seek(0) outf.flush() global depth depth = 0 global currentFunction currentFunction = "" # Header Code def header(): ...
import re import ctypes import typing import pathlib import itertools from collections import defaultdict from . import declarations from . import libtypes DEBUG_SHOW_SOURCES = False _COMMENT_START_RE = re.compile(r"^/\*\s*") _COMMENT_END_RE = re.compile(r"\s*\*/$") class ParserError(libtypes.AnnotatecError): ...
#!/usr/bin/env python3 import getopt import sys import configparser import csv import queue import os from multiprocessing import Process, Queue,Pool from collections import namedtuple from datetime import date, datetime, timedelta import time IncomeTaxQuickLookupItem = namedtuple( 'IncomeTaxQuickLookupItem', ...
import argparse import json import socket import time from multiprocessing.connection import Listener from typing import List from urllib.parse import urljoin import requests import validators import vsw.utils from vsw.log import Log from vsw.utils import Constant from vsw.commands import exit vsw_config = vsw.utils....
import sys import time import curses import click from ecstools.main import version from ecstools.resources.service import Service from ecstools.resources.task_definition import TaskDefinition from ecstools.lib.config import config COLOR_MAP = { 'NO_COLOR': 0, 'BLUE': 1, 'GREEN': 2, 'RED': 3, 'YE...
#!/usr/bin/env python # # Make software environment from a yml database. # import getopt import yaml import sys import shlex def usage(): print(""" {0} [--pkg=<pkg>] [--pkgs=<pkg1,pkg2>,...] [--script] \ [--docker] [--vagrant] [--split=...] [--distrib=...] \ /path/to/<example>.yml""".format(sys.argv[0])) ...
"""Dataset constructers""" from torch.utils.data import Dataset, ConcatDataset import torchvision from torchvision import transforms import AlbumentationsImageFolder from candidate_corruptions import dict_corruptions import os from albumentations.pytorch import ToTensor, ToTensorV2 import albumentations as album """...
#!/usr/bin/python # Based on nagios plugin : https://github.com/defaultUser0816/nagios-plugins/blob/master/check_esxi_resources.py import pyVmomi import argparse import atexit import humanize import re import os from pyVim import connect from pyVmomi import vim from pyVim.connect import Disconnect from operator impo...
""" Tools for sorting. """ from __future__ import annotations import typing from typing import ( AbstractSet, Any, Collection, Mapping, NamedTuple, Sequence, Set, Type, TypeVar, Union, ) from natsort import natsorted, ns from natsort.ns_enum import ns as ns_enum # noinspection...
# -*- coding: utf-8 -*- # videobox photo url extractor util # Gets the photo URL for various links '''URLExtractor File''' import re import json import base64 from bs4 import BeautifulSoup from discord.ext import commands from .utils import TwitterAuthException class PhotoExtractor(): """Provides a way to get p...
import logging import os import sys from pathlib import Path from typing import Tuple, Union from cryptography.fernet import Fernet import config from modules.create_process import create_piped_process, log_subprocess_output from modules.globals import get_current_modules_dir, instance_path # -- Log to Stdout keepin...
import databaseLib import gmailLib import sys class Receipt(): def __init__(self, order_id): self.db = databaseLib.Database() self.mail = gmailLib.Email() self.order_id = order_id self.customerID = "" self.orderDescription = "" self.first = "" self.last = "" self.str...
import contextlib import itertools import tkinter import pytest from porcupine import actions, get_main_window, tabs, utils _action_path_counter = itertools.count() @pytest.fixture def action_path(): return 'Test/Blah' + str(next(_action_path_counter)) def test_errors(porcusession, action_path): actions...
# -*- coding: utf-8 -*- import tempfile, os, pytest import tensorflow as tf import numpy as np import pinn from shutil import rmtree @pytest.mark.forked def test_potential_model(): """A simple example to test training and using a potential""" from ase import Atoms from ase.calculators.lj import Lenna...
# -*- coding: utf-8 -*- import collections import operator import colorama import six MAX_DEPTH = 10 TAB_WIDTH = 4 TAB = ' ' LIST_ITEM = '└─► ' COLOR_OUTPUT = True BOLD = colorama.Style.BRIGHT DIM = colorama.Style.DIM NORMAL = colorama.Style.NORMAL FG_BLACK = colorama.Fore.BLACK FG_RED = colorama.Fore.RED FG_GREEN =...
""" weight 행렬을 찾기 위한 경사 하강법(gradient descent) """ import numpy as np def softmax(X): """ 1) X - 1차원: [x_1, x_2, ..., x_n] 1) X - 2차원: [[x_11, x_12, ..., x_1n], [x_21, x_22, ..., x_2n], ...] """ dimension = X.ndim if dimension == 1: m = np.max(X) ...
import warnings import numpy as np import pandas as pd from scipy import stats import matplotlib.pyplot as plt import pylatex as pl class coxsum(): def __init__(self, index, params, alpha=0.05, file_nm='portec'): """This class print the s...
import os import traceback import time CGRP_CPU_LIMIT = 'RES_CPU_LIMIT' class cpuutilisation: def __init__(self, cpu_limit=None): ''' Initate the object for calculating cpu utilisation. If it fails to calculate, in any case it will return value pass while initiating the class or it...
import os, subprocess import argparse import logging def write_header(cluster=None): if cluster == 'supercloud': header = """#!/bin/bash #SBATCH -p normal #SBATCH -J uvvis_pred #SBATCH -o uvvis_pred-%j.out #SBATCH -t 1:00:00 #SBATCH -n 1 #SBATCH -N 1 #SBATCH --mem=10gb #SBATCH --gres=gpu:volta:1 echo "Dat...
# this project is licensed under the WTFPLv2, see COPYING.txt for details """Action intents Intents are generic actions triggered by plugins that are delegated to user configuration and other plugins. An example is the "`openEditor`" intent. It be triggered by an "Open" dialog (:any:`eye.widgets.filechooser`) when a...
# Copyright 2015 Google Inc. 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 law or ag...
import torch from .bbox import bbox_overlaps_cython import numpy as np from mmdet.core.bbox.transforms_rbbox import RotBox2Polys, poly2bbox, mask2poly, Tuplelist2Polylist def bbox_overlaps_cy(boxes, query_boxes): box_device = boxes.device boxes_np = boxes.cpu().numpy().astype(np.float) query_boxes_np = qu...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: zcy # @Date: 2019-02-15 13:01:05 # @Last Modified by: zcy # @Last Modified time: 2019-02-15 14:53:53 import torch import torch.nn as nn import torch.nn.functional as F from collections import OrderedDict import math __all__ = ['DenseNet'] class _DenseLa...
# -*- coding:UTF-8 -*- """ Fetching arguments in args.yaml """ import os import yaml import torch import numpy as np import pandas as pd from tqdm.auto import tqdm def fetch_args(yaml_path ): with open(yaml_path, 'r', encoding='utf-8') as f: args = f.read() args = yaml.load(args) return ar...
import asyncio import logging from functools import partial from json import JSONDecodeError import pytest from aiohttp import web, ClientSession from aiohttp.client_reqrep import ClientRequest from aiohttp.connector import TCPConnector from aiohttp.helpers import sentinel from aiohttp.test_utils import BaseTestServer...
import logging import time import bspump import bspump.common import bspump.file import bspump.trigger import bspump.analyzer import bspump.model import re import requests import numpy as np import pandas as pd import pickle import datetime import json import socket import urllib.request import pythonwhois as pw ##...
from operator import itemgetter candidateSize = 100 def initBestEnergies(combined_g2, firstTerm, candidateTerms): preBest = [] postBest = [] for candidate in candidateTerms: pre_score = 0 post_score = 0 # preBest if (candidate, firstTerm) in combined_g2: pre_scor...
from math import e, tanh from random import randint # Actual nodes stored in class variable. Nodes are then referenced with assigned IDs. def activation(x): # Activation function. return tanh(x) class BoundVar: # Creates an object that links to the value of an input node. def __init__(self, var): ...
import logging from abc import ABC, abstractmethod from pathlib import Path from typing import List import jsonrpcclient import yaml from sn_agent import SettingsBase, Required from sn_agent.job.job_descriptor import JobDescriptor from sn_agent.ontology import Service from sn_agent.utils import import_string logger ...
#------------------------------------------------------------------------------ #file global functions #------------------------------------------------------------------------------ def FCparseMatlabSequence(s): if (s.find(":") >= 0): seq = s.split(":") if (len(seq) == 2): from_ = float(seq[0]); ...
import torch import random import numpy as np from sklearn.cluster import KMeans, SpectralClustering from sklearn.metrics import silhouette_score, silhouette_samples def attention_sampling(q_input_ids, q_input_mask, q_segment_ids, knn_index): attention = knn_index.get_attention_heads(q_input_ids, q_input_mask, q_...