text stringlengths 3.07k 22.1k |
|---|
# TODO check for transfer learning: https://thebinarynotes.com/how-to-train-mask-r-cnn-on-the-custom-dataset/
# Source: https://github.com/miki998/Custom_Train_MaskRCNN/blob/master/train.py
import json
import cv2
import os
import numpy as np
# Import Mask RCNN
from mrcnn.config import Config
from mrcnn import model as... |
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 29 13:42:23 2019
@author: garci
"""
import random as ran
import numpy as np
import matplotlib.pyplot as plt
'''montemarathon.py - acceptance-rejection sampling example:
marathon race
<NAME>, 2019'''
'bad runners - probabilities for injuries / exhaustion high '
probs_... |
import math
from typing import Any, Iterable, List, Mapping, Optional, Tuple, Union, cast
import affine
import numpy as np
from datacube.utils.geometry import CRS, GeoBox, polygon
from datacube_ows.config_utils import CFG_DICT, RAW_CFG, OWSConfigEntry
from datacube_ows.ogc_utils import ConfigException, create_geobox
... |
# 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... |
'''****************************************************************************
* Hexnet.py: Hexnet Base System Wrapper
******************************************************************************
* v0.1 - 01.03.2019
*
* Copyright (c) 2019 <NAME> (<EMAIL>)
*
* Permission is hereby granted, free of charge, to a... |
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 4 10:44:25 2019
@author: vjha1
"""
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import interp1d
#from scipy import signal
from scipy.signal import find_peaks
import time
#import operator
def __abs__(self):
return (self.x... |
# Copyright 2018 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... |
# by using the data in the several JSON files about each review and revision,
# this script extracts the discussion of each revision and writes it in a separate text file for easy access
# each revision generates a discussion file which contains the description of that revision and the discussion/comments by the develo... |
"""
Code for building neural network models.
"""
import inspect
import re
import torch
from torch import nn
import torch.nn.functional
from torch.autograd import Variable
from torch.utils import model_zoo
from torchvision import models
import dsnt.nn
from dsnt.nn import euclidean_loss, thresholded_softmax
from dsnt ... |
# -*- encoding: utf8-*-
from flask import Flask, Blueprint
from flask.helpers import send_file, send_from_directory
from flask_restful import Api, Resource, request, reqparse
from werkzeug import exceptions
import model
import err
import entities
import csv
app = Flask(__name__)
api_bp = Blueprint("scores", __name__, ... |
import json
import pandas as pd
class Table:
"""
Instantiates a Table object which houses information about each table/df
:param table: (pandas DataFrame) - df/table you want to add to the diagram
:param table_name: (str) Name of the table
"""
def __init__(self, table, table_name, **kwargs):
... |
# -*- coding: utf-8 -*-
from collections import defaultdict
from functools import reduce
from operator import mul
try:
import numpy as np
except ImportError:
np = None
import pytest
from chempy import ReactionSystem
from chempy.units import (
allclose,
logspace_from_lin,
unitless_in_registry,
... |
import speech_recognition as sr
from gtts import gTTS
import pyglet
from chatterbot import ChatBot
import webbrowser as wb
#System imports
import random
import time, os
from time import ctime
import sys
import subprocess
import win32con
import win32gui
sys.path.append(r'..\Travis\Typedefs')
#Custom imports
import pat... |
import torch.optim as optim
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
import torchvision
import torchvision.transforms as transforms
import os
import time
import argparse
from models import *
from utils import progress_bar
# 1.添加参数 - -local_rank
# 每个进程分配一个 local_rank 参数,表示当前进程在当前主机上的编号。
#... |
#!/usr/bin/env python3
'''
Trains a Pytorch classifier on the images in the images directory.
The class labels are the names of the subdirectories.
'''
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision
import torchvision.transforms as transform... |
"""
Greynir: Natural language processing for Icelandic
Wrapper functions module
Copyright (C) 2021 <NAME>.
This software is licensed under the MIT License:
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
... |
# Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
"""
Example: Modelling mortality over space and time
================================================
This example is adapted from [1]. The model in the paper estimates death rates for 6791 small
areas in England for 19 age groups (0,... |
import datetime
import html
import json
import os
import traceback
from typing import Optional
from urllib.parse import urlencode
from cachetools import TTLCache
from discord import Color, Embed, Forbidden, Member
from discord.ext import commands, flags, tasks
from jose import jwt
from bot.utils import fuzzy
from con... |
"""
High level parser that processes a token stream to produce clauses and actions.
The parser structure is a recursive descent parser with look ahead N through an
unlimited pushback buffer.
"""
import functools
import io
import judged
from judged import tokenizer
from judged.tokens import *
from judged import world... |
import inspect
import re
import Session7 as pxt
import os
import pytest
import random
README_CONTENT_CHECK_FOR = [
'Fibonacci',
'vowels',
'list',
'lambda',
'zip',
'tuple',
'detox',
'reduce',
'sigmoid',
'Cipher',
'number plate',
'ReLU'
]
def test_function_name_had_cap_let... |
import mxnet as mx
import numpy as np
from importlib import import_module
from easydict import EasyDict as edict
cfg = edict()
cfg.bn_use_global_stats = True
cfg.bn_use_sync = False
cfg.bn_eps = 2e-5
cfg.absorb_bn = False
cfg.workspace = 512
cfg.lr_type = ''
cfg.param_attr = None
def get_sym_func(func_name):
part... |
from __future__ import annotations
from itertools import chain
from puzzle_input import puzzle_input
import re
from typing import Generator, Iterable, Literal, NamedTuple, Set
class Int3(NamedTuple):
x: int
y: int
z: int
def clamp(self, minv: Int3 | None, maxv: Int3 | None) -> Int3:
x, y, z ... |
import os
import glob
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import config
from util import *
from data_retrieval import *
repo_lang = Repository_language()
data_ret = Data_Retreival()
os.system('mkdir -p {}'.format(config.PREDICTION_RES_PATH))
metric_list = ['precision_score_not_c... |
#! /usr/bin/env python3
from enum import Enum
#from numba import jit
from random import choice, randrange, shuffle
from itertools import accumulate, chain, permutations
from math import factorial
from section_type import SectionType, short_section, long_section, INTRO, VERSE, PRE, CHORUS, BRIDGE, OUTRO
f... |
from __future__ import print_function
from memories.DMC_query import DynamicMemoryCell
import numpy as np
import tensorflow as tf
from tflearn.activations import sigmoid, softmax
from functools import partial
import logging
class EntityNetwork():
def __init__(self, vocab_size, sent_len, sent_numb, num_blocks, emb... |
#!/usr/bin/env python3
# MIT License
#
# Copyright (c) 2020, <NAME>
#
# 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... |
import urllib
from io import BytesIO
import json
import os
import uuid
import logging
import boto3
from flask import Flask, request, Response, jsonify, render_template
from google.cloud import storage
from PIL import Image, ImageDraw
import requests
from twilio.twiml.messaging_response import MessagingResponse
from tw... |
import math
import pandas as pd
def calculate_entropy(zeros_count, ones_count):
if zeros_count == 0 or ones_count == 0:
return 0
if heuristic_val.lower() == "h1":
value_one = ones_count/(ones_count+zeros_count)
value_zero = zeros_count/(ones_count+zeros_count)
if value_one !... |
"""
A few validation problems to make sure the smoothers are working as expected.
These depend on the supsmu module, which was created using f2py from Breiman's supsmu.f
"""
import matplotlib.pyplot as plt
import numpy
from ace.samples import smoother_friedman82
import ace.smoother as smoother
import ace.supersmooth... |
# -*- coding: utf-8 -*-
import datetime
import os
import re
import sys
import pytest
import jinja2
from lektor.environment import PRIMARY_ALT
from lektor.reporter import BufferReporter
from lektor.types import RawValue
from lektor_git_timestamp import (
run_git,
_fs_mtime,
_is_dirty,
_iter_timestamps... |
# Copyright 2017 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... |
#import shell modules
import os
import os.path
import sys
from subprocess import Popen
#set proper path for modules
sys.path.append('/home/pi/oasis-grow')
sys.path.append('/home/pi/oasis-grow/utils')
sys.path.append('/usr/lib/python37.zip')
sys.path.append('/usr/lib/python3.7')
sys.path.append('/usr/lib/python3.7/lib-... |
import argparse
import logging
import subprocess
import os
import re
from tempfile import NamedTemporaryFile
from lxml import etree
from .exceptions import SysException
logger = logging.getLogger(__name__)
def cmd_parser():
parser = argparse.ArgumentParser(description='Replicate a MySQL database to MongoDB')
... |
"""2D & 3D vector classes"""
from __future__ import annotations
import itertools
import math
from typing import Iterable, Union
class vec2:
"""2D vector class"""
__slots__ = ["x", "y"]
x: float
y: float
def __init__(self, x: float = 0, y: float = 0):
self.x, self.y = x, y
def __abs_... |
# Copyright 2018 Xanadu Quantum Technologies Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agre... |
import io
import os
import json
import sqlite3
import functools
import pandas as pd
from flask import (Flask, g, render_template, flash, redirect, url_for, abort, jsonify, request, session)
from flask_cors import CORS, cross_origin
######################################################################################... |
import argparse
import logging
import os
import shutil
from argparse import Namespace
from functools import partial
from pathlib import Path
from typing import Callable
from typing import Union
import torch
from torch.optim.optimizer import Optimizer
from torch.utils.data import DataLoader
from torch.utils.tensorboard... |
#
# Copyright BrainPad Inc. All Rights Reserved.
#
# 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, ... |
import gzip as gz
import sys, os
import argparse
import functools
import numpy as np
import pandas as pd
import warnings
import torch
import pickle
from roost_message import LoadFeaturiser
from torch.utils.data import Dataset, DataLoader
def build_dataset_prepare(data,
target_property='e_ab... |
#! /usr/bin/python
# -*- coding: utf8 -*-
import os
import time
import random
import numpy as np
import scipy, multiprocessing
import tensorflow as tf
import tensorlayer as tl
from model import get_G, get_D
from config import config
import tifffile
import json
from skimage import metrics
## Adam
batch_size = config.T... |
from functools import wraps
from importlib.util import find_spec
from typing import Optional, List, Union
import click
import pandas as pd
from pandas_genomics import GenotypeDtype
def print_wrap(func):
@wraps(func)
def wrapped(*args, **kwargs):
click.echo("=" * 80)
click.echo(f"Running {func... |
# Copyright 2018 The Hypebot 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 (c) 2022 <NAME>
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from typing import Any, Optional
import json
from ..primitive import JSON
from ..util impo... |
#!/usr/bin/env python
import numpy;
import sptensor;
import tools;
class tensor:
data = None;
shape = None;
def __init__(self, data, shape = None):
"""Constructor for tensor object.
dat can be numpy.array or list.
shape can be numpy.array, list, tuple of integers"""
... |
import json
from datetime import datetime
from flask import render_template, Blueprint, current_app, redirect
from flask.helpers import url_for
from flask import request
from application.datasette import (
get_monthly_counts,
publisher_counts,
publisher_coverage,
active_resources,
sources_by_datas... |
import os
import ged_lib as gl
class persons_class(object):
def __init__(self, individual_id=None, name=None, birth_year=None, more=None, link=None):
self.individual_id = individual_id
self.name = name
self.birth_year = birth_year
self.more = more
self.link = link
... |
"""
Using this script, you can create your own NST & ISS simulations. The default parameters will produce a high-quality
A4 Painting of Sydney's Opera house painted in smART's style. The ABB RAPID code for our robot is also exported, but
you can find the simulated painting (from ISS) and the style transferred image (fr... |
import os
import requests
import json
import time
from notifier.sms import TwilioSMS
from decouple import config
import logging
class Base(object):
"""Base class to access account, and facilitate inheritance of the subclasses
"""
# TODO test if this base class is still required?
def __init__(self, **... |
"""Field class.
"""
__author__ = '<NAME> <<EMAIL>>'
__copyright__ = 'Copyright © <NAME> <https://github.com/neurobin/>'
__license__ = '[BSD](http://www.opensource.org/licenses/bsd-license.php)'
__version__ = '0.0.1'
import copy
from typing import Any, Optional, Callable, Tuple, Dict, List, Union
from morm.types impor... |
import tensorflow as tf
import tensorflow_probability as tfp
import unittest
from baconian.core.core import EnvSpec
import numpy as np
from baconian.envs.gym_env import make
from baconian.common.special import *
from baconian.test.tests.set_up.setup import TestTensorflowSetup
import baconian.algo.distribution.mvn as mv... |
from scipy.signal import medfilt
import numpy as np
import matplotlib.pyplot as plt
from types import SimpleNamespace
def clip_outliers(x, y, yerr = None, clip=5, width=15, verbose=True, return_clipped_indices = False):
"""
Remove outliers using a running median method. Points > clip*M.A.D are removed
whe... |
import discord
import discord.game
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio
import time
from itertools import cycle
import youtube_dl
import json
import os
import sys
Client = discord.Client()
client = commands.Bot(command_prefix = "bob.")
client.remove_command('help')
os.ch... |
from sys import exit, stderr
import numpy as np
import mpmath as mp
from scipy.optimize import newton, minimize
import hde_utils as utl
def d_xi(beta, K):
"""
First derivative of xi(beta).
xi(beta) is the entropy of the system when no data has been observed.
d_xi is the prior for the nsb estimator
... |
from typing import List
from lark import Lark, Transformer
class SimaiTransformer(Transformer):
def title(self, n):
n = n[0]
return {"type": "title", "value": n.rstrip()}
def artist(self, n):
n = n[0]
return {"type": "artist", "value": n.rstrip()}
def smsg(self, n):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
变量的过滤条件
"""
import json
import re
from collections import OrderedDict
from .util import utf8, text
from value_type import is_value_type_supported
class Filter(object):
def __init__(self, source, object, object_type, object_subtype, operation, value, type, para... |
from ScriptingBridge import SBApplication, SBObject
import weakref
import struct
import shlex
import subprocess
import objc
from contextlib import contextmanager
from enum import Enum
from typing import Mapping
from typing import List, Optional, Generator
from collections import namedtuple
SIZE = namedtuple('Size', ('... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 10 11:14:55 2017
Solving the nuclear wavepacket dynamics on 1D adiabatic potential energy surface.
@author: <NAME>
History:
2/12/18 : fix a bug with the FFT frequency
Possible improvements:
1. use pyFFTW to replace the Scipy
"""
import nu... |
"""
This file is intended as a library of tensor operations and vectorized
operations written in PySEAL.
"""
#TODO multiplication in pyseal won't allow values to be zero. make sure all 0's are epsilon
import streamlit as st
import seal
import numpy as np
from copy import deepcopy as dc
from seal import ChooserEvalu... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# debinsight/debinsight.py
#
# debinsight algorithm
#
# This file is part of debinsight.
# See the LICENSE file for the software license.
# (C) Copyright 2019, <NAME>, <EMAIL>
# -------------------------------... |
"""Tests for metrics."""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import itertools
import os
import numpy as np
from numpy.testing import (assert_almost_equal, assert_equal,
assert_raises_regex)
from scor... |
"""
A module to contain all the functions that parse command line arguments, and their error classes.
"""
from typing import Dict, NoReturn, Optional
import logging
from wheatley.aliases import CallDef, JSON
from wheatley.row_generation import RowGenerator
from wheatley.row_generation.place_notation_generator import ... |
import numpy as np
import sys
import torch
import scipy.stats as stats
import copy
def pred_singlemodel(ReasonerObj, args):
"""A Python re-writing of part of the procedure followed in
https://github.com/andyzeng/arc-robot-vision/image-matching/evaluateModel.m"
"""
#Find NN based on the embeddings of a ... |
import os, sys
import argparse
import numpy as np
import h5py
from text_utils import TextEncoder # This is my version
#sys.path.append('pytorch-openai-transformer-lm')
import csv
# Needed for BPE stuff
pretrained_model_path = os.path.join('.', 'finetune-transformer-lm', 'model')
# Needed for the train/dev/test f... |
import pandas as pd
import numpy as np
import sys
class Stmt:
def __init__(self, start_line, start_char, end_line, end_char):
self.start_line = start_line
self.start_char = start_char
self.end_line = end_line
self.end_char = end_char
def __str__(self):
return("[" + str(self.start_line) + ", " + str(self.... |
from __future__ import annotations
import pygame
from typing import Optional
class Actor:
"""
A class to represent all the game's actors. This class includes any
attributes/methods that every actor in the game must have.
This is an abstract class. Only subclasses should be instantiated.
=== Publ... |
# 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 ... |
"""Code parsing and data extraction utilies.
This module exposes a public function, [`visit()`][griffe.visitor.visit],
which parses the module code using [`parse()`][parse],
and returns a new [`Module`][griffe.dataclasses.Module] instance,
populating its members recursively, by using a custom [`NodeVisitor`][ast.NodeV... |
"""Implement Regular Expression with vm
Basic ideas borrowed mainly from https://swtch.com/~rsc/regexp/regexp2.html
"""
from typing import Iterator, List, Optional
from ..parse_tree import PTNode
from ..pattern import Finder as BaseFinder, Pattern
from ..env import DEBUG
from .program import (
Instruction,
... |
from merkato.merkato_config import load_config, get_config, create_exchange
from merkato.merkato import Merkato
from merkato.parser import parse
from merkato.utils.database_utils import no_merkatos_table_exists, create_merkatos_table, insert_merkato, get_all_merkatos, get_exchange, no_exchanges_table_exists, create_exc... |
import base64
import json
import time
import sys
import cStringIO
from docopt import docopt
from localstack.utils import testutil
from localstack.utils.common import *
from localstack.config import HOSTNAME, PORT_SQS
from localstack.constants import ENV_DEV, LAMBDA_TEST_ROLE, TEST_AWS_ACCOUNT_ID
from localstack.mock im... |
"""
Original script: demo_ZND_CJ_cell.m found at
http://shepherd.caltech.edu/EDL/PublicResources/sdt/nb/sdt_intro.slides.html
Modified for python by <NAME>
<EMAIL>
Shock and Detonation Toolbox Demo Program
Computes ZND and CV models of detonation with the shock front
traveling at the CJ speed. Evaluates various mea... |
import time, uos
from utime import sleep_ms
from usys import path as syspath
from machine import Pin, SPI
_BAUD = const(0x500000) #5 Mb ~ can be overwritten in SDCard constructor
_NOCONN_WARN = 'SD Card Not Initialized'
_NODTCT_WARN = 'SD Card Not Detected'
class SDCard(object):
@property
def drive(se... |
# This file is part of pdar.
#
# Copyright 2011 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
# Copyright (c) 2020, <NAME>, Honda Research Institute Europe GmbH, and
# Technical University of Darmstadt.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code mus... |
# Original Code from this page copied from the Home Assistant project
# https://github.com/home-assistant/home-assistant/blob/678f284015a2c52f96a7687979cfd9f785e4527a/homeassistant/util/yaml.py
#
# Additions by <NAME>
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may n... |
import requests
import json
import os
import hashlib
import smtplib
import email
from apscheduler.schedulers.blocking import BlockingScheduler
import time
# 登录
def login():
global headers
global Token
headers['Host'] = "apps.ulearning.cn"
#用户名
username = ""
# 密码
password = ""
login_url ... |
import numpy as np
def overlap(x1, len1, x2, len2):
len1_half = len1/2
len2_half = len2/2
left = max(x1 - len1_half, x2 - len2_half)
right = min(x1 + len1_half, x2 + len2_half)
return right - left
def box_intersection(a, b):
w = overlap(a.x, a.w, b.x, b.w)
h = overlap(a.y, a.h, b.y, b.h)
... |
"""
TODO(AJC): things for me to add in the future.
- sin, cos, log, max, min, others?
"""
from __future__ import annotations
from copy import deepcopy
from .list2d import List2D
def full(nrow: int, ncol: int, val: float, children: tuple = ()) -> Matrix:
"""Create a matrix of given size using the fill value.
... |
# LOCAL DEPENDENCIES print(airplane.passengers)
from utilities import *
from constants import *
# EXTERNAL DEPENDENCIES
from scipy import *
import sys
################################################################################
class Mission:
segments = None
cruiseRange = None
def simul... |
from __future__ import print_function
from __future__ import division
import os
import numpy as np
import collections
import json
import h5py
import random
from tqdm import tqdm
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
import framework.configbase
import f... |
from collections import Counter
from os.path import dirname, exists
from os import path, makedirs
from sklearn.model_selection import train_test_split
from time import strftime, localtime
import bz2
import copy
import numpy as np
import pickle
import random
from keras.callbacks import ModelCheckpoint
from keras.layer... |
# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
#
# 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://w... |
# -*- coding=utf-8 -*-
#try:
import xlrd
from xlwt import Workbook, Worksheet, easyxf
import time
from os import path, mkdir
import traceback
from xlutils.copy import copy
#except Exception as e:
# print('\033[1;31;0m' + "[Import Error]:" + '\033[0m' + " The imported modules are not exist: " + str(e))
# 读写Excel封装
... |
import json
import random
import numpy as np
import pickle
import os
import torch
import torch.utils.data as Data
from itertools import chain
import more_itertools as mit
from functools import reduce
ADE_root = 'data/ADE'
ADE_data = os.path.join(ADE_root, 'DRUG-AE.rel')
def readfile(data):
with open(data, "r"... |
from . import field_parser as fp
from . import parser_organisation
from . import alchemy_tables
from . import create_session
from .bug_report import add_error
class UploadStatusTyper(fp.Parser):
""" Simple class for handling 2D keys for status typer """
def __init__(self, key_store):
table_class = alc... |
from graphviz import Digraph
import theme
import util
import os
from pathlib import Path
import datamap
import leetcode
from svgpathtools import svg2paths
from bs4 import BeautifulSoup
svg_icon_finish = '''
<g transform="translate(%s, %s) scale(0.3)">
<circle fill="#4caf50" cx="24" cy="24" r="21"/>
<polygon fill="... |
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Program Purposes:
# (1) Home the robot
# (2) Get multiple poses from the dobot magician arm using the button on the arm
# (3) Display alarms
# (4) Clear alarms
# Initial Author: <NAME> (<EMAIL>)
# (note anyone is welcome to contribute, intial author ... |
# -*- coding: utf-8 -*-
# Copyright: <NAME> <<EMAIL>>
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import os
import copy
import re
from anki.lang import _
from anki.utils import intTime, json
from anki.db import DB
from anki.collection import _Collection
from anki.consts import *
fro... |
import logging
import random
import pytest
from piqe_ocp_lib import __loggername__
from piqe_ocp_lib.api.resources import OcpLimitRanges
logger = logging.getLogger(__loggername__)
five_digit_number = "".join(random.sample("0123456789", 5))
NAMESPACE = "default"
NAME = f"test{five_digit_number}"
@pytest.fixture(sc... |
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib import cm
from genepy.epigenetics import chipseq as chip
from genepy.utils import helper as h
def plotAverageOfSamples(samples, folder="", showAll=False, maxv=None, minv=None):
res = []
plt.figure()
plt.... |
import os
import numpy as np
import pandas as pd
import fiona
import geopandas as gpd
# Enable fiona driver
gpd.io.file.fiona.drvsupport.supported_drivers['KML'] = 'rw'
import glob
import subprocess
from multiprocessing import Pool
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rcParams.update({'font.s... |
"""Implementation of org.mpris.MediaPlayer2.Player interface.
https://specifications.freedesktop.org/mpris-spec/2.2/Player_Interface.html
"""
import logging
from gi.repository.GLib import Variant
from pydbus.generic import signal
from mopidy.core import PlaybackState
from mopidy_mpris.interface import Interface
l... |
'''
File to define inference and BLEU evaluation method of NIC,
including how to generate captions by given image use greedy or beam search,
based on the paper:
https://www.cv-foundation.org/openaccess/content_cvpr_2015/papers/Vinyals_Show_and_Tell_2015_CVPR_paper.pdf
'''
import math
import os
impor... |
from typing import Tuple, List, Union
import numpy as np
import torch
from scipy import stats
from torch import Tensor
from torch.nn import Module
from torch_geometric.data.storage import recursive_apply
from torch_geometric.typing import OptTensor
import tsl
from tsl.typing import TensArray
__all__ = [
'Scaler'... |
from __future__ import print_function
from __future__ import absolute_import
from tests.test_base import *
from qgate.script import *
from qgate.model.gate_type import U
import numpy as np
import math
import cmath
def gate_mat(gate) :
# FIXME: Remove from test.
mat = gate.gate_type.pymat()
if gate.adjoin... |
import tensorflow as tf
import numpy as np
import sys
from CatmullRom import *
# Tensorflow config
tf_config = tf.ConfigProto()
tf_config.gpu_options.allow_growth = True
# Config
EPOCH = 20
BATCH_SIZE = 32
DATASET_PATH = "./data/myown/test/"
LEARNING_RATE = 0.0001
BETA_1 = 0.9
BETA_2 = 0.999
EPSILON =... |
from opymize import Variable, LinOp
from opymize.linear.sparse import diffopn, lplcnopn
import numpy as np
try:
import opymize.tools.gpu
from pkg_resources import resource_stream
from opymize.tools.gpu import prepare_kernels
except:
# no cuda support
pass
def imagedim_skips(imagedims):
ndims... |
##############################################################################
#
# Copyright (c) 2005 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOF... |
'''
Results video generator Udacity Challenge 2
Original By: <NAME>: <NAME>
'''
from __future__ import print_function
import argparse
import sys
import numpy as np
import h5py
import pygame
import json
import pandas as pd
from os import path
#from keras.models import model_from_json
import time
imp... |
import sys
import os
import torch
import torch.autograd as autograd
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
import pickle
from data import POSdata, TorchData
from models import SequenceTagger
from text_classifier_torch.t2i import T2I as text_vectorizer
from... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.