text stringlengths 3.07k 22.1k |
|---|
import pytest
from multielo import MultiElo
import numpy as np
from typing import List
@pytest.mark.parametrize(
"k, d, s, ratings, true_expected, true_new",
[
(32, 400, 1, np.array([1000, 1000]), [0.5, 0.5], [1016, 984]),
(32, 400, 1, [1200, 1000], [0.75974693, 0.24025307], [1207.68809835, 9... |
import os
import threading
import logging
try:
from Queue import Queue, Empty as QueueEmptyException
except ImportError:
from queue import Queue, Empty as QueueEmptyException
from ms_deisotope.data_source import MSFileLoader, ScanBunch
from ms_deisotope.data_source.metadata.file_information import (
Sour... |
# coding=utf-8
# Copyright 2020 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... |
"""
A simple 2D FEM simulation using quadrilaterals
to show the compliance computation using FEM.
Following the convention of the other code, indexing is xy/cartesian
and not ij (see doc. of numpy.meshgrid)
"""
import os
import sys
import numpy as np
import scipy.sparse as sp
from scipy.sparse.linalg import spsolve
... |
import abc
import numpy as np
from sklearn.base import BaseEstimator, ClassifierMixin
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.linear_model import Percep... |
# 重要:对于scipy.optimize中的优化方法,不能通过改变目标函数的方式,将含有联合自变量的约束条件加入目标函数;
# 要增加带有联合自变量的约束条件,必须在方法中传入constraints关键字参数;若该方法没有constraints参数,则不能定义带有联合自变量的约束条件。
# the loss function of linear least square optimization is a convex function, so local or global optimizations are equal
from time import process_time
from pandas import DataF... |
"""
MIT License
Copyright (c) 2022 <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, copy, modify, merge, publish, distri... |
import numpy as np
from numpy import ndarray
def alpha_quartz_stiffness():
"""
Returns the stiffness matrix for α-silicon dioxide, as defined in Voigt notation.
:returns: The 6x6 stiffness matrix for α-silicon dioxide as a numpy array.
:rtype: ndarray
"""
C11, C33, C44, C66, C12, C13, C14 = ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import os
import time
import tensorflow as tf
import tensorflow.contrib.layers as layers
from six.moves import range, zip
import numpy as np
import zhusuan as zs
... |
import numpy as np
import ubelt as ub # NOQA
def group_consecutive(arr, offset=1):
"""
Returns lists of consecutive values
Args:
arr (ndarray): array of ordered values
offset (float): any two values separated by this offset are grouped.
In the default case, when offset=1, thi... |
# -*- coding: utf-8 -*-
# Copyright (c) 2018-2020 <NAME>
"""
Application for downloading and presenting investment results for
several people-to-people (P2P) lending platforms.
"""
from datetime import date, timedelta
import gc
import logging
import os
import sys
from typing import Set
from PyQt5.QtCore import (
... |
# Identifies inverted repeats and converts them to Feature objects
import re
import subprocess
import tempfile
from collections import namedtuple
from typing import Iterator, Optional, Tuple
from Bio.Seq import Seq
from operon_analyzer import genes, load
Repeat = namedtuple('Repeat', ['upstream_sequence', 'upstream_... |
import time
import matplotlib.pyplot as plt
import numpy as np
from GPGO import GP
from GPGO import RBF as RBF1
from GPGO import BayesianOptimization
from GPGO.GaussianProcess import log_gp
from GPGO.GaussianProcess import generate_grid
import logging
from GPGO.GaussianProcess.Kernel import Matern, Bias
x = np.random.... |
from datetime import datetime
import sqlalchemy as sa
import sqlalchemy.orm as sa_orm
from db_schema import Post as MappedPost, Posts, HashTag as MappedHashTag, HashTags, StarredPost as MappedStarredPost, StarredPosts
import db_util
from db_util import DbException
class PaginatedSequence:
"""A sequence of items re... |
# Copyright 2021 The Magenta Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
# Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""I2C module for controlling I2C buses and I2C slaves.
It is customized for the FPGA board with the TIO (Three-In-One) daughter
card. It drives the I... |
"""
Hyperbolic K-means implementation from https://github.com/drewwilimitis/hyperbolic-learning/blob/master/hyperbolic_kmeans/hkmeans.py
- Should be able to fit on poincare data
"""
import numpy as np
import sys
from tqdm import tqdm
from clustering.hkmeans_utils import *
#from args import args
def exp_map(v, theta,... |
# -*- encoding: utf-8 -*-
from Tyf import values, __geotiff__
_TAGS = {
# GeoTIFF Configuration GeoKeys
1024: ("GTModelTypeGeoKey", [3], 0, None),
1025: ("GTRasterTypeGeoKey", [3], 1, None),
1026: ("GTCitationGeoKey", [2], None, None), # ASCII text
# Geographic CS Parameter GeoKeys
... |
# Copyright 2022 Huawei Technologies Co., Ltd
# 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... |
"""WISDEM Monopile API"""
__author__ = ["<NAME>"]
__copyright__ = "Copyright 2020, National Renewable Energy Laboratory"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
import os
import yaml
import openmdao.api as om
from ORBIT import ProjectManager
class Orbit(om.Group):
def setup(self):
# D... |
import copy
import numpy as np
from collections import OrderedDict
from taps.models.models import Model
from ase.atoms import Atoms
from ase.data import atomic_masses
# from ase.calculators.calculator import get_calculator_class
# from ase.symbols import Symbols
class AtomicModel(Model):
implemented_properties... |
# imports
import logging
from cartoframes.auth import set_default_credentials
from cartoframes import read_carto, to_carto
import geopandas as gpd
from datetime import datetime
import dateutil.relativedelta
import requests
import xml.etree.ElementTree as ET
import math
import time
import pandas as pd
... |
"""
********************************************************************************
* Name: utilities.py
* Author: <NAME>
* Created On: 2014
* Copyright: (c) Brigham Young University 2014
* License: BSD 2-Clause
********************************************************************************
"""
from __future__ import... |
import sys
sys.path.append("..")
#import tensorflow as tf
import numpy as np
import time
from Featurize import *
import glob
from multiprocessing import Pool
def GetNodeMask(graph_size, max_size=None):
if max_size == None:
max_size = np.max(graph_size)
return np.array([np.pad(np.ones([s, 1]), ((0, max... |
import argparse
import enum
import io
import math
import serial
import struct
class MoteusReg():
# These constants can be found in:
# https://github.com/mjbots/moteus/blob/master/docs/reference.md under
# "register command set".
INT8 = 0
INT16 = 1
INT32 = 2
F32 = 3
WRITE_BASE = 0x00
... |
# encoding: utf-8
import sys
import time
import socket
import getopt
from select import select
from multiprocessing import Process
import logging # Using standard logging
# Setup logging
format_string = u'%(asctime)s - %(levelname)-10s : %(message)s'
formatter = logging.Formatter(fmt=format_string,
... |
#-*- coding:utf-8 -*-
#
# Original code is here: https://github.com/openai/guided-diffusion
#
import numpy as np
import torch as th
import torch.nn as nn
import torch.nn.functional as F
from .fp16_util import convert_module_to_f16, convert_module_to_f32
from .modules import *
NUM_CLASSES = 1
class UNetModel(nn.Modu... |
import flask
import pickle
import pandas as pd
import numpy as np
#load models at top of app to load into memory only one time
with open('model/xgb_cv_compact.pkl', 'rb') as f:
clf = pickle.load(f)
with open('model/knn_regression.pkl', 'rb') as f:
knn = pickle.load(f)
#load APR table
df_fico_ap... |
'''
This module contains various utilitarian functions used by other modules.
'''
#***************************************
# Imports
#***************************************
import sys
import os
import stat
import threading
import logging, logging.handlers
from dependencies.pefile import pefile
import globs
impo... |
#!/usr/bin/python
# calculaRaizEcu2doGrado.py
# Calcula la raices de una ecuación de la forma ax^2+bx+c=0
#
# Coeficientes an0 estan representados por la lista an0=[a,b,c],
# donde: {a,b,c} pertenece a los Reales y an0 <>0.
#
# Se calcula el discriminante = b^2 - 4ac.
#
# Si, discriminante > 0. Entonces CASO I... |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Test handlers."""
from __future__ import absolute_import, print_function
import ... |
import os
import sys
from pypeLauncher import PypeLauncher
# add forcefully click from vendor in case we didn't installed pype yet
try:
import click
except ImportError:
click_path = os.path.join(os.environ['PYPE_SETUP_PATH'],
'vendor', 'python', 'click')
sys.path.append(click_... |
# Copyright 2017 Codethink Ltd.
#
# 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 writin... |
# -*- coding: utf-8 -*-
import os
import collections
from datetime import datetime
from randomizer import *
from numpy import core
from UnionFind import UnionFind
from nx_converters import *
from clique_tree import TreeStatistics
from Runners import *
from report_generator import *
"""
Implements the markenzon alg... |
#
# This file is distributed under MIT License.
# Copyright (c) 2020 draghan
# 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 t... |
import discord
import base91
import numpy as np
from random import randint
from discord.ext import commands
# If smoother is specified in the config file, it awaits before sending the new random tile, making it slightly more smoothe
smoother = True
numbers = ["zero", "one", "two", "three", "four", "five", "six", "sev... |
import datetime
import shutil
import sys
import time
from copy import deepcopy
from pathlib import Path
from utils import *
def fRAT():
start_time = time.perf_counter()
Utils.checkversion()
config, orig_path = load_config()
config = argparser(config)
# CompareOutputs.run(config) # TODO THIS IS... |
#!/usr/bin/env python3
# Copyright (c) 2020 <NAME>
# Licensed under the terms of the MIT License.
# This software is a derivative of the original makesite.py available at
# <https://github.com/sunainapai/makesite>. The license text of the
# original makesite.py is included below.
# The MIT License (MIT)
#
# Copyrigh... |
import re
import pandas as pd
from .models import load_and_test_model
from .dictionary import get_synonyms_and_antonyms
"""
This is the core textplainer interface.
The models passed into these functions are required to implement a
single function called 'predict(x)'
The function should take a pandas dat... |
import numpy as np
import pandas
from precomputed_tif.client import ArrayReader
from scipy import ndimage
import pickle
import typing
def corr(blk_fixed:np.ndarray,
blk_moving:np.ndarray,
pt:typing.Sequence[int],
orig_fixed:np.ndarray,
orig_moving:np.ndarray,
dx:int, dy:in... |
"""
Includes a lot of useful constants that are used in the bot.
"""
from os import environ as env
from datetime import datetime as dt
from dataclasses import dataclass
from discord import Colour
BASE_URL = env['BASE_URL'] if 'BASE_URL' in env else "https://judge0-ce.p.rapidapi.com"
IDE_LINK = "https://ide.glossar... |
import tensorflow as tf
from utils import *
def prenet(inputs, num_units=None, is_training=True, scope="prenet"):
if num_units is None:
num_units = [embed_size, embed_size // 2]
with tf.variable_scope(scope):
outputs = tf.layers.dense(inputs, units=num_units[0], activation=tf.nn.relu, name="d... |
import cv2 as cv
import numpy as np
import sys
import math
# /home/luis-sanroman/Documents/ele882/lab2
# /home/luis-zugasti/ele882/lab2
'''
ELE882 lab2: Edge Detection
This laboratory focuses on edge detection on grey scale images.
This library of function serves only for implementing the Edge Detector described in Se... |
#!/usr/bin/env python
#
# Copyright 2019 <NAME> <<EMAIL>>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... |
# SPDX-License-Identifier: Apache-2.0
import hashlib
import os
import sys
from cmakefileapi import TargetType
from cmakefileapijson import parseReply
from spdx.builder import BuilderDocumentConfig, BuilderPackageConfig, convertToSPDXIDSafe, makeSPDX
from spdx.relationships import outputSPDXRelationships
def getCmake... |
# Copyright 2017 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompa... |
# (c) 2012-2013 Continuum Analytics, Inc. / http://continuum.io
# All Rights Reserved
#
# conda is distributed under the terms of the BSD 3-clause license.
# Consult LICENSE.txt or http://opensource.org/licenses/BSD-3-Clause.
from __future__ import absolute_import, division, print_function, unicode_literals
from argpa... |
# Copyright (C) 2015 Catalyst IT Ltd
#
# 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 o... |
import numpy as np
from abc import ABC, abstractmethod
class Parameterization(ABC):
"""A generic class representing a subgrid parameterization. Inherit from
this class, :math:`UVParameterization`, or :math:`QParameterization` to
define a new parameterization."""
@abstractmethod
def __call__(self, ... |
import pygame
from enum import Enum
class GAME(Enum):
INTRO = 0
OPTIONS = 1
WIN = 2
GAMEOVER = 3
NEWGAME = 4
import mapgenerator
import GameObjects
import flow
class Game(object):
pygame.font.init()
smallfont = pygame.font.SysFont(None, 20)
medfont = pygame.font.SysFont(None, 50)
... |
# -*- coding: utf-8 -*-
'''Chemical Engineering Design Library (ChEDL). Utilities for process modeling.
Copyright (C) 2017, 2018, 2019, 2020 <NAME> <<EMAIL>>
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... |
import numpy as np
import pandas as pd
from collections import defaultdict
import operator
# Get Efficacy against threshold
def FScore(precision, recall, alpha = 1):
if (alpha ** 2 * precision + recall) == 0:
return 0.0
return (alpha ** 2 + 1) * precision * recall / (alpha ** 2 * precision + recall)
d... |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Project : acs-project-krr
@File : assignment_test.py
@Author : <NAME>
@Contact : <EMAIL>
@Date : 2020/11/20 8:07 下午
@Version : 1.0.0
@License : Apache License 2.0
@Desc : None
"""
# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Project : acs... |
from .forms import MemberChangeRoleForm, MemberCreateForm, OrganizationCreateForm
from .forms import ROLE_CHOICES
from datetime import datetime
from flask import Blueprint, current_app as app, flash, jsonify, redirect, render_template, request, session, url_for
from kqueen_ui.api import get_kqueen_client
from kqueen_ui... |
import argparse
import logging
import os
import pathlib
from copy import deepcopy
from glob import glob
from pathlib import Path
from typing import Any, Dict, List, Union
import json
import numpy as np
import pandas as pd
import torch
import torch.nn.functional as F
import yaml
from PIL import Image
from tqdm import t... |
"""
ARCHES - a program developed to inventory and manage immovable cultural heritage.
Copyright (C) 2013 <NAME> and World Monuments Fund
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either ... |
import pygame as pg
import numpy as np
from time import time
from settings import *
class Square(pg.sprite.Sprite):
# test object
def __init__(self, size):
pg.sprite.Sprite.__init__(self)
self.image = pg.Surface([size, size])
self.rect = self.image.get_rect()
self... |
# -*- coding: utf-8 -*-
"""
party.py
"""
from trytond.pool import PoolMeta, Pool
from trytond.transaction import Transaction
from trytond.pyson import Eval, Bool
from trytond.model import ModelView, fields
from trytond.wizard import Wizard, StateView, StateTransition, Button
__all__ = [
'Address', 'AddressVal... |
import argparse
import json
import logging
from datetime import datetime
import shutil
from itertools import chain
from os.path import join, exists
import numpy as np
import os
import matplotlib.pyplot as plt
import torch
import torch.backends.cudnn as cudnn
import torch.nn.parallel
import torch.optim as optim
import t... |
import inspect
from typing import List, Dict, Set
from ._base import Grammar
class Symbol:
def __init__(self, name):
self.name = name
def __eq__(self, other):
return self.name == other.name
def __hash__(self):
return hash(self.name)
def __repr__(self):
return "Symbo... |
# -*- coding: utf-8 -*-
import numpy as np
import sympy.core as sp
from sympy.simplify import simplify as sympy_simplify
from sympy import symbols as sympy_symbols
import pickle
from ProGED.model import Model
"""Implements ModelBox, an class that stores and manages a collection of Model instances."""
class ModelBox... |
#!/usr/bin/env python3
import argparse
import logging
import os
import readline
import sys
import textwrap
from s3_browser import bookmarks
from s3_browser import client
from s3_browser import completion
from s3_browser import paths
from s3_browser import tokeniser
from s3_browser import utils
logger = logging.getLo... |
'''
markup views
Copyright (c) 2017 <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, copy, modify, merge, publish, dist... |
import copy
from enum import Enum
from difflib import SequenceMatcher
from collections import namedtuple, Counter, defaultdict
import copy
def break_match(a: str, b: str, match: namedtuple):
"""Breaks a strings with a common substring into prefix, root, suffix.
Args:
a (str)
b (str)
m... |
import logging
import os
from typing import List, Optional, Dict
import networkx as nx
import numpy as np
import pandas as pd
from openfermion import QubitOperator
import orquestra
from qequlacs import QulacsSimulator
from zquantum.core.interfaces.optimizer import Optimizer, OptimizeResult
from zquantum.core.interfac... |
from __future__ import annotations
from typing import List, Tuple, Optional
import dns
from . import utils
from .utils import DNSSECScannerResult, Zone, Key
from .messages import Message, Validator, Msg, Types
def validate_zone_keys(zone: Zone, result: DNSSECScannerResult):
if zone.DNSKEY and zone.DNSKEY_RRSIG:... |
"""
SimpleICPOptimization class.
"""
from __future__ import (
annotations,
) # needed for type hinting of RigidBodyParameters before it is defined
from dataclasses import dataclass, fields
from typing import List, Optional, Tuple
import lmfit
import numpy as np
from . import corrpts, mathutils
class SimpleIC... |
import uuid
from math import floor
from django.utils import timezone
from django.core import signing
from django.utils.translation import gettext_lazy as _
from django.utils.text import slugify
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.dispatch import Signal
from djang... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import Adafruit_BBIO.PWM as PWM
from time import sleep
import Adafruit_BBIO.GPIO as GPIO
import Adafruit_BBIO.ADC as ADC
import Adafruit_BBIO.PWM as PWM
import Adafruit_TCS34725
import os
import pprint
import pygame
import smbus
import time
import numpy as np
GPIO.se... |
import torch
import numpy as np
import matplotlib.pyplot as plt
import norse
import random as rand
from norse.torch import lif_step, lif_feed_forward_step, lif_current_encoder, LIFParameters
from norse.torch import li_step, LICell, LIState, LIParameters
from norse.torch.module import leaky_integrator as li
import rando... |
# Copyright (C) 2020 Intel 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 License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
import os
import sys
import logging
import importlib
from collections import OrderedDict
from pathlib import Path
from functools import reduce
from common import utilities
from common.exceptions import ModuleLoadException
from common.module.module import Module
from .dependency_graph import DependencyGraph
from .modul... |
from __future__ import absolute_import, unicode_literals
import pytest
from case import skip
from kombu.utils.functional import lazy
from celery.five import nextfun, range
from celery.utils.functional import (DummyContext, first, firstmethod,
fun_accepts_kwargs, fun_takes_argument... |
# tarkoitettu ESP32-Wroom-32 NodeMCU:lle
# Lukee DHT22-anturia ja ohjaa 2-kanavaista reletta
# Parametrit tuodaan parametrit.py-tiedostosta
# Yksi ledin vilaus = toiminta alkaa
# Kaksi ledin vilautusta = toiminta saatettu loppuun
# 10 ledin vilautusta = virhe!
# Osa kanalan automaatioprojektia, https://hiltsu.dy.fi
# <... |
from datetime import datetime
from datetime import timedelta
import time
import matplotlib as mplt
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
from numpy import NaN, Inf, arange, isscalar, asarray, array
from scipy import signal
from scipy.signal import argrelextrema, argr... |
import copy
import logging
from functools import partial, lru_cache
from typing import Optional, Union, Any, List
from bson import ObjectId
from fastapi import HTTPException, status
from torch.jit import RecursiveScriptModule
from enel_service.common.apis.hdfs_api import HdfsApi
from enel_service.common.apis.mongo_ap... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 适用于 tensorflow >= 2.0, keras 被直接集成到 tensorflow 的内部
# ref: https://keras.io/about/
from tensorflow.keras.layers import Input, Add, Dense, Activation, ZeroPadding2D, BatchNormalization, \
Flatten, Conv2D, AveragePooling2D, MaxPooling2D, Concatenate
from tensorflow.keras... |
"""
Created on 11 Nov 2020
@author: SMHI
"""
from django.core.management.base import BaseCommand
from sharkdata_core import (
SharkdataAdminUtils,
DatasetUtils,
ResourcesUtils,
SharkArchiveFileReader,
)
import app_datasets.models as datasets_models
import app_ctdprofiles.models as ctdprofiles_models
... |
"""The Adversarial GLUE (AdvGLUE) benchmark.
Homepage: https://adversarialglue.github.io/
"""
import json
import os
import textwrap
import datasets
_ADV_GLUE_CITATION = """\
@article{Wang2021AdversarialGA,
title={Adversarial GLUE: A Multi-Task Benchmark for Robustness Evaluation of Language Models},
author={<NAM... |
import torch.nn.functional as F
from torch.autograd import Variable
import torch
import torch.nn as nn
def adentropy(out_t1, lamda, reduce=True):
out_t1 = F.softmax(out_t1, dim=1)
loss_adent = lamda * torch.sum(out_t1 * (torch.log(out_t1 + 1e-5)), 1)
if reduce:
loss_adent = torch.mean(loss_adent, d... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2016-2017 China Telecommunication Co., Ltd.
#
# 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/lice... |
"""
draftsimtools.load
~~~~~~~~~~~~~~~~~~
Utilities for loading draftsim set and draft files.
"""
import re
import numpy as np
import pandas as pd
from sklearn import preprocessing
import torch
from torch.utils.data.dataset import Dataset
def create_set(path1, path2=None, alphabetical=True):
"""Load set ... |
import asyncio
import time
from django.utils import timezone as djangotime
from loguru import logger
from packaging import version as pyver
from typing import List
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.decorators import (
api_view,
permission_... |
# Released under the MIT License. See LICENSE for details.
#
"""Settings UI functionality related to wiimote support."""
from __future__ import annotations
import _ba
import ba
class WiimoteSettingsWindow(ba.Window):
"""Window for setting up Wiimotes."""
def __init__(self) -> None:
self._r = 'wiimot... |
"""Top-level package for Auto deprecator."""
import argparse
import ast
from io import BytesIO
from importlib import import_module
from functools import wraps
import logging
from os import environ, walk
from os.path import isfile, join
from tokenize import tokenize, COMMENT
from warnings import warn
__version__ = '202... |
#<NAME>
#
#CS 1411
#05/07/2017
#
#BATTING FILE STATISTIC ORGANIZER
#
#MAJOR PROGRAM SEQUENCE:
#OPENS A FILE OF BASEBALL BATTING STATISTICS
#ASKS USER WHAT INFORMATION THEY ARE LOOKING FOR
#CALLS A FUNCTION
#FUNCTION ORGANIZES THAT INFORMATION INTO A DICTIONARY WITH THE PLAYER+YR AS A KEY
#ASKS USER FOR PLAY... |
# Copyright 2022 Google LLC
#
# 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 writing, ... |
from CurlingLeagueManager import Team
from CurlingLeagueManager import TeamMember
from CurlingLeagueManager import Competition
from CurlingLeagueManager import League
from emailer import Emailer
import unittest
import datetime
class TeamMemberTests(unittest.TestCase):
def test_create(self):
oid = 1
... |
#!/usr/bin/env python
# -*- coding: latin-1 -*-
"""
Mandelbrot Set. (October 4, 2014)
See http://en.wikipedia.org/wiki/Mandelbrot_set#Computer_drawings .
Piece of SimpleGUICS2Pygame.
https://bitbucket.org/OPiMedia/simpleguics2pygame
GPLv3 --- Copyright (C) 2013, 2014 <NAME>
http://www.opimedia.be/
"""
import math
... |
import pygame
import math
from OpenGL.GL import *
from OpenGL.GLU import *
from pygame.locals import *
useQuat = True
def find_difference_between_quarternion(q1, q2):
diff = [0, 0, 0, 0]
diff[0] = q1[0] * q2[0] + q1[1] * q2[1] + q1[2] * q2[2] + q1[3] * q2[3]
diff[1] = q1[0] * q2[1] - q1[1] * q2[0] - q1[2]... |
# Copyright 2011 the V8 project authors. All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditi... |
from discord.ext.commands import Cog, command, Context
from discord import utils, Embed, Colour, Message, NotFound, Activity, ActivityType, Forbidden
from discord.ext import commands, tasks
import random
class General(Cog):
"""
General Purpose Commands and Events
"""
def __init__(self, bot):
... |
# SPDX-FileCopyrightText: 2021 <NAME> and <NAME> for Adafruit Industries
# SPDX-License-Identifier: MIT
# MagTag Sports Schedule Viewer
# Be sure to add your wifi credentials to the secrets.py file
# Press D to advance to next game
# Press C to go back one game
# Press B to refresh the schedule (this takes a minute)
... |
import matplotlib
matplotlib.use("agg")
import os,datetime,argparse,torch,numpy,pandas,seaborn,logging,scipy
from torchvision import transforms
from torchvision.datasets import MNIST
from torch.utils.data import DataLoader,Subset
from modules import *
from itertools import product
from matplotlib import pyplot
... |
import pandas as pd
import requests
import json
import base64
import logging
import os.path
from manubot import cite
headers = {} # For Development you can insert your GH api token here and up the rate limit {'Authorization': 'token %s' % "<apiToken>"}
if "GITHUB_TOKEN" in os.environ:
print("GITHUB_TOKEN env var... |
import torch
from config import cfg
import numpy as np
from utils.box_overlaps import *
from utils.anchor_utils import *
def cal_anchors():
# Output:
# Anchors: (w, l, 2, 7) x y z h w l r
x = np.linspace(cfg.SCENE_X_MIN, cfg.SCENE_X_MAX, cfg.FEATURE_WIDTH)
y = np.linspace(cfg.SCENE_Y_MI... |
"""Contains classes that are used to describe the structure of a site."""
from enum import Enum
from typing import Optional, List, Union
class VisitState(Enum):
"""Visit state of a category (node)"""
NEW = 0
IN_PROGRESS = 1
VISITED = 2
class Node:
"""
The node (category). Most sites are buil... |
# easings.py
# Useful easing functions for values animation
#
# How to use:
# The four inputs t, b, c, d are defined as follows:
# t = current time (in any unit measure, but same unit as duration)
# b = starting value to interpolate
# c = the total change in value of b that needs to occur
# d = total tim... |
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import pandas as pd
import numpy as np
import re
def product_choice(df):
products = list(set(df['product_code'].unique()))
hs_codes = []
hs_chapters = []
industry = []
for code in products:
... |
# Copyright (C) 2016 University of Vienna
# All rights reserved.
# BSD license.
# Author: <NAME> <<EMAIL>>
#
from __future__ import print_function, division
from six import iteritems
__all__ = [ 'hellerman_rarick_p_3_5' ]
def main():
try:
import mc33 #@UnusedImport
except ImportError:
import ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.