text stringlengths 8.04k 46.5k |
|---|
# -*- coding: utf-8 -*-
from numpy import median
import numpy as np
import sys
import importlib
importlib.reload(sys)
characters = ["age", "type_employer", "fnlwgt", "education", "education_num", "marital", "occupation", "relationship",
"race", "sex", "capital_gain", "capital_loss", "hr_peer_we... |
"""
Tensorflow SMPL implementation as batch.
Specify joint types:
'coco': Returns COCO+ 19 joints
'lsp': Returns H3.6M-LSP 14 joints
Note: To get original smpl joints, use self.J_transformed
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy ... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import src.training_utils as training_utils
import numpy as np
from flair.training_utils import store_embeddings
from .data import TagSequence
import src.utils as utils
START_TAG = '<START>'
STOP_TAG = '<STOP>'
class BaseModel(nn.Module):
def __in... |
# Copyright 2018 The Cirq Developers
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
from pgvbotLib import *
import pywikibot
from copy import deepcopy
#from sys import argv
import re, sys, os
from pywikibot.exceptions import NoPageError
from arywikibotlib import isHuman, hasPropertyXValue
RECENT_LOG_FILE = "recent_log.txt"
def load_pages_in_log():
if not os.path.exists(RECENT_LOG_FILE):
... |
"""
A module for layer classes for strided operations with feature maps. These can be used for supervised
and unsupervsed learning. For classical convolutional networks, the classes ConvLayer and PoolLayer
will be most useful here.
`Filter' nomenclatures:
`window' - size of kernel within each feature map
`kernel' ... |
import scipy
import warnings
import numpy as np
import matplotlib.pyplot as plt
from spafe.utils.converters import (hz2bark, bark2hz, hz2mel, mel2hz, fft2barkmx, fft2melmx)
NFFT = 512
def cqt(sig, fs=16000, low_freq=10, high_freq=3000, b=48):
"""
Compute the constant Q-transform.
- take the absol... |
#!/usr/bin/env python
# Copyright (c) 2020 Arista Networks, Inc. All rights reserved.
# Arista Networks, Inc. Confidential and Proprietary.
'''
TCPCheck Utility
The purpose of this utility is to test HTTP/HTTPS reachability, alert if its down and
run a config change. On recovery run another list of config changes.
A... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 27 17:44:49 2020
@author: sergeykoldobskiy
"""
import numpy as np
import warnings
warnings.filterwarnings("ignore", message="divide by zero encountered in")
warnings.filterwarnings("ignore", message="invalid value encountered in")
warnings.filterw... |
# -*- coding: utf-8 -*-
from .helpers import EPSILON
from .song import Song
import dj_feet.feedback
from collections import defaultdict
import os
import random
import librosa
import numpy
from sklearn.decomposition import PCA
from copy import copy
import scipy
import logging
l = logging.getLogger(__name__)
class Pi... |
import unittest
import gzip
import json
from webfront.tests.InterproRESTTestCase import InterproRESTTestCase
from rest_framework import status
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
class GroupByModifierTest(InterproRESTTestCase):
def test_can_get_the_entry_type_groups(self... |
import warnings
from contextlib import contextmanager
from decimal import Decimal
import webcolors
from . import BaseRenderer, renders
from ..operations import (BaseList, Bold, BulletList, CodeBlock, Footnote,
Format, Group, Heading, HyperLink, Image, InlineCode,
It... |
# Copyright 2015 Brocade Communications System, 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
#
#... |
from __future__ import print_function
import numpy as np
import os
import tensorflow as tf
from tensorflow.contrib import rnn
import tensorflow.contrib as tf_contrib
import json
import pprint
import utils
import base_model
def variable_summaries(var):
"""Attach a lot of summaries to a Tensor (for TensorBoard visuali... |
# -*- coding: utf-8 -*-
# Copyright 2017 Kakao, Recommendation Team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by a... |
import numpy as np
import math
import sys
import pickle
def Coord2Pixels(lat, lon, min_lat, min_lon, max_lat, max_lon, sizex, sizey):
#print(max_lat, min_lat, sizex)
ilat = sizex - int((lat-min_lat) / ((max_lat - min_lat)/sizex))
#ilat = int((lat-min_lat) / ((max_lat - min_lat)/sizex))
ilon = int((lon... |
import datetime
import io
import math
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple, Union
import attr
import numpy
import pandas
from .data_model import (
Comment,
FileRecordIndex,
History,
PingHeader,
PingSpatialBounds,
PingTimestampBounds,
SwathBathymetryS... |
# Copyright 2015 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 collections
import datetime
import json
import os
import random
import re
import globals
from crawlers.bestdori import CardTable, EventTable, GachaTable
from nonebot.adapters.cqhttp import Message, MessageSegment
from utils import ImageProcesser
from utils.Asset import ImageAsset
class Card:
def __init__... |
import math
import random
import torch
__all__ = [
'fbank',
'get_mel_banks',
'inverse_mel_scale',
'inverse_mel_scale_scalar',
'mel_scale',
'mel_scale_scalar',
'spectrogram',
'vtln_warp_freq',
'vtln_warp_mel_freq',
]
# numeric_limits<float>::epsilon() 1.1920928955078125e-07
EPSILON... |
from datetime import datetime, timedelta
import json
from pathlib import Path
import time
import unittest
import pytube
from datatube import DATATUBE_VERSION_NUMBER, ROOT_DIR, VIDEO_DIR
import datatube.check as check
from datatube.youtube import Channel, Video, video_id_to_url
TEST_VIDEO_ID = "dQw4w9WgXcQ"
TEST_CHA... |
'''
Do some forced-photometry simulations to look at how errors in
astrometry affect the results. Can we do anything with forced
photometry to measure astrometric offsets? (photometer PSF + its
derivatives?)
'''
from __future__ import print_function
import sys
import os
import numpy as np
import pylab as plt
import fi... |
#
# SoftPixelMesh Exporter 1.1.3 for Blender 2.63 - (21/09/2011)
# Copyright (c) 2011 by <NAME>
#
# === Contributors: ===
# - "Mikey" (SoftPixel Forum Member) -> extended the script for Blender 2.63 to work with 'tessfaces'
#
# === Updates: ===
# v.1.1.1:
# - Updated support for Blender 2.6
#
# v.1.1.2:
# - Bug ... |
import base64
import datetime
import copy
import logging
from django.conf import settings
from django.contrib.auth import logout, login as auth_login
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.views import LoginView
from django.core.exceptions import (ImproperlyConfigured,
... |
# ============================================================================================
# PROGRAMA : TorreHanoi2.0.py
# AUTOR : QED
#
# DESCRIPCION: Mi sexto programa. Aprendiendo a programar.
# Con 3 columnas (a,b y c) con una torre de discos en a, todos los discos
#
# Reglas : 1- solo s... |
#!/usr/bin/env python3
import struct, sys, argparse, os, subprocess
argparser = argparse.ArgumentParser(description="generate wasm module for bug")
argparser.add_argument("-fast", action="store_true", help="for patched jsc, dont emit the 32gb stuff")
argparser.add_argument("-stkchk", action="store_true", help="emit mo... |
# Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Factories that create entities."""
# pylint: disable=too-many-arguments
# pylint: disable=invalid-name
# pylint: disable=redefined-builtin
import copy
import random
from lib.constants import element, obj... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""soundlooper - Manage loop sounds for StarCraft: Remastered."""
import codecs
import io
import os
import random
import string
import struct
from io import BytesIO
from math import ceil, floor
from eudplib import *
# tinytag - an audio meta info reader
# Copyright (c) 2... |
# !/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 16 13:34:51 2019
@author: jaime
#"""
import h5py as h5
from circle_fit import least_squares_circle
import pandas as pd
import re as re
from sys import platform
import numpy as np
import os
cmy = 365 * 24 * 60 * 60. * 100
class UserChoice(Excepti... |
"""
Routes and views for the flask application.
"""
from datetime import datetime, timedelta, date
from dateutil import parser
from flask import Flask, render_template, redirect, url_for, flash, request, jsonify
from flask_cors import CORS
import requests
import json
import uuid
import pandas as pd
from timer import T... |
# coding: utf8
"""
ref
1. http://disi.unitn.it/moschitti/Tree-Kernel.htm
2. http://disi.unitn.it/moschitti/Teaching-slides/slides-AINLP-2016/SVMs-Kernel-Methods.pdf
3. code: http://joedsm.altervista.org/pythontreekernels.htm
4. wiki: https://en.wikipedia.org/wiki/Tree_kernel
"""
from __future__ import print_function
im... |
import sys
import re
from enum import Enum
from alnitak import prog as Prog
from alnitak import exceptions as Except
from alnitak import config
from alnitak import datafile
from alnitak import printrecord
from alnitak import dane
from alnitak import logging
def print_check(prog, pos, flag_name, input):
"""Pars... |
import re
import datetime
import numpy as np
import pytest
# NOTE:
# DO NOT make relative imports here (else import cleanup wont work)
# WRONG: import core
# RIGHT: from timple import core
def test_strftimedelta():
import timple.timedelta as tmpldelta
cases = [
(datetime.timedelta(days=1), "%d %day... |
# -*- coding: utf-8 -*-
# Copyright (C) 2020-2021 by SCICO Developers
# All rights reserved. BSD 3-clause License.
# This file is part of the SCICO package. Details of the copyright and
# user license can be found in the 'LICENSE' file distributed with the
# package.
"""ADMM solver and auxiliary classes."""
from func... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
# <NAME> 07/25/21
# Import statements.
import torch
from torch.utils.data import DataLoader, RandomSampler
from data... |
""" Based on torchvision.models.resnet
This is basically resnet50, just to get you started.
"""
import logging
import torch
from torch import nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torch.optim.lr_scheduler import LambdaLR
import pugh_torch as pt
from pugh_torch.models impor... |
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import numpy as np
import scipy.io as sio
import gym
import time
import random
import datetime
import os
import imageio
import glob
import tqdm
import json
def get_center_state(env):
total_buffer_list = np.zeros([env.agent_nu... |
# CWA Reader
# <NAME>, Open Movement, 2017-2021
#
import sys
from struct import *
import time
from datetime import datetime
def read_timestamp(data):
value = unpack('<I', data)[0]
if value == 0x00000000: # Infinitely in past = 'always before now'
return 0
if value == 0xffffffff: # Infinitely in future = 'always... |
## python
from collections import defaultdict
import math
import matplotlib.pyplot as plt
import multiprocessing
import networkx as nx
import numpy as np
import pandas as pd
import random
import seaborn as sns
import statistics
import time
## graph utilities
def grid_r(N, M, p):
'''
N - height
M - width
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import re, collections, functools, json
from copy import deepcopy
from argparse import Namespace
try:
from functools import lru_cache
except ImportError:
from functools32 import lru_cache
###############################... |
# =========================================================================================
# Copyright 2016 Community Information Online Consortium (CIOC) and KCL Software Solutions
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.... |
import math
import re
from collections import Counter, OrderedDict, defaultdict
from enum import IntEnum
from fractions import Fraction
from itertools import groupby, combinations, permutations
from numbers import Real
from typing import FrozenSet
from typing import Iterable, Tuple, List, Dict, TypeVar, Optional, Set, ... |
import torch
from torch.nn import BCEWithLogitsLoss
import numpy as np
from itertools import product
DEFAULT_EPS = 1e-10
PADDED_Y_VALUE = -1
# From https://github.com/allegro/allRank/blob/master/allrank on June 7th 2021
def rankNet_weightByGTDiff(y_pred, y_true, padded_value_indicator=PADDED_Y_VALUE):
"""
... |
"""This module contains the backend implementation for tf Agents (see https://github.com/tensorflow/agents)"""
from abc import ABCMeta
from typing import Dict, Type
import math
import os
# noinspection PyUnresolvedReferences
import easyagents.agents
from easyagents import core
from easyagents.backends import core as b... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "<NAME>"
__copyright__ = "Copyright 2020, <NAME>, <NAME>, <NAME>, <NAME>"
__credits__ = ["<NAME>", "<NAME>"]
__license__ = "MIT"
__version__ = "1.0"
__status__ = "Development"
import numpy as np
import os
import csv
import cv2
from datetime i... |
class DAO(object):
def __init__(self, **kwargs):
for k, v in kwargs.iteritems():
setattr(self, k, v)
def _to_dict(self, name=None):
attrs = [attr for attr in self.__dict__ if not attr.startswith('_')]
_to_dict = {}
for attr in attrs:
if isinstance(getattr(self, attr), DAO):
_to_dict[attr] = getatt... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: segmentation.py
# Author: <NAME> <<EMAIL>>
import numpy as np
from math import ceil
import cv2,colorsys
import pydensecrf.densecrf as dcrf
import os, sys
from tensorpack.utils import logger
from tensorpack.utils.palette import PALETTE_RGB
__all__ = ['update_confus... |
import json
import logging
import re
from copy import deepcopy
from localstack.aws.api import RequestContext, ServiceRequest, handler
from localstack.aws.api.apigateway import (
Account,
ApigatewayApi,
ApiKeys,
Authorizer,
Authorizers,
BasePathMapping,
BasePathMappings,
Blob,
Boolea... |
#!/usr/bin/env python3
import json, time, uuid, sys
"""EIQJson
A simple EIQ json generator
Example usage:
obj = EIQJson()
obj.set_entity(obj.ENTITY_SIGHTING, 'Entity Title', 'This sighting came from <...>', '2017-12-15T10:15:00+01:00')
obj.add_observable(obj.OBSERVABLE_IPV4, '127.0.0.1')
obj.add_observable... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Class for plotting stuff
"""
import logging
import numpy
from numpy import pi
from matplotlib import pyplot
# import matplotlib.cm as cm
from amuse.datamodel import Particles
from amuse.io import read_set_from_file
from amuse.units import units, constants, nbody_syst... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This module has been written in order to be the main entry for every tests in a
directory which contain a list to test.
Authors:
- @Funilrys, <NAME> <contactTAfunilrysTODcom>
- @mitchellkrogza, <NAME> <mitchellkrogTAgmailTODcom
Contributors:
Let's contr... |
# coding: utf-8
# In[1]:
__author__ = '<NAME>'
__Lab__ = 'Gipsa-Lab'
__Corresponding_Paper__ = 'https://ieeexplore.ieee.org/document/8481451'
__Journal__ = 'IEEE Transactions on Affective Computing'
__Model__ = 'Corresponding Implementation of the model'
__license__ = 'Usage of the code require citation of the paper... |
import numpy as np
import warnings
from collections import deque
import random
import time
class DummyTransformer:
def fit(self, x, y=None):
return self
def fit_transform(self, x, y=None):
return x
def transform(self, x, y=None):
return x
class SarsaAgent:
"""Model-free on-p... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2013-2019 European Commission (JRC);
# Licensed under the EUPL (the 'Licence');
# You may not use this work except in compliance with the Licence.
# You may obtain a copy of the Licence at: http://ec.europa.eu/idabc/eupl
"""*(OUTDATED)* command-line entry-poin... |
# routines for a pyvista display tool
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib
import scipy.stats
from astropy.wcs import wcs
from astropy.nddata import support_nddata
from . import cmap
from . import mmm
from . import image
try:
# import autopy
im... |
import torch
import torch.nn as nn
from collections import OrderedDict
import torch.nn.functional as F
import numpy as np
import logging
import importlib
import sys
from torch_relay_build import torch_relay_func
from torch_func_modifier import func_modifier
formatter = logging.Formatter('%(asctime)s %(levelname)s %(me... |
# What's in a Name?
# In this live code-along, we will explore a rich dataset of first names of babies born in the US, that spans a period of more than 100 years! This surprisingly simple dataset can help us uncover so many interesting stories, and that is exactly what we are going to be doing.
#
# pip install html_tab... |
import pandas as pd
import numpy as np
import os
DATASET_DIR=os.path.join(".", "datasets")
#COMPAS
#https://github.com/fair-preprocessing/nips2017/blob/master/compas/code/Generate_Compas_Data.ipynb
# Quantize priors count between 0, 1-3, and >3
def quantizePrior(x):
if x <=0:
return '0'
elif 1<=x<=3:
... |
#!/usr/bin/env python
# This file is part of Diamond.
#
# Diamond is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ... |
import json, sqlalchemy, six
from sqlalchemy.orm.exc import MultipleResultsFound, NoResultFound
from functools import wraps
import datetime as dt
from operator import and_
from flask import jsonify, current_app, request, abort
from flask_restplus import reqparse, marshal
import unicodecsv as csv
from io import BytesIO
... |
import plotly.express as px
import time
import plotly
import os
import pandas as pd
import numpy as np
from scipy.stats import linregress
from plotly import tools
import chart_studio.plotly as py
import plotly.graph_objs as go
# Global variables
NMETHODS = 4
NDATASETS = 3
NRESOLUTIONS = 5
MetricsFilePath = '../Metric... |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from __future__ import (absolute_import, division,
with_statement, print_function)
import math
import cmath
import operator
import re
import random
try:
import color
from color import Color
from helpers import round_format_str
import ... |
import cv2
import sys, datetime
import glob
import dlib
import math
import os
from time import sleep
from shapely.geometry import Polygon
import numpy as np
# Kinect Azure intrinsics
FX = -622.359
CX = 641.666
FY = -620.594
CY = 352.072
FRAME_W, FRAME_H = 1280, 720
GREEN = (0, 255, 0)
BLUE = (255, 0, 0)
RED = (0, 0... |
#!/usr/bin/python
"""
Copyright 2017-2018 University of Cincinnati
All rights reserved. See LICENSE file at:
https://github.com/AS4SR/website
Additional copyright may be held by others, as reflected in the commit history.
"""
import os
import sys
import shutil
#
# create "verticalmenubar.part" as verticalmenubar_str ... |
"""
File: tests.py
Author: <NAME> (<EMAIL>)
Created: December 19, 2017
Suite of unit tests for functions in hammming.py.
Each test returns a tuple of (# tests failed, textual info about the failure).
"""
from bitarray import bitarray
from sys import stderr, stdout
import hamming
# total number of unit tests (for ni... |
""" Supports sparse codegen exhaustive tests.
This modules exports two classes InputDesc and TestDesc. It provides utilities
for enumerating codegen options as well as sparsity annotation for tensors with
certain ranks. It also provides utilities for parsing comman lines, generating
sparse tensor inputs, running tests... |
#!/usr/bin/env python3
# vim: set fileencoding=utf-8 :
import serial
import time
from time import gmtime, strftime
import struct
import sys
import datetime
from calendar import timegm
def usage():
print ("Usage: dmm_util info : Display info about the meter")
print (" d... |
# -*- coding: utf-8 -*-
u"""ML execution template.
:copyright: Copyright (c) 2020 RadiaSoft LLC. All Rights Reserved.
:license: http://www.apache.org/licenses/LICENSE-2.0.html
"""
from __future__ import absolute_import, division, print_function
from pykern import pkcompat
from pykern import pkio
from pykern import pk... |
import re
from accentuation import recessive, on_penult
from endings import PRIMARY_ACTIVE, PRIMARY_MIDDLE, SECONDARY_ACTIVE, SECONDARY_MIDDLE
from endings import ACTIVE_SUBJUNCTIVE, MIDDLE_SUBJUNCTIVE
from endings import PRIMARY_ACTIVE_OPTATIVE, PRIMARY_MIDDLE_OPTATIVE
from endings import SECONDARY_ACTIVE_OPTATIVE, ... |
#!/usr/bin/env python3
"""
Copyright (C) 2018-2019 <NAME>.
Use, modification and distribution are subject to the
Boost Software License, Version 1.0. (See accompanying file
LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
"""
import argparse
import copy
import json
import math
import mul... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Hive Netius System
# Copyright (c) 2008-2020 Hive Solutions Lda.
#
# This file is part of Hive Netius System.
#
# Hive Netius System is free software: you can redistribute it and/or modify
# it under the terms of the Apache License as published by the Apache
# Foun... |
"""
The idea behind cached-path is to provide a unified, simple interface for accessing both local and remote files.
This can be used behind other APIs that need to access files agnostic to where they are located.
"""
import glob
import os
import logging
import tempfile
import json
from dataclasses import dataclass, a... |
# plots mA and mC probabilities above threshold for single molecules
# modified from methplotlib
# input from guppy&winnow merge or megalodon
#
# use:
# python single_molecule.py -i <bam_file(s)> -w <window> -t <thresh> -b <bed_file> -n <name(s)>
#
# example use:
# python single_molecule_plotly_meg_winnow_guppy_FINAL.... |
"""The initial module that gets called when the program is launched."""
import argparse
from vimvaldi.components import *
from vimvaldi.utilities import *
from vimvaldi.graphics import *
from vimvaldi.music import *
@dataclass
class Rectangle:
"""A rectangle class."""
x: int
y: int
width: int
h... |
# -*- coding: utf-8 -*- {{{
# vim: set fenc=utf-8 ft=python sw=4 ts=4 sts=4 et:
#
# Copyright (c) 2020, <NAME>, Godithi.
# All rights reserved.
#
#
# IIIT Hyderabad
#}}}
#Sam
import datetime
import logging
import sys
import uuid
from volttron.platform.vip.agent import Agent, Core, PubSub, compat, RPC
from volttron.... |
import enum
import json
from datetime import datetime
from operator import attrgetter
from typing import Any, Dict, List, Optional, Union
from fastapi import APIRouter, Depends, Path, Query
from fastapi.encoders import jsonable_encoder
from fastapi.logger import logger
from requests.exceptions import ConnectionError, ... |
""" molecular graph transformations (representing transformations)
"""
import numbers
import itertools
from automol import formula
from automol import dict_
import automol.convert.graph
from automol.graph._graph import atom_keys as _atom_keys
from automol.graph._graph import explicit as _explicit
from automol.graph._gr... |
import torch
import numpy as np
import torch.nn as nn
from torch.nn import functional as F
__all__ = ['BCELoss', 'BalancedBCELoss',
'DiceLoss', 'BCEDiceLoss', 'GeneralizedDiceLoss',
'BinaryFocalLoss',
'TverskyLoss']
# todo: 学习一下 https://github.com/LIVIAETS/surface-loss/blob/maste... |
import math
import numpy as np
import torch.nn.functional as F
import torch, sys
from torch import nn
import pystrum.pynd.ndutils as nd
def sliding_predict(model, image, tile_size, n_dims, overlap=1/2, flip=False):
image_size = image.shape
stride_x = math.ceil(tile_size[0] * (1 - overlap))
stride... |
import abc
import more_itertools as itertools
import re
from . import types
from .types import Union, Optional, Literal, List, set_context
from . import checker
import logging
logger = logging.getLogger(__name__)
pattern = re.compile(r'(?<!^)(?=[A-Z])')
def get_instances_from_hacked_dataclasses(constraint):
ass... |
import pyarrow as pa
import pytest
def test_slice(client):
data = client.execute('{ length slice(length: 3) { columns { zipcode { values } } } }')
assert data == {'length': 41700, 'slice': {'columns': {'zipcode': {'values': [501, 544, 601]}}}}
data = client.execute('{ slice(offset: 1) { columns { zipcode ... |
# -*- coding: utf-8 -*-
from __future__ import print_function, division
import re
from PyAstronomy.pyaC import pyaErrors as PE
import pickle
import os
import uuid
import six
import six.moves as smo
def equal(dependsOn):
return dependsOn
class Params:
"""
Manage a set of parameters.
This class provi... |
# ===============================================================================
# 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/... |
import os
import argparse
import warnings
import numpy as np
import tensorflow as tf
import scipy.stats as sps
import tensorflow_probability as tfp
import seaborn as sns
from matplotlib import pyplot as plt
from callbacks import RegressionCallback
from regression_data import generate_toy_data
# workaround: https://g... |
import itertools
import functools
import random
from datetime import datetime
from pathlib import Path
import shutil
import warnings
import gc
import os
import pytorch_lightning.plugins.environments
from matplotlib import pyplot as plt
import numpy as np
import torch
import pytorch_lightning as pl
from pytorch_light... |
"""
Validate profiles and instances in a FSH file.
Process:
- Run SUSHI to generate JSON files (StructureDefinitions, ValueSets, Instances, etc) from FSH files
- Parse FSH file to identify profiles and instances defined in the file
- Run FHIR Java validator for each instance defined in FSH file
"""
import warnings
fro... |
# -*- coding: utf-8 -*-
import curses
import curses.ascii
import logging
from sys import version_info, platform
import locale
locale.setlocale(locale.LC_ALL, '') # set your locale
logger = logging.getLogger(__name__)
class SimpleCursesLineEdit(object):
""" Class to insert one line of text
Python 3 support... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import torch.nn as nn
import numpy as np
import json
from json import encoder
import random
import string
import time
import os
import sys
import misc.utils as utils
from misc.rewards import init_... |
import sys
import threading
import os
from textwrap import dedent
from collections import OrderedDict
import json
import time
import stat
import sublime
import sublime_plugin
PACKAGE_ROOT_DIRECTORY = os.path.dirname( os.path.realpath( __file__ ) )
CURRENT_PACKAGE_NAME = os.path.basename( PACKAGE_ROOT_DIRECTORY ).r... |
#!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
import sys
sys.path.append("/usr/local/cython/")
import numpy as np
import math
import json
import hydra
import os
import time
import pickle as pkl
import pushestcpp
import gtsam
from itertools import combinations, permutations, combinations_w... |
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import datetime
import time
import json
try:
import arcpy
arcpyFound = True
except:
arcpyFound = False
from ..packages import six
import copy
import os
import tempfile
import uuid
from .spatial impor... |
"""Main driver to run model."""
import numpy as np
import tensorflow as tf
# used to add values to summary
from tensorflow.core.framework import summary_pb2
import time
import sys
import os
import argparse
import pickle
import subprocess
from video_recorder import VideoRecorder
sys.path.insert(0, './preprocessors')
sys... |
#!/usr/bin/env python
# test_cursor.py - unit test for cursor attributes
#
# Copyright (C) 2010-2011 <NAME> <<EMAIL>>
#
# psycopg2 is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of t... |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
##############################################################################
"""Functions for evaluating results computed... |
# -*- coding: utf-8 -*-
from __future__ import print_function
from distutils.version import LooseVersion
from numpy import nan, random
import numpy as np
from pandas.compat import lrange
from pandas import (DataFrame, Series, Timestamp,
date_range)
import pandas as pd
from pandas.util.testing im... |
#!/usr/bin/env python2
# Copyright (c) 2017-present, Facebook, 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 ... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
import torch
import torch.nn as nn
import torch.nn.functional as F
from fairseq import utils
from fairseq.model_parallel.model... |
import logging
import sqlite3
import typing
import asyncio
import binascii
import time
from torba.client.basedatabase import SQLiteMixin
from lbrynet.conf import Config
from lbrynet.extras.wallet.dewies import dewies_to_lbc, lbc_to_dewies
from lbrynet.schema.claim import ClaimDict
from lbrynet.schema.decode import smar... |
# Stores classes & functions needed to check harmony of a piece
from pyknon.music import Note, NoteSeq
from CheckMyChords.models import MusicPiece
from CheckMyChords.pyknon_extension import *
class Chord(object):
# a class storing a chord (as Note objects) and additional info about it
# (as well as methods f... |
"""sklearn interface to finetuning BERT.
Overall flow:
-------------
# define model
model = BertClassifier() # text/text pair classification
model = BertRegressor() # text/text pair regression
model = BertTokenClassifier() # token sequence classification
# fit model to training data... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.