text
stringlengths
3.07k
12.6k
# -*- coding: utf-8 -*- ''' Management of firewalld .. versionadded:: Beryllium The following example applies changes to the public zone, blocks echo-reply and echo-request packets, does not set the zone to be the default, enables masquerading, and allows ports 22/tcp and 25/tcp. .. code-block:: yaml public: ...
from itertools import product, combinations import numpy as np import sys import torch def string_matmul(list_1, list_2): ''' Matrix multiplication with strings.''' prod = [element[0] + element[1] for element in product(list_1, list_2)] return prod def terms_definition(poly_list, deriv_list): ''' Cal...
""" m2wsgi.middleware.gzip: GZip content-encoding middleware ========================================================= This is a GZip content-encoding WSGI middleware. It strives hard for WSGI compliance, even at the expense of compression. If you want to trade off compliance for better compression, put an instanc...
# -*- coding: utf-8 -*- try: import typing except: # pragma: no cover pass import os import shutil from re import findall def split_s3_uri(s3_uri): """ Split AWS S3 URI, returns bucket and key. :type s3_uri: str :rtype: typing.Tuple[str, str] """ parts = s3_uri.split("/") bucke...
import time from datetime import datetime import numpy as np import pandas as pd import ccxt from quickndirtybot.io import save_csv, load_csv def connect(exchange_str='gdax'): return getattr(ccxt, exchange_str)() def get_ohlcv(exchange, interval='1m', symbol='BTC/USD'): if exchange.has['fetchOHLCV']: ...
from typing import Optional, Any class GuraError(Exception): """General Gura error, with position, line and a custom message""" def __init__(self, pos: int, line: int, msg: str, *args): self.pos = pos self.line = line self.msg = msg self.args = args def __str__(self): ...
import json from django.http import HttpResponse from rest_framework.permissions import AllowAny from rest_framework.response import Response from rest_framework.generics import GenericAPIView from translations.helpers import truncate import mkt from mkt.api.authentication import (RestSharedSecretAuthentication, ...
import math import numpy as np import matplotlib.pyplot as plt def getParetoFitness(objectivePair): """ Determines and returns the pareto fitness based on the proportional distance of a given point""" objectiveCoverVal = objectivePair[1] / coverMax #Special Case i = 0#-1 foundPerp = Fals...
# coding: utf-8 from __future__ import unicode_literals from numpy.testing import assert_almost_equal, assert_array_almost_equal import pytest from pytest import approx from spacy.gold import GoldParse from spacy.scorer import Scorer, ROCAUCScore from spacy.scorer import _roc_auc_score, _roc_curve from .util import ge...
# -*- coding: utf-8 -*- # ***************************************************************************** # NICOS, the Networked Instrument Control System of the MLZ # Copyright (c) 2009-2021 by the NICOS contributors (see AUTHORS) # # This program is free software; you can redistribute it and/or modify it under # the t...
#!/usr/bin/env python __author__ = "<NAME> <<EMAIL>>, <NAME> <<EMAIL>>" __copyright__ = "Copyright 2016, Cisco Systems, Inc." __license__ = "Apache 2.0" # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the Li...
from django.utils.timezone import now from django.utils.deprecation import MiddlewareMixin import logging import traceback from time import perf_counter # Matches response time browsers return more accurately than now() def get_remote_addr(request): """ Get IP address of user making request can be used for othe...
import shutil import subprocess from itertools import zip_longest import bs4 import requests from .constants import * def test(args): contest, problem_letter = translate_problem_name(args.problem) problem = contest + problem_letter if not os.path.exists('in'): os.makedirs('in') if not os.pa...
import numpy as np class SudokuState: # dict of constraints, RCV as keys get_constraints = {} # Populate get_constraints for r in range(9): block_y = r // 3 for c in range(9): block_x = c // 3 b = (block_y * 3) + block_x for v in range(1, 10): ...
import calendar import datetime import random import requests from flask import request, abort from home.core.models import get_device from home.iot.speech import Speech, message, part_of_day from home.web.utils import api_auth_required from home.web.web import app BASE_URL = "http://api.openweathermap.org/data/2.5/...
# The MIT License (MIT) # # Copyright (c) 2018 <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, me...
#!/usr/bin/python """Collection Objects Every object follows the standard collection interface and maps some key to an item The user should select the appropriate key when passing items or use zip, map, and a key_getter The key will be interpreted as a byte array and split on char unless configured otherwise. This P...
#This script invokes the ohter web jobs in a simulation mode. Every time it runs, it passes a new date to the other web jobs. #For example, if this script is scheduled to run once every hour, the data and results of one day will be generated every hour. #This script invokes the other web jobs in the order of Simulator...
import logging import sys import os import numpy as np import pickle import tvm import topi from topi.testing import conv2d_nchw_python from tvm import te from tvm import autotvm from tvm.autotvm.tuner import XGBTuner, GATuner, RandomTuner, GridSearchTuner import tvm.contrib.graph_runtime as runtime #from tvm.autotvm...
import dataclasses import functools import sys from dataclasses import dataclass from collections import defaultdict from datetime import datetime from typing import Dict, Type, Any, TYPE_CHECKING from bxcommon import constants from bxcommon.utils import memory_utils from bxcommon.utils.sizer import Sizer from bxcomm...
import string import re from nltk.corpus import stopwords from nltk.tokenize import word_tokenize from nltk import WordNetLemmatizer from keras import Sequential from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras import layers from sklearn.model_selection i...
# encoding=utf-8 import email import re from typing import Match, NamedTuple, Union, cast from deprecated import deprecated from hamcrest import anything from hamcrest.core.base_matcher import BaseMatcher from hamcrest.core.description import Description from hamcrest.core.helpers.wrap_matcher import wrap_matcher from...
#!/usr/bin/env/python ''' Client for interacting with the Voxel51 Vision Services API. | Copyright 2017-2019, Voxel51, Inc. | `voxel51.com <https://voxel51.com/>`_ | ''' # pragma pylint: disable=redefined-builtin # pragma pylint: disable=unused-wildcard-import # pragma pylint: disable=wildcard-import from __future__ i...
# Copyright (c) 2015-present, Facebook, Inc. # All rights reserved. import os,glob import json import pandas as pd import pickle import random from PIL import Image from torch.utils.data import Dataset from torchvision import datasets, transforms from torchvision.datasets.folder import ImageFolder, default_loader fro...
class _FieldConfig: def __init__(self, accessor, default): if not callable(accessor): raise TypeError('accessor must be callable') if type(default) is not bool: raise TypeError('default must be bool') self.accessor = accessor self.default = default def _fe...
import os from peewee import SqliteDatabase from backup.db.domain import * from enum import Enum from backup.core.luke import FileEntryDTO from backup.common.progressbar import create_pg class BackupDatabaseWriter: def __init__(self, backup_root): self.backup_root = backup_root self.files = dic...
# Copyright (C) 2019 The Raphielscape Company LLC. # # Licensed under the Raphielscape Public License, Version 1.c (the "License"); # you may not use this file except in compliance with the License. # # Asena UserBot - <NAME> """ Bu modül commit sayısına bağlı olarak botu günceller. """ from os import remove, execl...
import json from app.document_retrieval import DocumentRetriever from app import utils, models from app.general_align_reader import GeneralAlignReader align_reader = GeneralAlignReader() doc_retriever = DocumentRetriever() plm = models.PLM() def get_links(editions, verse_id, edition_token_offset): links = [] ...
from typing import Callable, Type, Union import torch from einops import rearrange from torch import Tensor, einsum from torch.nn import Conv1d, Conv2d, Conv3d, Module from torch.nn.functional import conv1d, conv2d, conv3d, unfold def get_conv_module(N: int) -> Type[Module]: """Return the PyTorch module class of...
import argparse import torch from torch import nn import torch.nn.functional as F from torchvision import models, transforms, utils import torchvision.transforms.functional as TF import numpy as np from matplotlib import pyplot as plt from PIL import Image import requests parser = argparse.ArgumentParser(description...
from rect import Line, Rect, rects, at_right_angle, get_cycle def _standard_rect(r): return min( # forward: a -> b -> c -> d (r.a, r.b, r.c, r.d), (r.d, r.a, r.b, r.c), (r.c, r.d, r.a, r.b), (r.b, r.c, r.d, r.a), # opposite: d -> c -> b -> a (r.d, r.c, r.b,...
# Copyright (c) nexB Inc. and others. All rights reserved. # http://nexb.com and https://github.com/nexB/scancode-toolkit/ # The ScanCode software is licensed under the Apache License version 2.0. # Data generated with ScanCode require an acknowledgment. # ScanCode is a trademark of nexB Inc. # # You may not use this ...
"""coding=utf-8 Copyright 2020 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 ...
from typing import List, Optional from django.contrib import admin from django.contrib.postgres.fields import ArrayField from import_export import fields, widgets from import_export.admin import ImportExportMixin from import_export.resources import ModelResource from rangefilter.filter import DateRangeFilter from eah...
import re import psycopg2 import sys import datetime import os import json #save a record to db. def save_rec(tid, rec, cursor, record_cnt, connection): if rec['agent'] == 'Zoho Monitor' or rec['agent'] == 'Site24x7'\ or rec['user'] == 'dexterpratt' or rec['user'] == 'cjtest'\ or rec['user'...
from __future__ import absolute_import import datetime class CursorResult(object): def __init__(self, results, next, prev=None, has_prev=None, has_next=None): self.next = next self.prev = prev self.has_next = has_next self.has_prev = has_prev self.results = results de...
import scipy as sp import torch from torch import nn import aljpy import hashlib import json import pandas as pd import numpy as np import matplotlib.pyplot as plt import aljpy.plot from pavlov import runs from boardlaw import analysis, arena from . import plot, data from tqdm.auto import tqdm import plotnine as pn fro...
from numpy import array, sort, nan from numpy.random import permutation, randint import scipy.stats as st def compareOneSubjectClass(countsInAffected,countsInUnaffected,nullI=0,bootstrapI=0): '''Compares a subject variant class in two groups of children using a normalization variant class. The two groups o...
#!/usr/bin/env python3 # Copyright The Cloud Custodian Authors. # SPDX-License-Identifier: Apache-2.0 """ Cli tool to package up custodian lambda policies for folks that want to deploy with different tooling instead of custodian builtin capabilities. This will output a set of zip files and a SAM cloudformation templat...
""" test_matrix_stability.py For systems with very slow kinetics, the conventional matrix solvers seem to have trouble computing first passage times due to poor matrix conditioning. Recreates the problem and test matrix solutions that will remain stable for milestoning matrices with long timescales. """ import os imp...
import argparse import ctypes import numpy as np from PIL import Image parser = argparse.ArgumentParser(exit_on_error=False) parser.add_argument('input', type=argparse.FileType('rb')) args = parser.parse_args() TILE_WIDTH_SHIFT = 3 TILE_HEIGHT_SHIFT = 3 TILE_WIDTH = 1<<TILE_WIDTH_SHIFT TILE_HEIGHT = 1<<TILE_HEIGHT_SH...
# -*- coding: utf-8 -*- import os import re import sys import urllib if sys.version_info[0] >= 3: from urllib.request import urlretrieve, urlopen #from urllib.request import urlopen else: from urllib import urlretrieve, urlopen # third-party modules import imgurpython as imgur # local imports import settin...
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the ...
""" This module of config objects should be backwards compatible to Docker Engine API 1.25. If future APIs are not backwards compatible in terms of config objects, then the user of this library will instead import a different module of config files or other config objects. """ from dataclasses import dataclass, field ...
# -*- coding: utf-8 -*- from __future__ import annotations from itertools import chain, islice from typing import TYPE_CHECKING import numpy as np from numpy.random import RandomState from sklearn.model_selection._split import StratifiedGroupKFold, _BaseKFold from skmultilearn.model_selection import IterativeStratif...
# -*- coding: utf-8 -*- import re import grab import lxml.html import toolkit H_TAGS = ['h{}'.format(i) for i in range(1, 7)] TAGS_TO_SEPARATE = H_TAGS + ['p', 'li', ] TAGS_PARAGRAPHS = H_TAGS + ['p', ] MANY_LINE_ENDINGS = re.compile('(\n|\r\n){3,}') TRASH_SPACES = re.compile(' {2,}') TRASH_SYMBOLS = re.compile('[...
# Copyright 2015-2016 Internap. # # 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...
import re # Solution def part1(data): return process_find_divisors_algorithm(data) def part2(data): return process_find_divisors_algorithm(data, [1, 0, 0, 0, 0, 0]) def process_commands_naive(data, initial_state=None): ip, commands = read_data(data) cpu = CPU(initial_state) ip_value = 0 wh...
import discord,asyncio,time,random,names,requests as rq,pymongo,os,json from discord.ext.commands.cog import Cog from discord.ext import commands from discord.ext.commands import command from discord.utils import sleep_until import datetime from discord.ext import tasks class Events(commands.Cog,name='Events'): d...
import datetime import json import logging import os import urllib.parse from typing import Optional, Dict, Any import aws_embedded_metrics import boto3 import botocore.client from aws_embedded_metrics.logger.metrics_logger import MetricsLogger STATIC_HEADERS = { "Content-Type": "text/plain; charset=utf-8", "...
''' A module that holds blueprint and views for authorization pages ... Methods ------- ''' import functools from flask import Blueprint, redirect, render_template, request, session, flash, url_for, g from werkzeug.security import check_password_hash, generate_password_hash import requests import re from unishare....
import pandas as pd import numpy as np import matplotlib.pyplot as plt plt.style.use('seaborn') from Status import * from BackTest import BackTest def plot_dmac(stock, plt_df, plot_full_location, cur_descp): words = cur_descp.split(" ", 1) values = words[1].replace('(', '').replace(')', '') v...
# Minus is Jump plus automated downloader and archiver. # (C) 2020 <NAME> (@Adolfoi_) All rights reserved. # LICENCE: MIT License from selenium import webdriver from PIL import ImageGrab from pynput.keyboard import Key, Controller from selenium.common.exceptions import NoSuchElementException import time impor...
""" These are automatically used without having to update anything else. The TOSCA variables are mapped to the SOL6 ones, they must have the same names. The program does not attempt to map variables beginning with '_' """ from mapping_v2 import * import logging log = logging.getLogger(__name__) class PathMapping: ...
import torch import torch.nn as nn class GoogLeNet(nn.Module): def __init__(self, in_channels=3, num_classes=1000, conv_block=None): super(GoogLeNet, self).__init__() self.in_channels = in_channels self.num_classes = num_classes if conv_block is None: self.conv...
# C O D E A Z / Samil """ Alive """ import asyncio import platform import sys import time from telethon import events from asyncio import create_subprocess_exec as asyncrunapp from asyncio.subprocess import PIPE as asyncPIPE from datetime import datetime from os import remove from platform import python_version, uname...
import os import argparse import pickle import numpy as np import random import time import torch import torch.nn.functional as F from torch_geometric.datasets import Coauthor, CitationFull, TUDataset from torch_geometric.data import Data from torch_geometric.utils import to_networkx, degree, k_hop_subgraph # citat...
import numpy as np from keras.models import Sequential, Model from keras import initializers from keras.initializers import normal, identity from keras.layers.core import Dense, Dropout, Activation, Flatten from keras.layers import Input, Concatenate from keras.layers.recurrent import LSTM from keras.optimizers import ...
import asyncio from typing import List from app.models.lightning import ( GenericTx, Invoice, LightningInfoLite, LnInfo, NewAddressInput, OnChainTransaction, Payment, PaymentRequest, SendCoinsInput, SendCoinsResponse, ) from app.utils import SSE, lightning_config, send_sse_messa...
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import dataset from core.networks import * from core.datasets import * from tools.general.io_utils import * from tools.general.time_utils import * from tools.general.json_utils import * from tools.general.Q_...
#!/usr/bin/env pluginwrapper3 import json import logging from base64 import urlsafe_b64decode from copy import deepcopy from datetime import datetime import jwt import requests from safeguard.sessions.plugin import AAResponse from safeguard.sessions.plugin.mfa_client import ( MFAClient, MFAAuthenticationFail...
# Copyright 2010 Google 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 to in writing, ...
""" Contains the base Controller class. """ import azcam from azcam.tools.console_tools import ConsoleTools from azcam.tools.header import Header, ObjectHeaderMethods from azcam.tools.tools import Tools class Controller(Tools, ObjectHeaderMethods): """ Base class for controller tool. Attributes: ...
# Copyright © VASP Software GmbH, # Licensed under the Apache License 2.0 (http://www.apache.org/licenses/LICENSE-2.0) import functools import numpy as np from py4vasp.data._base import RefinementDescriptor import py4vasp.data._export as _export from py4vasp.data._selection import Selection as _Selection import py4vasp...
"""AaC Plugin implementation module for the aac-gen-gherkin-behaviors plugin.""" # NOTE: It is safe to edit this file. # This file is only initially generated by the aac gen-plugin, and it won't be overwritten if the file already exists. from iteration_utilities import flatten from aac import parser, util from aac.p...
import os import sys import argparse import configparser # TODO: (johngiorgi): use the supported datatypes functions for bools: https://docs.python.org/3.6/library/configparser.html#supported-datatypes # TODO: (johngiorgi): is there a better way to specify multiple filepaths def config_parser(config_filepath): ""...
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from stable_baselines3.common.running_mean_std import RunningMeanStd class Discriminator(nn.Module): def __init__(self, intention_dim, state_dim, action_dim, hidden_dim=64): super(Discriminator, self).__init__() ...
#--------------------------------------------------------------------------- # # Reformats the llrpdef.xml file into a Python-formatted description llrpdef.py # # The reason we so this is so we avoid a dependency on the xml parser in deployment. # It is also much faster to use the .pyc file rather than parsing XML agai...
''' Miscellaneous helper functions ''' import sys import matplotlib.pyplot as plt import numpy as np import cv2 import torch # For clustering & centroid detection from scipy import ndimage as ndi from skimage.feature import peak_local_max def show_image(window, img, delay=0): cv2.imshow(window, img) # Esca...
# coding=utf-8 import os as os import collections as col import numpy as np import pandas as pd from crplib.auxiliary.hdf_ops import get_default_group,\ get_chrom_list from crplib.auxiliary.file_ops import create_filepath from crplib.numalg.normalization import nonzero_qnorm from crplib.metadata.md_signal import ...
import xml.etree.ElementTree as ET from .leaf_element import LeafElement, Element class SceneFile (Element): def __init__(self): Element.__init__(self, 'Experiment') self.attributes['version'] = 2.0 def add_spatial_query(self): self.spatial_query = SpatialQuery() self.sub_ele...
# coding: utf-8 import argparse import time import math import torch import torch.nn as nn import torch.onnx import numpy as np import data from sklearn.utils import shuffle import model import os # cuda device os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" os.environ['CUDA_VISIBLE_DEVICES']='3' def get_args(): p...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2009 <NAME> # # Distributed under the MIT license (See accompanying file # LICENSE.txt or copy at http://jagpdf.org/LICENSE.txt) import jag.testlib as testlib import jagpdf def check_font_metrics(doc): f1 = doc.font_load("standard; name=Helvetica; siz...
import itertools from package.models import Category, Project, PackageExample, ProjectImage from package.utils import prepare_thumbnails from profiles.models import Account from django.core.exceptions import ValidationError from django import forms from django.forms.formsets import formset_factory from django.forms.m...
import traceback import cv2 import numpy as np import sys import argparse from datetime import datetime import os # Gaze estimation # https://github.com/david-wb/gaze-estimation # Install steps: # cd .. # git clone https://github.com/david-wb/gaze-estimation # cd gaze-estimation; ./scripts/fetch_models.sh # Status: ...
import argparse import qt import requests import docscraper from functools import partial import threading class EasyLayout(): """Base class for layout wrappers. These wrappers provide several conveniences: 1. Constructor takes margin as a keyword argument so it can easily be changed. 2. Margin defaults to ...
""" profiles.py Contains definitions of BM3DStages and BM3DProfiles classes, as well as several predefined BM3DProfile subclasses. """ import enum class BM3DStages(enum.Enum): HARD_THRESHOLDING = 1 WIENER_FILTERING = 2 # Pass a hard-thresholding estimate to the function instead of WIENER_FILTERIN...
from numpy import * import nlopt import numpy as np import matplotlib.pyplot as plt import numbers import math import pandas as pd import random import autograd.numpy as ag from autograd import grad from mpl_toolkits.mplot3d import Axes3D from numpy.lib.function_base import vectorize from autograd import value_and_grad...
# Space Invaders import turtle import os import math import random # To make the enemy start from random positions # Set up the screen wn = turtle.Screen() wn.bgcolor("black") wn.title("Space Invaders") wn.bgpic("space_invader_background.gif") # Register the shapes turtle.register_shape("invader.gif") turtle.registe...
# pylint: disable=non-parent-init-called # -*- coding: utf-8 -*- # # ramstk.gui.gtk.ramstk.Entry.py is part of the RAMSTK Project # # All rights reserved. # Copyright 2007 - 2017 <NAME> doyle.rowland <AT> reliaqual <DOT> com """RAMSTK Entry Module.""" # Standard Library Imports from datetime import datetime from...
# A part of NonVisual Desktop Access (NVDA) # Copyright (C) 2006-2021 NV Access Limited, <NAME>, <NAME> # This file is covered by the GNU General Public License. # See the file COPYING for more details. """A module used to record Windows versions. It is also used to define feature checks such as making sure NVD...
import argparse import functools import json import os import wave from collections import Counter import librosa import soundfile from tqdm import tqdm from data.utility import add_arguments, print_arguments from data_utils.normalizer import FeatureNormalizer parser = argparse.ArgumentParser(description=__doc__) ad...
# Author <NAME> from XJTU(<EMAIL>) # inference import tensorflow as tf import os import time import cv2 import numpy as np import sys from erf_net import ERF_Net from erf_net_slim import * from train_slim import * from data_load import instance_generator from config import cfg from IOU_metrics import * FLAGS = tf.a...
#!/usr/bin/python3 # query_generator.py # Date: 15/09/2021 # Author: <NAME> # Email: <EMAIL> import logging import pathlib from distutils.dir_util import copy_tree from pathlib import Path from shutil import copyfile import numpy as np import pandas as pd from dqgen.adapters.ap_reader import read_ap_from_csv from ...
import unittest from pathlib import Path from docx import Document from docx.enum.text import WD_COLOR_INDEX from docx.shared import Pt from nsb_toolbox import tables data_dir = Path(__file__).parent / "test_data" class TestInitializeTable(unittest.TestCase): def _check_table_characteristics(self, document, nro...
__author__ = '<NAME> [IPPM]' import os import re import subprocess import shutil import time import copy import sys import networkx as nx from cada033 import * def test_1(): G = nx.DiGraph() G.add_edge(1, 2) print(G.nodes()) print(G.edges()) exit() def print_graph_structure(G): print(G.nodes...
import torch from torch import nn import torch.nn.functional as Fu class AdaIn(nn.Module): def __init__(self, latent_dims=128, gf_dim=64): super(AdaIn, self).__init__() self.gf_dim = gf_dim self.mlp = nn.Sequential(nn.Linear(latent_dims, 2*gf_dim), nn.ReLU()) self.instNorm = nn.Ins...
# Copyright 2020 - 2021 MONAI Consortium # 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...
#!/bin/env python # Copyright 2021 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 agre...
# Authors: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # # License: Simplified BSD import time class IntSlider(object): """Class to set a integer slider.""" def __init__(self, plotter=None, callback=None, first_call=True): self.plotter = plotter self.callback = ca...
from lsd import LsdExtractor from scipy.ndimage import gaussian_filter, convolve, maximum_filter import h5py import logging import mahotas import numpy as np import time logging.basicConfig(level=logging.INFO) logging.getLogger('lsd.local_shape_descriptor').setLevel(logging.DEBUG) k_z = np.zeros((3, 1, 1), dtype=np.f...
import os from datetime import datetime from logging import getLogger, Logger from typing import Dict, Any, List import json import jwt import requests from requests.exceptions import HTTPError BASE_URL: str = 'https://api.liquid.com' """API Base URL""" SIDE_BUY: str = 'buy' """Side: buy""" SIDE_SELL: str = 'sell...
"""Utility functions.""" import inspect import logging from typing import Any, List, Optional, cast, Iterable, Set, Dict from homebot.validator import is_iterable_but_no_str def make_list(value: Any, null_empty: bool = True) -> Optional[List[Any]]: """ Makes a list out of the given value. If value is a list,...
#!/usr/bin/python2.4 # Copyright 2009 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required ...
import numpy as np from scipy.spatial.distance import cdist, pdist, squareform def apply_sequence_kernel(seq_emb, kernel_radius=1, eplison=0.01): ''' Method applies fuzzy graph kernels to sequence vectors. This is used to naively propagate local information of neighbors within a specified kernel radius. Al...
import logging import os import sys import httpx from coverage_comment import badge, comment_file from coverage_comment import coverage as coverage_module from coverage_comment import ( github, github_client, log, settings, subprocess, template, wiki, ) def main(): logging.basicConfi...
from django.db.utils import IntegrityError from django.conf import settings from django.utils.decorators import method_decorator from django.utils.translation import ugettext_lazy as _ from django.views.decorators.debug import sensitive_post_parameters from rest_framework.views import APIView from rest_framework.respo...
import numpy as np import pytest import xarray as xr from dask import is_dask_collection from xskillscore.core.resampling import ( _gen_idx, resample_iterations, resample_iterations_idx, ) resample_iterations_funcs = [resample_iterations, resample_iterations_idx] ITERATIONS = 2 def assert_dim_coords(a, ...
#!/usr/bin/env python # coding: utf-8 # Copyright (c) 2021 Huawei Device 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 ...
"""training should invoke this function""" import numpy as np from functools import partial import torch from torch import nn, FloatTensor from torch.utils.data import TensorDataset, DataLoader from tang_jcompneuro import training from .cnn_aux import get_loss, get_optimizer from scipy.stats import pearsonr def eval...