text
stringlengths
3.07k
12.6k
''' Pupil Detection ''' #-------------------------------- # Date : 23-06-2020 # Project : Pupil Detection # Category : Detection # Company : weblineindia # Department : AI/ML #-------------------------------- import os import numpy as np import cv2 from skimage import io import imutils import argparse import dlib # Ar...
from unittest import TestCase import pandas as pd import numpy as np from functools import partial import plotly.graph_objs as go from pybleau.plotly_api.api import BLACK, BLUE, GREEN, plotly_scatter, RED from pybleau.plotly_api.testing_utils import BaseFigureArguments DATA = pd.DataFrame({"a": list("abcdcb"), "b": n...
from defcon import Font, Glyph, Contour, Point from functools import partial from objects import BitFont, BitInfo, BitGlyph, BitMetrics import codepoints import re import unicodedata from utils import flatten, distinct, distinct_by, count_while def convert_to_font(bit_font): bit_metrics = calculate_bit_metrics(bit...
from __future__ import absolute_import from rlib import jit from rlib.debug import make_sure_not_resized from rtruffle.node import Node from som.interpreter.ast.frame import ( create_frame_args, create_frame_3, create_frame_2, create_frame_1, ) from som.vmobjects.method import AbstractMethod def get...
import re import os import pytest import subprocess import textwrap from conftest import BINDIR, HlwmProcess import conftest HLWM_PATH = os.path.join(BINDIR, 'herbstluftwm') def test_reload(hlwm_process, hlwm): with hlwm_process.wait_stdout_match('hlwm started'): # run the command, but read not hlwm's o...
"""Didcommm Universal DID Resolver.""" import json import re import logging from typing import Callable, List, NamedTuple, Set, cast from aries_cloudagent.config.injection_context import InjectionContext from aries_cloudagent.connections.models.conn_record import ConnRecord from aries_cloudagent.core.profile import P...
from __future__ import annotations import importlib import os from dataclasses import dataclass, field from operator import attrgetter from types import ModuleType from typing import TypeVar, Generic, Union, Optional, Iterable from PyQt5.QtGui import QFont, QColor from Cat.extensions import processRecursively from C...
"""Recursively saves the outputs as ROOT objects: TH1D, TH2D, TGraph.""" from gna.ui import basecmd, append_typed, qualified import matplotlib from matplotlib import pyplot as plt from matplotlib.ticker import AutoMinorLocator from mpl_tools.helpers import savefig import numpy as np from tools.yaml import yaml_load fr...
import os import torch import torch.nn as nn from torch.utils.model_zoo import load_url from .universal import UniversalProcess from .util import remove_layer from .util import initialize_weights __all__ = ['resnet50'] model_urls = { 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth', } cla...
"""Symantec Web Service This is generated to get categories of given urls, normally it fetches category from symantec web service then saves it to local file which is called `categorized_urls` under `richkit/retrieve/data/` How to use: >>> # Import necesseary functions and make a call as demonstrated given belo...
import numpy as np import param from holoviews import Store, Options, Layout, HoloMap, Histogram, Dimension try: # HoloViews <1.8 from holoviews.operation import TreeOperation except: # HoloViws >=1.8 from featuremapper.analysis import TreeOperation class WeightIsotropy(TreeOperation): """ Compu...
# XML Object Handler # Version 0.2 Patch 2 # <NAME> - 5/2/16 from xml.etree.ElementTree import Element as _Element, ElementTree as _ElementTree, dump as _dump, fromstring as _fromstring, parse as _parse from http.client import HTTPConnection, CannotSendRequest import storageUtils as SU from os import chdir d...
from pyspark.sql import SparkSession from pyspark.sql.window import Window from pyspark.sql.types import IntegerType, Row, StringType, StructField, StructType, ArrayType, FloatType from pyspark.sql.functions import col, sum, first, udf, expr, mean, max, min, stddev def iniciaSpark(debug_mode=False): spark = Spark...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright (c) 2013 <NAME> # Distributed under the terms of the Modified BSD License. # The full license is in the file LICENSE, distributed with this software. # from izdvd import config import os import os.path import argparse import tempfile from datetime import ...
#!/usr/bin/python # -*- coding: iso-8859-1 -*- # Copyright (c) 2016, <NAME> <<EMAIL>> # All rights reserved. # See LICENSE.txt # Copyright (c) 2004 <NAME> (http://www.owlfish.com/) # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are pe...
"""Generally static data from the WoW API. This file interfaces with data that are most of the time a one-time-load, coming form the Game Data APIs. See also: https://develop.battle.net/documentation/world-of-warcraft/game-data-apis """ from __future__ import annotations __LICENSE__ = """ Copyright 2019 Google LLC ...
""" Author: <NAME> """ import logging import os from collections import OrderedDict import torch import torch.nn as nn try: from . import initializer except: import initializer class BottleneckC2D(nn.Module): #瓶颈层,一般在深度较高的网络中使用 expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None): su...
''' nurse scheduling problem (shift scheduling) optimize the shift scheduling with genetic algorithm ''' from random import randint, random, shuffle import numpy as np class SimpleGA: def __init__(self, n_pop, n_gen, ratio_select, prob_mut): self.n_pop = n_pop self.n_gen = n_gen se...
from ._package_utils \ import \ parse_package_full_name from .errors \ import \ DepSolverError from .constraints \ import \ Equal, GEQ, GT, LEQ, LT, Not from .package \ import \ parse_package_full_name from .requirement_parser \ import \ RawRequirementParser f...
#impot libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt import pickle import os from sklearn.cluster import KMeans from keras.datasets import mnist,cifar10,fashion_mnist from keras.utils import np_utils from keras.models import Sequential from keras.layers.core import Dense, Dropout, A...
#!/usr/bin/env python3 import argparse from datetime import datetime import os from pathlib import Path from jinja2 import Template import requests from sephiroth.providers import Provider import sephiroth supported_servers = ["nginx", "apache", "iptables", "ip6tables"] supported_targets = ["aws", "azure", "gcp", ...
from contextlib import contextmanager from mock import MagicMock from mock import patch import os import chainer from chainerrl.agents import a3c import chainerrl.distribution import gym import numpy import pytest from chainerrl_visualizer import launch_visualizer import chainerrl_visualizer.launcher as launcher @c...
import pytest from pathlib import Path import pexpect import json import shutil tests_dir = Path(__file__, '..').resolve() test_configs_path = tests_dir / "configs" download_path = tests_dir / "download" # Mapping from model name to config-model_dir-ispretrained and corresponding queries-response list. PARAMS = {"e...
from typing import List, Tuple import gmpy2 from cat.utils.result import Result from cat.utils.result import ResultEntry as RE from cat.utils.result import Severity class RSAResult(Result): """ Results for checks on RSA components. """ OK = RE(Severity.OK, """The RSA component is as one would expec...
import bisect import json from common import networkClasses from random import seed, randint from pickle import load, dump from igraph import Graph import csv # helper functions def loadCSV(fp): reader = csv.reader(fp) return reader def loadJson(fp): """ helper function to load json :param fp:...
import pickle from functools import partial from typing import Union, Callable, Optional, List, Dict from .. import uwsgi from ..typehints import Strint from ..utils import decode, decode_deep, listify __offloaded_functions: Dict[str, Callable] = {} TypeMuleFarm = Union[Strint, 'Mule', 'Farm'] def _get_farms() ->...
# coding: utf-8 from django.conf import settings from django.contrib.auth.decorators import login_required from django.contrib import messages from django.urls import reverse_lazy, reverse from django.http import HttpResponseRedirect from django.shortcuts import redirect, get_object_or_404 from django.utils.translation...
#!/usr/bin/python3 ########################################################################### # Copyright 2019 Supranational 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 # # h...
# Copyright 2020 Cognoscitive Automata Incorporated # # 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 applicabl...
#!/usr/bin/env python # coding: utf-8 # In[8]: import os from os.path import join from pathlib import Path import torch from tqdm import tqdm import random import pandas as pd import sys sys.path.append(os.path.abspath(Path('..'))) from notebooks.profiles import MahalanobisProfile from notebooks.feature_extractor...
import json import logging from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework.decorators import permission_classes from rest_framework import permissions from api.helpers import FormHelpers from .constants import ErrorConstants f...
# -*- coding: utf-8 -*- from __future__ import division, print_function, unicode_literals __all__ = ["PeakDetect"] import os import h5py import logging import numpy as np from scipy.ndimage.filters import gaussian_filter from .pipeline import Pipeline def count_overlapping_transits(p1, t1, p2, t2, tmn, tmx, tol):...
""" bluew.tests ~~~~~~~~~~~ This module provides tests for the Bluew API. :copyright: (c) 2017 by <NAME>. :license: MIT, see LICENSE for more details. """ import bluew from unittest import TestCase from testconfig import config from nose.plugins.attrib import attr from bluew.errors import DeviceNotAvailable, Contro...
# -*- coding: utf-8 -*- """ Workload objects for running IO. Example: Run IO for 10 minutes on 2 volumes: # Create volumes: appinst = api.app_instances.create(name="ai1") storinst = appinst.storage_instances.create(name="si1") vol1 = storinst.volumes_create(name="testvol1", ...
"""Methods for graph plotting.""" import networkx as nx import seaborn as sns import json from matplotlib import colors import matplotlib.pyplot as plt from .generic import interactions_to_edges # seaborn settings sns.set_style("white") sns.set_context("poster") color_palette = sns.color_palette("colorblind") sns.set_...
# # nuna_sql_tools: Copyright 2022 Nuna 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 agreed...
# -*- coding: utf-8 -*- """ @author by mkzhou @time 2021/5/23 下午3:00 """ import tensorflow as tf import numpy as np from matplotlib import pyplot as plt def get_data(): n = 400 x = tf.random.uniform([n, 2], minval=-10, maxval=10) w0 = tf.constant([[2.0], [-3.0]]) b0 = tf.constant([[3.0]]) # @表示矩阵...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (c) 2022 PaddlePaddle 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/...
import discord from discord.ext import commands from ScoreManager import ScoreManager from pytz import timezone from datetime import datetime Client = discord.Client() client = commands.Bot(command_prefix='&') manager = ScoreManager('template.db') time_zone = timezone('Europe/Amsterdam') with open('token') as file: ...
import cv2 import numpy as np import math from tools.utils import bgr2ycbcr def cal_PSNR(img_HR, img_SR, use_YCbCr = True): #x3 # if img_SR.shape[1] != img_HR.shape[1] or img_SR.shape[0] != img_HR.shape[0]: # img_HR = cv2.resize(img_HR,(img_SR.shape[1], img_SR.shape[0]), interpolation=cv2.INTER_CUBIC) ...
"""The first three functions are just used for testing purposes for this assignment. You also saw them in the last programming problem set. list_strings gives a list of all strings of length n, string_to_nat and nat_to_string convert back and forth between binary strings and natural numbers.""" def list_strings(n): ...
import sys sys.path.insert(1, r'C:\Users\ewais\Documents\GitHub\tensor-hero\Model_1\Processing') sys.path.insert(1, r'C:\Users\ewais\Documents\GitHub\tensor-hero\Model_3') from m4_functions import * from m1_postprocessing import * import os from pathlib import Path import pickle import numpy as np from tqdm import tqdm...
#!/usr/bin/env python2 # # Code to send trajectory to the command node by sending setpoints at a certain rate. # By running the main fonction (waithere), User can decide what to do depending on the drone state (armed or not, in air or not) import rospy import time import math import numpy as np import tkinter from tki...
#!/usr/bin/env python from __future__ import unicode_literals 'Make the WOFF metadata xml file based on input UFO and FONTLOG.txt' __url__ = 'http://github.com/silnrsi/pysilfont' __copyright__ = 'Copyright (c) 2017 SIL International (http://www.sil.org)' __license__ = 'Released under the MIT License (http://opensource....
import argparse import os import subprocess import sys class AutomataGenerator: '''Class for generating random automata. The class is used to generate random automata identified with a LTL-like formula for using ltlcross for comparing tools on random automata instead of LTL formulas. Attributes: ...
import numpy import scipy from scipy.linalg.misc import _datacopied from jadapy import Target _double_precision = ['i', 'l', 'd'] __all__ = ['generalized_schur', 'generalized_schur_sort'] def generalized_schur(a, b, output='real', lwork=None, overwrite_a=False, overwrite_b=False, sort=None, c...
# MIT License # Copyright (c) 2021 <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...
import torch import torchvision.utils as utils def compute_i_th_moment(input, i): """ computes the i-th moment of the input tensor channel-wise :param input: tensor of size (n, c, h, w), n=1 :param i: the moment one wants to compute :return: tensor with the i-th moment of every channel """ ...
from __future__ import unicode_literals from __future__ import absolute_import, division, print_function """ Test module used to create some initial site data for experimentation and manual testing """ __author__ = "<NAME> (<EMAIL>)" __copyright__ = "Copyright 2014, <NAME>" __license__ = "MIT (http://opens...
import torch import numpy as np from utils import layer from torch.nn import functional as F from torch import nn from radam import RAdam class ActorModel(nn.Module): def __init__(self, layer_number, env, FLAGS): super().__init__() self.actor_grads = FLAGS.actor_grads and layer_number > 0 ...
# Copyright 2021 <NAME> # Copyright 2015 <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 or agr...
import os import abc import json import redis from flask import request from flask import Response from base64 import b64encode, b64decode, urlsafe_b64decode from Crypto.Signature import PKCS1_v1_5 from Crypto.Hash import SHA256 from Crypto.PublicKey import RSA REDIS_HOST = os.environ.get('REDIS_HOST') REDIS_PORT = os...
#!/usr/bin/env python """ Given: 1. single cell UMI, BC file (ccs -> umi, bc) 2. collapse group.txt (ccs -> pbid) 3. SQANTI classification (pbid -> transcript, isoform, category) 4. optional ontarget file (pbid -> ontarget or not) Output a collated infor file that is: <ccs>, <pbid>, <transcript>, <ge...
""" Created on Tuesday 22 August 2017 Last update: Thursday 18 January 2018 @author: <NAME> <EMAIL> Functions for quadratic optimization """ import numpy as np def solve_1d_quadratic(p, q, r=0): """ Finds the minimizer of an 1-D quadratic system, raises an error if there is no minimizer (p<0) Input...
import os import sys # scipy stack from matplotlib import pyplot as plt import seaborn as sns import numpy as np import pandas as pd import pypdb as pdb # making sql queries of pd.Dataframes import pandasql class OPMqueryException(pandasql.PandaSQLException): pass def get_path(filename): """ Locate th...
import decimal from dataclasses import dataclass import typing from aiokraken.model.assetpair import VolumeFee, AssetPair from hypothesis import strategies as st from marshmallow import fields, post_load, post_dump from marshmallow.schema import BaseSchema from aiokraken.model.tests.strats.st_assetpair import AssetP...
import math from sklearn.metrics import f1_score import numpy as np import pandas as pd from ChemSelML.bin.ChemSelectivityDataset import ReactionDataset, SelectivityDataset from ChemSelML.bin.ChemSelectivityDataset import Transform_DG_to_DDG ArR_dataset = ReactionDataset(root='/PyScripts/PyTorch.dir/Radical/DataSet',...
import json import pytest from spantools import ( Error, NoErrorReturnedError, InvalidAPIErrorCodeError, errors_api, PagingReq, PagingResp, ) class CustomError(errors_api.APIError): api_code = 2001 http_code = 405 class TestError: def test_from_exception_api(self): exc = ...
from PyPDF2 import PdfFileReader, PdfFileWriter import pathlib from pathlib import Path from reportlab.pdfgen import canvas import io import os import csv import numpy as np def getPDF(lngths, perimeters, CSA, APW, MLW): """ creates a PDF file containing information about the limb in correct locations on t...
# Sample # # # # Sample contains a series of functions to define waveforms. # # VOLUME: function that dictates output volume in one of three modes. # Duration: function shape between x = 0 and x = 1 dictates volume over duration of the requested time alive. # Fixed: function shape between x = 0...
import pandas as pd import numpy as np import statsmodels.api as sm import scipy.stats as scs import matplotlib.pyplot as plt import tushare stock = ['000651格力电器', '000725京东方A', '600036招商银行', '600519贵州茅台', '601318中国平安'] noa = len(stock) start_date = '2017-01-01' end_date = '2017-10-27' df1 = tushare.get_hist_data('00...
import logging from logging.handlers import SysLogHandler import os.path import sys import traceback import platform import os DEBUG = logging.DEBUG INFO = logging.INFO WARNING = logging.WARNING ERROR = logging.ERROR CRITICAL = logging.CRITICAL _pid = os.getpid() syslog_socket_paths = { 'Darwin': '/var/run/syslo...
# Author: <NAME>, https://users.soe.ucsc.edu/~cicekm/ from argparse import ArgumentParser, RawTextHelpFormatter from EstimatorLists import * import sys def getEstimatorsInfo(): faceDetDes = '' for c, est in zip(faceDetectorCodes, faceDetectors): faceDetDes += '\'%s\': %s\n' % (c, est) lndmrkDetDes...
import os import numpy as np from Bio.Alphabet import IUPAC, Gapped from BConverters.Converters import convert_alignment, convert_tree from RouToolPa.Parsers.R import get_indices_from_names def generate_partition_finder_control_file(alignment_file_name, genes_file, ...
"""Base LightningModule class.""" import argparse import inspect from typing import Any, Optional import pytorch_lightning as pl import torch import torch.optim import torch.nn as nn OPTIMIZER = "Adam" LR = 1e-3 WEIGHT_DECAY = 0.0 LR_SCHEDULER = None REDUCELRONPLATEAU_MODE = 'min' REDUCELRONPLATEAU_FACTOR = 0.1 RED...
import numpy as np import pandas as pd import tensorflow.compat.v1 as tf import tensorflow_addons as tfa import tensorflow_constrained_optimization as tfco from tensorflow.keras import activations, layers, losses, Sequential, Input from tensorflow_constrained_optimization.python.rates import loss class _DatasetWrapp...
#Team # <NAME> # <NAME> # <NAME> #Implemented Genetic Algorithm import sys import math from math import sqrt from random import randint, uniform class city: def __init__(self, location=""): temp = location.split(" ") self.index = int(temp[0])-1 self.fileindex = self.index+1 ...
import streamlit as st import pandas as pd import altair as alt import re import numpy as np import streamlit.components.v1 as components components.iframe("https://connie.dog/rat-image-tsne/", width=700, height=1000) st.write('<style>div.Widget.row-widget.stRadio > div{flex-direction:row;}</style>', unsafe_allow_htm...
## # File: svm_training.py # # Author: <NAME> # # Date: 17 February 2021 # # @brief soft svm trainer, will take in data and produce a set of CSVs corresponding to the # coeficcients produced by our loss function # import pandas as pd import numpy as np import cvxpy as cp class soft_SVM_train...
import asyncio from datetime import datetime from decimal import Decimal import logging import os from hexbytes import HexBytes import pytz from tenacity import retry, stop_after_attempt, wait_fixed, wait_random from web3 import Web3 from web3.exceptions import BlockNotFound import beneath LATEST_COUNT = 24 STABLE_A...
# ############################################################################################### # # # # Implements the a more efficient variant of the WEAT score calculation presented in [1]. # # ...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities __a...
import logging import yaml from pymodm import connect from biocontainers.common.models import MongoTool import click from ruamel.yaml import YAML import requests logger = logging.getLogger('misc_jobs') def print_help(ctx, value): if value is False: return click.echo(ctx.get_help()) ctx.exit() ...
#!/usr/bin/python # # Generates a complete library of wrapper functions for all the # Cuda calls defined in cuda_runtime_api.h. The library is a single # C file (libcudart_wrapper.c) which is to be compiled and linked # with the GPU_Locklib.c file to form a dynamically loaded library # libcudart_wrapper.so. (see Make...
""" Copyright 2021 <NAME> This script holds a simple conscious "thread" data structure. A conscious holds it own state. * work stack * function stack * 10 work registers * PC registers * ect. """ # built-in from functools import lru_cache from typing import Dict, Tuple, Type, Union # backrooms fr...
"""Support lib for the parser scripts found in this directory""" import os import inspect import logging import pwd import datetime from io import StringIO import socket import sys import traceback from email.mime.text import MIMEText from syslog import LOG_LOCAL2 # 3rd party from twisted.python import log as tplog fr...
from time import time import torch import numpy as np from torch.nn.utils import clip_grad_norm_ from transformers import AdamW, get_linear_schedule_with_warmup from transformers import BertForSequenceClassification from config.BERT_QS.const import NUM_EPOCH, ES_EPOCH, MAX_GRAD_NORM, DEFAULT_LEARNING_RATE, WEIGHT_DEC...
import argparse import csv import os import time import random import cv2 import numpy as np from keras.layers import Lambda, Cropping2D, Conv2D, MaxPool2D from keras.layers.core import Dense, Flatten, Dropout from keras.models import Sequential from keras.optimizers import Adam from sklearn.utils import shuffle i...
# -*- coding: utf-8 -*- # Copyright (c) 2014, <NAME> # 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 condi...
import pandas as pd import logging logger = logging.getLogger(f'cibi.{__file__}') def make_dataframe(columns, dtypes, index_column=None): # Stackoverflow-driven development (SDD) powered by # https://stackoverflow.com/questions/36462257/create-empty-dataframe-in-pandas-specifying-column-types assert len...
#!/usr/bin/env python """Evaluate word representations by example-based classification. The task is to classify a word into one of two candidate sets based on its similarity (dot product of normalized vectors) to example words of those classes. The full evaluation is as follows. Given word vectors and two or more se...
"""List of tests for PyTests""" import os import joblib import pytest from context import ( SentinelAOI, SentinelAOIParams, KMeansNDVI, KMeansNDVIParams, debug_message ) def test_SentinelAOI(): """Test that the input system works correctly for SentinelAOI""" param_keys = [ 'geojs...
import csv import logging import os from typing import List import torch from scipy.stats import pearsonr import torch.backends.cudnn from sentence_transformers.evaluation import SentenceEvaluator, SimilarityFunction from sentence_transformers.readers import InputExample from sklearn.metrics.pairwise import paired_cosi...
import os from collections import namedtuple from typing import List, NamedTuple, Optional, Union import xlwings as xw from xl_populate_named_ranges import (backup_workbook, dump, logger, update_named_ranges) Command: NamedTuple = namedtuple("Command", "id function") class Cons...
import pygame from pygame.locals import * # @UnusedWildImport import string KEY_INPUT_DICT = {6 : {0:K_q, 1:K_w, 2:K_e, 3:K_a, 4:K_s, 5:K_d}, 7 : {0:K_q, 1:K_w, 2:K_e, 3:K_r, 4:K_a, 5:K_s, 6:K_d}, 8 : {0:K_q, 1:K_w, 2:K_e, 3:K_r, 4:K_a, 5:K_s, 6:K_d, 7:K_f}} class Letter_Square(obj...
# Copyright 2021 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...
# -*- coding: utf-8 -*- import sys import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Function from torch.autograd import Variable from torch.autograd.function import once_differentiable from data import coco as cfg from ..box_utils import match, log_sum_exp, decode, encode, j...
import random from StringSigFigs import Number, MakeNumber, RoundValue, CheckAnswer from CalcsWithSigFigs import subtractValues, multiplyValues, divideValues, findDecimalPlaces operators = ['+', '-', '*', '/'] def addValues(first,second): firstDP = findDecimalPlaces(first.value) secondDP = findDecimalPlaces(s...
""" Footprint functions for fetc harea using eddy covariance data """ import sys import numpy as np import scipy from scipy.special import gamma from scipy.integrate import quad, odeint from scipy.interpolate import griddata import matplotlib.pyplot as plt from kljun.calc_footprint_FFP import FFP from kljun.calc_fo...
from django.db import models from ckeditor.fields import RichTextField from django.utils.translation import gettext_lazy as _, get_language class Individual(models.Model): MALE = 1 FEMALE = 2 GENDER = [ (MALE, _('Male')), (FEMALE, _('Female')) ] class SocialStatus(models.IntegerChoices): UNKNOWN = (0, _...
# coding: utf-8 import typing from math import acos from math import degrees from math import sqrt from synergine2.exceptions import SynergineException from synergine2.share import shared from synergine2.simulation import Subject """ Positions are exprimed as tuple: (x, y, z) Considering start point at top left: ...
import discord from discord.ext import commands from discord.commands import Option, slash_command, SlashCommandGroup from discord import File from easy_pil import Editor, load_image_async, Font, Canvas import json with open ('././config/guilds.json', 'r') as f: data = json.load(f) guilds = data['guilds'] class sla...
import numpy as np import matplotlib.pyplot as plt from py_wake.deficit_models.gaussian import BastankhahGaussian, ZongGaussian, ZongGaussianDeficit from py_wake.deflection_models import GCLHillDeflection from py_wake.examples.data.hornsrev1 import V80 from py_wake.flow_map import XYGrid from py_wake.site.xrsite import...
# /**************************\ # | --- <NAME> --- | # | Python application for | # | site stress test | # \**************************/ import argparse import logging import random import socket import ssl import sys import time parser = argparse.ArgumentParser(description="IS Stresser - simple stress ...
from manimlib.constants import * from manimlib.mobject.geometry import Rectangle from manimlib.mobject.mobject import Mobject from manimlib.utils.config_ops import digest_config from manimlib.container.container import Container from manimlib.utils.space_ops import angle_of_vector from manimlib.utils.space_ops import r...
#!/usr/bin/env python from __future__ import print_function # support python3-style print import sys import os import re import argparse # 2022 <NAME> # MIT License # Copyright (c) 2022 <NAME> # Version: 1.0 # Email: <EMAIL> # ref /dataset/gseq_processing/active/bin/batch_qiime_prism/add_sample_name.py # which doe...
import cupy from cupy import internal def atleast_1d(*arys): """Converts arrays to arrays with dimensions >= 1. Args: arys (tuple of arrays): Arrays to be converted. All arguments must be cupy.ndarray objects. Only zero-dimensional array is affected. Returns: If there are onl...
import json import os import random import shutil import numpy as np import pandas as pd import torch from sklearn.metrics import confusion_matrix from termcolor import colored #### class ScalarMovingSummary(object): def __init__(self, alpha=0.95): self.alpha = alpha self.tracking_dict = {} d...
#!/usr/bin/env python3 # coding=utf-8 import torch from torch.nn import functional as F from torch.nn.modules import Module class PrototypicalLoss(Module): """ Loss class deriving from Module for the prototypical loss function defined below """ def __init__(self, n_support): super(Prototy...
# -*- coding: utf-8 -*- """ pygments.lexers ~~~~~~~~~~~~~~~ Pygments lexers. :copyright: Copyright 2006-2009 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import sys import fnmatch import types from os.path import basename try: set except NameError: from s...