text
stringlengths
3.07k
22.1k
"""The instruction decoder part of the RISC-V CPU""" from baremetal import * from chips_v.utils import * def decode(instruction, src1, src2, fwd1, fwd2, fwd_val, this_pc): rs1 = instruction[19:15] rs2 = instruction[24:20] opcode = instruction[6:0] shamt = instruction[24:20] funct3 = instruction[...
import pickle import time import numpy as np import torch import tqdm from liga.models import load_data_to_gpu from liga.utils import common_utils def statistics_info(cfg, ret_dict, metric, disp_dict): for cur_thresh in cfg.MODEL.POST_PROCESSING.RECALL_THRESH_LIST: metric['recall_roi_%s' % str(cur_thres...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from .policies import * from .objects import * class BaseAgent(Object): ''' QTable: Q Table state: state of agent last_state: last state init_state: init. state ''' env = None n_steps = 0 total_reward = 0 def next_state(self, act...
import json import torch from torch.nn import functional as F from torch.utils.data import DataLoader from tqdm import tqdm from helpers.text import devectorize from helpers.training import load_checkpoint from models.translate import prior_model_from_checkpoint from modules.data.collates import Seq2SeqCollate from m...
# Copyright 2021 NVIDIA CORPORATION # SPDX-License-Identifier: Apache-2.0 # # Script to generate the GLSL compute functions # # uint autogeneratedGetCaseNumber(float sample000, float sample001, float sample010, float sample011, # float sample100, float sample101, float sample110, float s...
from imgaug import augmenters as iaa import matplotlib.pyplot as plt from itertools import cycle from scipy import interp import tensorflow as tf import itertools import numpy as np import json import argparse import warnings import os from synth.utils import datagenerate from sklearn.metrics import roc_curve, auc, a...
# convert the downscaled data archive def run( x ): ''' simple wrapper to open and return a 2-D array from a geotiff ''' import rasterio return rasterio.open(x).read(1) def sort_files( files, split_on='_', elem_month=-2, elem_year=-1 ): ''' sort a list of files properly using the month and year parsed from the...
# import XML libraries import xml.etree.ElementTree as ET import xml.dom.minidom as minidom import HTMLParser # Function to create an XML structure def make_problem_XML( problem_title='Missing title', problem_text=False, label_text='Enter your answer below.', description_text=False, answers=[{'corr...
import numpy as np, matplotlib.pyplot as plt, seaborn as sns from rdkit import Chem from dataclasses import dataclass from utils.exp import BaseArgs, BaseExpLog from utils.data import remove_processed_data import torch from torch_geometric.data import DataLoader from data.data_processors.ts_gen_processor import TSGenDa...
#!/usr/bin/env python """Script used to generate a cuboid dataset with cubes and rectangles under various shapes, rotations, translations following the general format of ShapeNet. """ import argparse import random import os from string import ascii_letters, digits import sys import numpy as np from progress.bar import...
import numpy as np import random from collections import namedtuple, deque, defaultdict import matplotlib.pyplot as plt from mdp import * import pdb import util import json import pprint import logging import utils_nn as utils BUFFER_SIZE = int(1e4) BATCH_SIZE = 1 LR = 1e-3 class ReplayBuffer: def __init__(self, bu...
""" This module defines all the user endpoints """ import re import json import requests from flask import ( jsonify, request, abort, make_response, json, Blueprint, render_template_string, url_for, redirect) from flask_jwt_extended import ( jwt_required, create_access_token, jwt_refresh_token_required, cre...
# coding: utf-8 import plugins.tools as tl import time import datetime import subprocess import shutil from slackbot.bot import respond_to from slackbot.bot import listen_to from slackbot.bot import default_reply import os import sys sys.path.append("{}/gametools".format(os.getcwd())) import ggssapi_gameresult as ggss...
# -*- coding: utf-8 -*- """Module providing stuff for plugin handling """ # import basic stuff import logging import abc import sys import argparse from typing import List, Optional, Type, Any # import own stuff import tlsmate.config as conf import tlsmate.structs as structs # import other stuff class Args(object):...
class Point3: """A point in three-dimensional space.""" def __init__(self, x=0, y=0, z=0): self.x=x self.y=y self.z=z def __repr__(self): return f"({self.x},{self.y},{self.z})" def __str__(self): return self.__repr__() def __add__(self, other...
# # Python script to get the list of virtual addresses in an Identity Pool # # _author_ = <NAME> <<EMAIL>> # # Copyright (c) 2021 Dell EMC Corporation # # 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 Li...
import argparse import datetime import netrc import os import subprocess import threading import time import typing import google.auth import googleapiclient.discovery from src.context import DataContext TIMEOUT_MULTIPLIER = 10 API = googleapiclient.discovery.build('tpu', 'v1') _, PROJECT = google.auth.default() OL...
import numpy as np import torch import torch.nn as nn from torch import Tensor from ..utils import ReverseLayerF def reparameterization(mean, log_var): std = torch.exp(0.5 * log_var) eps = torch.randn_like(std) return eps.mul(std).add_(mean) class ConvEncoder(nn.Module): def __init__(self, data_size...
# encoding: utf-8 from __future__ import division, print_function, unicode_literals ########################################################################################################### # # # Reporter Plugin # # Read the docs: # https://github.com/schriftgestalt/GlyphsSDK/tree/master/Python%20Templates/Reporter ...
from __future__ import print_function, absolute_import import argparse import os.path as osp import random import numpy as np import sys import torch.nn.functional as F from hdbscan import HDBSCAN from sklearn.cluster import KMeans, DBSCAN from sklearn.metrics.pairwise import cosine_similarity from sklearn.preprocessin...
import uuid from typing import Dict, List, Optional from hestia.datetime_typing import AwareDT from django.conf import settings from django.contrib.postgres.fields import JSONField from django.db import models from django.utils import timezone from django.utils.functional import cached_property import auditor impor...
# Test results on all possible clustering methods using clustering results import seaborn as sns import pandas as pd import numpy as np import matplotlib.pyplot as plt import torch from sklearn.metrics import silhouette_samples, silhouette_score, adjusted_rand_score from sklearn.cluster import KMeans, SpectralClusteri...
import copy from typing import Callable, Tuple import numpy as np from odyssey.distribution import Distribution from iliad.integrators.fields import softabs from iliad.integrators.info import CoupledInfo from iliad.integrators.terminal import cond from iliad.integrators.states.coupled_state import CoupledState from ...
from __future__ import absolute_import, unicode_literals import base64 import hashlib import json import logging import os import pickle import re from builtins import str import numpy as np from boto.s3.connection import Key, S3Connection from .constants import * from btb import ParamTypes from future import stan...
from collections import OrderedDict from xnmt.settings import active as settings import numpy as np import dynet as dy from xnmt.param_collection import ParamManager from xnmt.persistence import serializable_init, Serializable, bare, Ref import xnmt.optimizer from xnmt.training_task import SimpleTrainingTask class T...
from itertools import zip_longest from typing import List, Tuple, Optional, Dict, Set import requests import hashlib from .logger import logger from .constants import REPO_PATH import subprocess import shlex import tempfile import textwrap from pathlib import Path from distutils.version import Version def vercmp(v1: ...
import collections import os import random from pathlib import Path import logging import shutil from packaging import version from tqdm import tqdm import numpy as np import torch import torch.nn as nn from torch.nn.parallel import DistributedDataParallel as DDP import torch.distributed as dist import torch.multipro...
# -*- coding: utf-8 -*- """Generating a cosmological summary of the H0 or D_dt H0_samples Example ------- To run this script, pass in the version ID and the sampling method as the argument:: $ python summarize.py 21 simple_mc_default The summary will be saved to the same directory level as the sample directo...
#!/usr/bin/python ################################################################################ # "THE BEER-WARE LICENSE" (Revision 42): # # <lennartATlacerta.be> wrote this file. As long as you retain this notice you # # can do whatever you want with this stuff. If we meet som...
__copyright__ = """ Copyright 2020 Cisco Systems, 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 app...
import argparse import functools import math import sys import traceback import tkinter as tk import tkinter.messagebox from labrat.catcher import Catcher import labrat.convert as convert VERSION = [0, 1, 1] def canonicalize_int(s): try: return str(int(s)) except ValueError: return s def ...
# Copyright 2019 Inspur Corporation. 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 app...
""" Class for caching posts from a subreddit. Loads posts from file, fetches new ones when the cache is stale, and computes the scores for words found in the title @author <NAME> @version 7/19/21 """ import json import os import time import praw import config import utils from data import Post, TermGroup class Po...
from tea_block import * import math # VERIFY DIFFERENTIAL TRAIL PROBABILITIES def compute_round_differences(alpha, beta): round_differences = [[0x00000000,0x00000000] for i in range(len(alpha)+1)] # round_differences[0] = [0xFFFFFFF1, 0xFFFFFFFF] round_differences[0] = [sub(alpha[1],beta[0]), alpha[0]] ...
# implementation based on DeepLTL https://github.com/reactive-systems/deepltl from argparse import ArgumentParser import subprocess import os.path as path import sys import json import random import tensorflow as tf import numpy as np from dlsgs.utils import ltl_parser def argparser(): parser = ArgumentParser...
import numpy as np import pandas as pd import rpy2 import rpy2.robjects as ro # ro.r('library(devtools)') ## to use source_url # ro.r('library(tidyverse)') ############################## rpy2 functions ############################## # def pull(r): # return r2p(ro.globalenv[r]) # def push(py,rname=None): # im...
"""Definitions for filesystem-related [Tasks][snoop.data.models.Task]. These are the first steps in processing any dataset: walking the filesystem and recording files and directories in their respective database tables. The root directory for a dataset is explored by the [snoop.data.filesystem.walk][] [Task][snoop.da...
import abc import json import logging import queue import random from concurrent.futures.thread import ThreadPoolExecutor import websocket import threading from typing import Type from bpsenti.refinitiv.pipeline import PipelineStream from .rooms import RefiRooms from .security import TokenManagement from ..helpers.u...
import sspi, sspicon import win32api import base64 import logging logger = logging.getLogger(__name__) from flask import Response from flask import _request_ctx_stack as stack from flask import make_response from flask import request, session, g import threading from functools import wraps from socket impo...
from manimlib.imports import * import numpy as np import bats # slide scene from manim_reveal import SlideScene # manim interface with bats from manimtda import * import matplotlib from scipy.spatial import ConvexHull def gen_circle2(n, r=1.0): theta = np.linspace(0, 2*np.pi*(1 - 1./n), n) pts = np.array([r*...
import pandas as pd import numpy as np #################################################################################################################### # preprocess ACS data between 2012 to 2017 table_dict = {"total_population": {"table": "B01003", "zip": "GEO.id2", "variable":"HD01_VD01"}, ...
import sys import os import subprocess import errno print("########## Chi-Tech Dependency installer ##########") ####################################### Setting install dir cwd = os.getcwd() install_dir = cwd + "/chi-dependencies" log_str = ">>" + install_dir + "log.txt" if (len(sys.argv) == 1): print("Install dire...
# coding:utf-8 import re from .inflect import ( camelize, dasherize, humanize, ordinal, ordinalize, parameterize, pluralize, singularize, titleize, transliterate, underscore, ) def convert_keys(m, to=None, recurse=1, in_place=0): """ The main function to be used. C...
# Copyright 2018 The GamePad 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 2020 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Generates C++ code representing structured data objects from schema.org This script generates C++ objects based on a JSON+LD schema file. Blink uses the g...
#!/usr/bin/env python # This is largely adopted from https://github.com/enode-engineering/tesla-oauth2 import base64 import hashlib import os import sys import re import random import time import argparse import json from urllib.parse import parse_qs import requests MAX_ATTEMPTS = 7 CLIENT_ID = "81527cff06843c8634fd...
import matplotlib.image as mpimg import matplotlib.pyplot as plt import numpy as np import cv2 from detection_functions.feature_extraction import * from toolbox.draw_on_image import * from detection_functions.sliding_window import * # Define a function to extract features from a single image window # This function...
import dash import dash_table import dash_core_components as dcc import dash_html_components as html import dash_bootstrap_components as dbc import dash_dangerously_set_inner_html from dash.dependencies import Input, Output, State from dash.exceptions import PreventUpdate import plotly.express as px import plotly.graph...
"""Create an icosphere from convex regular polyhedron. Adapted from: https://gist.github.com/AbhilashReddyM/aed58c60438bf4c313831718013ce48f Thank you <NAME> (abhilashreddy.com)! Original authorship: Author: <NAME> (<EMAIL> where cu=columbia.edu) (github.com/wgm2111) copyright (c) 2010 liscence: BSD style Modifie...
import argparse import multiprocessing import os import sys _NUM_CPUS = multiprocessing.cpu_count() import tensorflow as tf import tqdm import datasets def _bytes_feature(value): """Returns a bytes_list from a string / byte.""" _bytes = value if not (isinstance(value, str) and sys.version_info[0] == 3) \ ...
from django.test import TestCase from django.urls import reverse from django.contrib.auth.models import User from datetime import datetime from http import HTTPStatus from .forms import CheckoutForm, CouponForm, RefundForm, PaymentForm from .models import Item, OrderItem, Address, Payment, Coupon, Order, Refund class...
# Copyright 2017 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 a...
"""Database stuff. :author: <NAME> """ import sys from datetime import datetime from pathlib import Path from typing import Any, Tuple import arrow import click from flask import Flask, current_app, g from flask.cli import with_appcontext from openpyxl import load_workbook from sqlalchemy import create_engine from sq...
from utility.constants import * from utility.amr_utils.amr import * from utility.dm_utils.DMGraph import * from utility.psd_utils.PSDGraph import * import logging score_logger = logging.getLogger("mrp.score") def list_to_mulset(l): s = dict() for i in l: if isinstance(i,AMRUniversal) and i.le == "i"an...
import os import requests import tkinter as tk from tkinter import * import threading from pytube import YouTube import pyperclip as pc import validators as vd from PIL import ImageTk, Image from io import BytesIO root = tk.Tk() root.title("Youtube Video Downloader") img = ImageTk.PhotoImage(Image.open("Assets...
#!/usr/bin/python2 """ Logical Volume Management utitltes python wrapper Written by : <NAME> Created date: 30.04.2019 Last modified: 04.05.2019 Tested with : Python 2.7 """ __version__ = "0.12" __copyright__ = "<NAME> aka Kvantum (c)2019" __all__ = ['find_lv', 'find_mount_target', 'find_mount_source', 'Logical...
import base64 import binascii import decimal import json import os import platform import sys import urllib.parse as urlparse from http.client import HTTP_PORT, HTTPConnection DEFAULT_USER_AGENT = "AuthServiceProxy/0.1" DEFAULT_HTTP_TIMEOUT = 30 # (un)hexlify to/from unicode, needed for Python3 unhexlify = binascii....
__author__ = 'ziyan.yin' __describe__ = '' from calendar import timegm from datetime import datetime from typing import Mapping import orjson from . import jwk from .exceptions import JWTError, JWTClaimsError, ExpiredSignatureError from .jws import verify, sign, load, b64decode, b64encode def encode(claims: dict, ...
import tkinter as tk import sys import os from . themes import Theme from . themes import ThemeConfig as _tcfg _THEME: _tcfg = Theme.LIGHT class Main(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) Main.configure(self, bg=_THEME.background) center_window...
""" @author: <NAME> @contact: <EMAIL> """ import argparse from ifpd import const, query from ifpd.scripts import arguments as ap # type: ignore from ifpd.exception import enable_rich_assert from joblib import Parallel, delayed # type: ignore import logging import numpy as np # type: ignore import os import pandas a...
from functools import partial from textwrap import dedent from io import StringIO import pytest import pandas.testing as pdtest import numpy import pandas from wqio.utils import misc from wqio.tests import helpers @pytest.fixture def basic_data(): testcsv = """\ Date,A,B,C,D X,1,2,3,4 Y,5,6,7,8 ...
from transformers import (AutoModelForTokenClassification, AutoModelForSequenceClassification, TrainingArguments, AutoTokenizer, AutoConfig, Trainer) from biobert_ner.utils_ner import (con...
#!/usr/bin/env python import re import logging import webapp2 import email import datetime as dt from google.appengine.ext.webapp.mail_handlers import InboundMailHandler from google.appengine.ext import db import WSF import pst import unicodedata class Alert(db.Model): body = db.TextProperty() # alert content...
''' Copyright (c) 2014 Dzakub Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublice...
from functools import lru_cache from operator import itemgetter from enum import Enum from hashlib import md5 import os from typing import TYPE_CHECKING, Union if TYPE_CHECKING: from mabed.corpus import Corpus from mabed.mabed import MABED import json import pickle import marshal import gc import time from d...
#!/usr/bin/env python3 from dataclasses import dataclass import struct import xlsxwriter from pokemon_data import Move, Type def mem_to_z64(addr): # Offset found by guess and check may vary between roms return addr - 0x3000 class CONSTANTS: class RENTAL_OFFSETS: # Source: https://datacrystal.r...
import ujson as json import sys import gzip #import seolib as seo from collections import defaultdict import argparse import os import matplotlib.pyplot as plt import numpy as np import urllib.request, re import time # a function to return a domain's rank # alexaMap dict for caching alexaMap = {} def obtainAlexa(url): ...
""" Manages a hub for easier access in UCSC genome browser """ import os from config import PUBLISH_URL_PATH_HUB, PUBLISH_DIR, TRACK_DESCRIPTION_TEMPALTE __author__ = 'eranroz' def add_track(track_name, url_name, short_label, long_label, description_html=None, genome="hg19"): """ Adds description for the new...
""" 3D Point Cloud Visualization Original Author: https://github.com/argoai/argoverse-api Modified by <NAME> Date October 2019 """ import os import numpy as np import argparse import matplotlib import matplotlib.pyplot as plt from PIL import Image from mpl_toolkits.mplot3d import Axes3D from mayavi import mlab from t...
import os.path import os import sys import math import argparse import time import random from collections import OrderedDict import torch import options.options as option from utils import util from data import create_dataloader, create_dataset from models import create_model from utils.logger import Logger, PrintLo...
import pandas as pd import numpy as np import py_entitymatching as em from .magellan_modified_feature_generation import get_features #Given a CANDIDATE SET and the list of ACTUAL duplicates (duplicates_df), #this function adds the 1/0 labels (column name = GOLD) to the candset dataframe def add_labels_to_candset(dupl...
#!/usr/bin/env python # -*- coding:utf-8 -*- # @Time : 2022/1/8 8:01 下午 # @Author: zhoumengjie # @File : BondBuilder.py class BondPage: def __init__(self): # 申购评测 self.apply_bonds = [] # 证监会核准/同意注册 self.next_bonds = [] # 已申购完,即将上市的 self.ipo_bonds = [] # 隔日...
import os import numpy as np import nilearn as nl import nilearn.plotting from math import floor import numpy as np import torch import torch.utils.data as data from torch import Tensor from typing import Optional def load_scenes(path: str) -> list: with open(path, "r") as f: result = [] for line ...
import argparse from pathlib import Path import os import sys import importlib import logging from p4z3 import Z3Reg, P4Package, z3 import p4z3.util as util sys.setrecursionlimit(15000) FILE_DIR = os.path.dirname(os.path.abspath(__file__)) log = logging.getLogger(__name__) # We maintain a list of passes that causes...
#!/usr/bin/env python3 """ Solves day 14 tasks of AoC 2020. https://adventofcode.com/2020/day/14 """ import argparse import gzip from os.path import dirname, realpath from io import StringIO from typing import List, Tuple, Set, Dict, IO, Iterator, cast from pathlib import Path from dataclasses import dataclass from r...
import re from pathlib import Path import torch import pandas as pd import numpy as np import torch from torch.utils.data import Dataset, DataLoader import sklearn.preprocessing from sklearn.preprocessing import StandardScaler from sklearn.feature_extraction.text import CountVectorizer from nltk.corpus import stopword...
from pathlib import PurePath from typing import Callable import torch import torch.nn as nn from torch.utils.data import DataLoader from labml import lab, experiment, monit, logger, tracker from labml.configs import option from labml.logger import Text from labml_helpers.datasets.text import TextDataset, SequentialDa...
from datetime import datetime, timedelta, time from flask import current_app from app.extensions import db from app.data_analysis.models import DailyOEE from app.default.models import Activity, ActivityCode, ScheduledActivity, MachineGroup from app.default.db_helpers import get_machine_activities, get_user_activities...
import os import json from decouple import config, Csv from django.shortcuts import render, redirect, get_object_or_404 from django.conf import settings from django.templatetags.static import static from django.http import HttpResponse, Http404, JsonResponse, HttpResponseRedirect from django.core.exceptions import Ob...
#! /usr/bin/env python3 import json from argparse import ArgumentParser import random # python noc_hetero_vc_gen.py -f test.json -m json VC_COUNT = 'vc_count' BUFFER_DEPTH = 'buffer_depth' NOC_X = 'noc_x' NOC_Y = 'noc_y' NUM_ROUTERS = 'num_routers' AVAILABLE_PORTS = 'available_ports' MODE_GEN_MAP = 'json' MODE_GEN_...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Code accompanying the manuscript: "Reinterpreting the relationship between number of species and number of links connects community structure and stability" ------- v1.0.0 (First release) ------- For any question or comment, please contact: <NAME>(1), <EMAIL> (1)...
import json import re import ast import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split, GridSearchCV, StratifiedKFold, cross_val_score from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, log_los...
""" Thanks to <NAME> """ from __future__ import division, print_function import sys import math import numba from numba import jit, autojit, size_t import numpy as np import numpy.testing as npt try: from skimage import img_as_float except ImportError as e: print("skimage not available, skipping") sys.exi...
# pylint: skip-file '''variants.py: A module to normalize font variants.''' import re import sys from collections import namedtuple from enum import Enum Data = namedtuple('Data', 'name, id, css, hidden') class FONT_WEIGHT(Enum): THIN = Data(name='Thin', id='100', css='100', hidden=False) EXTRALIG...
###################################################################### ###################################################################### # Copyright <NAME>, Cambridge Dialogue Systems Group, 2017 # ###################################################################### #############################################...
# -*- coding: utf-8 -*- """ Pharmacopedia.Py v1.0 Pharmacy Counting Project <NAME> DESCRIPTION Analyzes and organizes medical pharmacy data. Using data from the Centers for Medicare & Medicaid Services, this script calculates: (1) total number of prescribers and (2) total prescriber expenditure for all listed drugs....
#!/usr/bin/env python3 # # Wrappers meant for cores used in non-LiteX contexts # # Copyright (C) 2021 <NAME> <<EMAIL>> # SPDX-License-Identifier: CERN-OHL-P-2.0 # import importlib import os import pkg_resources import tempfile from migen import * from migen.genlib.cdc import MultiReg, PulseSynchronizer from migen.g...
# Copyright (c) 2021 The Trustees of the University of Pennsylvania # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, co...
import collections import numbers import torch import torch.nn.functional as F from types import SimpleNamespace as nm from .bioes import entities_jie_bioes from .viterbi import decode_bioes_logits, INFTY EPSILON = 1.e-8 def token_and_record_accuracy(logits, labels): '''Computes accuracy metric from logits and ...
# Copyright 2019 Nokia # # 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, softwa...
#!/usr/bin/env python3 # Convert HTML returned by http://tagger.jensenlab.org/ExtractPopup # into brat-flavoured standoff (http://brat.nlplab.org/standoff.html). import sys import os from collections import defaultdict from html.parser import HTMLParser from logging import warn, error EXTRACT_DATA_CONTENT_CLASS = ...
############################################################## # # ccm_unred: Deredden a flux vector using the CCM 1989 parameterization # # Cardelli_coeff: Calculate a,b and a+b/Rv for the Cardelli dust # law given a wavelength lam in angstroms # # calc_Av_from_Balmer_decrement: derive extinction using Balmer decr...
#!/usr/bin/python # Copyright (c) 2020, 2022 Oracle and/or its affiliates. # This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Apache License v2.0 # See LICENSE.TXT for d...
#!/usr/bin/env python3 """ Module to take in .mat MatLab files and generate spectrogram images via Short Time Fourier Transform ---------- ------------------------------ -------------------- | Data.mat | -> | Short-Time Fourier Transform | -> | Spectrogram Images | ...
# -*- coding: utf-8 -*- """ Created on Wed Sep 11 17:26:56 2019 @author: autol """ import re import pandas as pd #%% import dcm_util as ut from dcm_globalvar import * locals().update(var.to_dict()) # 设置读取的全局变量 #%% def df_transform_stream(df): df_x=pd.DataFrame(); df = ut.titles_trans_columns(df,titles_cn);...
import discord import asyncio import yaml import pandas as pd import urllib.request, urllib.error from xml.sax.saxutils import unescape from bs4 import BeautifulSoup client = discord.Client() @client.event async def on_ready(): print('Logged in as' + client.user.name) print(client.user.id) print('------')...
""" This module contains auxiliary functions to plot some information on the RESTUD economy. """ # standard library import matplotlib.pylab as plt import numpy as np import shutil import shlex import os from mpl_toolkits.mplot3d import Axes3D from matplotlib.ticker import FuncFormatter from matplotlib import cm # Ev...
# -*- coding: utf-8 -*- from functools import partial from datetime import datetime from kivy.uix.floatlayout import FloatLayout from kivy.uix.screenmanager import Screen from kivy.uix.dropdown import DropDown from kivy.uix.boxlayout import BoxLayout from kivy.uix.relativelayout import RelativeLayout from kivy.uix.l...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** 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...
import argparse import numpy as np from pyimzml.ImzMLWriter import ImzMLWriter from pyImagingMSpec.inMemoryIMS import inMemoryIMS from scipy.optimize import least_squares from pyimzml.ImzMLParser import ImzMLParser from pyimzml.ImzMLWriter import ImzMLWriter from scipy.signal import medfilt2d import logging def fit_fu...