text
stringlengths
2
999k
""" Functions to map between the coordinates in image pixel space and geographical coordinates. """ import logging from typing import Tuple from types import MethodType # for binding a method dynamically to a class import numpy from . import geocoords from ..io.complex.sicd_elements.blocks import Poly2DType, XYZPol...
# -*- coding: utf-8 -*- # Copyright 2020 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
import datetime import requests class TDException(Exception): def __init__(self, error): self.error = error def __str__(self): return self.error error_400 = TDException('Bad request') error_401 = TDException('Unauthorized') error_404 = TDException('Treasury data not found') error_429 = TDExcep...
# # Copyright 2015 SUSE 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, softw...
# coding=utf-8 # author uguisu import numpy as np import tensorflow as tf from tensorflow.python.framework.errors_impl import InvalidArgumentError def matrix_001(): print('\n- 矩阵转置 ------------------------') # 矩阵转置 np_array = np.array([[1., 2., 3.], [4., 5., 6.]]) tensor_a = tf.constant(np_array, dty...
import urllib, zipfile, os, csv, time, glob from datetime import date # Clear the data directories so you can download fresh files def clear_data_directory(): zipfiles = glob.glob("data/*.zip") for f in zipfiles: os.remove(f) csvfiles = glob.glob('data/csv/*.csv') for f in csvfiles: ...
import numpy as np import matplotlib.pyplot as plt # target = 100 size = 20 # alpha = 1 # beta = 1.0/target lam = 0.2 # target = 0.5 # target = 2.5*lam # beta = 1 / lam # beta = 1 / lambda Y = np.random.exponential(beta, size) # plt.plot(x, Y, 'b-') # plt.plot(x[:size], Y, 'r.') # # plt.plot(x[:size], simulated_dat...
# Copyright (c) 2021 Institute for Quantum Computing, Baidu 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 # # U...
# 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 or agreed to...
from celery import Celery import os #實例化對象 if not os.getenv('DJANGO_SETTINGS_MODULE'): # 如果没有该环境变量 # os.environ = {'DJANGO_SETTINGS_MODULE': 'meiduo_mall.settings.dev'} os.environ['DJANGO_SETTINGS_MODULE'] = 'meiduo.settings.dev' celery_app = Celery() #配置路徑 celery_app.config_from_object('celery_tasks.confi...
from pypy.interpreter.mixedmodule import MixedModule import os _WIN = os.name == "nt" class Module(MixedModule): applevel_name = 'time' interpleveldefs = { 'time': 'interp_time.time', 'clock': 'interp_time.clock', 'ctime': 'interp_time.ctime', 'asctime': 'interp_time.asctime'...
from precise.skaters.covarianceutil.covrandom import random_band_cov from precise.skaters.portfoliostatic.hrpport import hrp_unit_unit_s5_port import numpy as np def test_parity(): cov = random_band_cov() print(np.shape(cov)) w = hrp_unit_unit_s5_port(cov=cov) print(sum(w))
""" Author: Marcos Oliveira Github: https://github.com/the-physicist Date: 18/10/21 """ # 7 - Faça um Programa que calcule a área de um quadrado, em seguida mostre o dobro desta área para o usuário. lado = float(input("Qual o comprimento do lado do quadrado? \n")) area = lado * lado area_dobro = area * 2 print("...
from dash import dcc from dash import html import feffery_antd_components as fac import feffery_utils_components as fuc docs_content = html.Div( [ html.H2( 'AntdHeader(id, className, style, *args, **kwargs)', style={ 'borderLeft': '4px solid grey', 'p...
import cv2 import cv import caffe import numpy as np import ast import datetime import time class ImshowLayer(caffe.Layer): def setup(self, bottom, top): assert len(top) == 0, 'ImshowLayer has no output.' self.param_ = ast.literal_eval(self.param_str) if 'resize' not in self.param_ or self....
from base import *
# from .bert_graph import BERTGraph import torch.nn as nn from .bert import BERT import pdb import torch class CORAL(nn.Module): """ CORAL: Code representation learning """ def __init__(self, bert: BERT, n_topics=5): super(CORAL, self).__init__() self.n_topics = n_topics # ...
{ "targets": [ { "target_name": "numname", "sources": [ "./cpp/numname.cpp", "./cpp/numname_wrap.cpp" ], "include_dirs": [ "<!(node -e \"require('nan')\")" ] } ] }
from typing import Iterable, List, Tuple from unittest import TestCase from blspy import AugSchemeMPL, BasicSchemeMPL, G1Element, G2Element from tranzact.types.blockchain_format.program import Program from tranzact.types.blockchain_format.sized_bytes import bytes32 from tranzact.types.coin_spend import CoinSpend from...
# Not enough detections? # https://community.lsst.org/t/detectcoaddsource-detection-threshold-on-noisy-background-data/3050 #from lsst.meas.algorithms import SourceDetectionTask #config.detection.retarget(SourceDetectionTask) #use simpler detection algorithm config.detection.thresholdType='stdev' #default=stdev config....
''' Selection sort is an O(n^2) sorting algorithm. The logic is to go over the array from arr[1] to arr[n-1], compare it with the elements to the left, and swap it into the right position (if a swap is needed). At the end of the kth iteration, the element arr[k] will be in the right position considering only the elem...
# -*- coding: utf8 -*- # Copyright (C) 2013 Daniel Lombraña González # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. #...
#!/usr/bin/env python3 """StackOverflow keywords collector.""" import requests import daiquiri from f8a_tagger.keywords_set import KeywordsSet import libarchive import xmltodict from .base import CollectorBase _logger = daiquiri.getLogger(__name__) class StackOverflowCollector(CollectorBase): """StackOverflow...
#!/usr/bin/env vpython3 # Copyright 2018 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Runs WPT as an isolate bundle. This script maps flags supported by run_isolate_script_test.py to flags that are understood by WPT...
#!/usr/bin/env python3 # Output the value for the buttons. # The library used py-tm1638 (https://github.com/johnblackmore/py-tm1638) # TM1638 import TM1638 import time # These are the pins the display is connected to. Adjust accordingly. # In addition to these you need to connect to 5V and ground. DIO = 17 CLK = 21...
"""YAML-enabled Pydantic models.""" __all__ = [ "__version__", "yaml", "YamlEnum", "YamlInt", "YamlIntEnum", "YamlStr", "YamlStrEnum", "YamlModel", "YamlModelMixin", "YamlModelMixinConfig", "SemVer", "VersionedYamlModel", ] from .compat.old_enums import YamlEnum from .c...
from __future__ import annotations import os from pathlib import Path from typing import Dict, List, Optional, Union import python_on_whales.components.service.cli_wrapper import python_on_whales.components.task.cli_wrapper from python_on_whales.client_config import DockerCLICaller from python_on_whales.utils import ...
# SPDX-License-Identifier: BSD-3-Clause # Copyright(c) 2020 Ericsson AB import logging import paf.sd as sd DEFAULT_LOG_CONSOLE = False DEFAULT_LOG_SYSLOG = True DEFAULT_LOG_FACILITY = logging.handlers.SysLogHandler.LOG_DAEMON DEFAULT_LOG_FILTER = logging.INFO class Error(Exception): def __init__(self, message)...
#!/usr/bin/env python # -*- coding: utf-8 -*- import re, os for line in open ('watchdogs.txt').readlines(): line = line.strip() if len(line) != 0: match = re.search ('(?P<path>.*)/(?P<boot>Boot_0\d+)/.*', line) boot = match.group ('boot') num = re.search ('Boot_(?P<num>\d\d...
from __future__ import print_function import itertools import functools import sys import numba.unittest_support as unittest from numba.compiler import compile_isolated, Flags from numba import jit, typeof, errors, types, utils from .support import TestCase enable_pyobj_flags = Flags() enable_pyobj_flags.set("enable...
# # spyne - Copyright (C) Spyne contributors. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This libra...
# Copyright (c) 2020, NVIDIA CORPORATION. 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 conditions a...
from binary_search import binary_search # import pytest def test_binary_search_with_valid_input_in_list(): ''' tests array with a valid case of search key being in array ''' assert binary_search([1,2,3,4,5,6,7], 6) == 5 def test_binary_search_with_valid_but_not_included_input_in_list(): ''' te...
#!/usr/bin/env python3 # Copyright 2019 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'wiki.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportErr...
import time from bs4 import BeautifulSoup import requests import pymysql.cursors import unittest from validate_email import validate_email class UnitTestsDataMinerYellowPagesGilbraltar(unittest.TestCase): def test_extract_one_email(self): url = "https://gibyellow.gi/biz/Eliott-Hotel-1901" # Reque...
############################################################################## # Copyright by The HDF Group. # # All rights reserved. # # # # Th...
""" Linear regression is the most basic type of regression commonly used for predictive analysis. The idea is pretty simple: we have a dataset and we have features associated with it. Features should be chosen very cautiously as they determine how much our model will be able to make future predictions. We try to set th...
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) """ Spack allows very fine-grained control over how packages are installed and over how they are built and configured. To...
from django.conf import settings MEDIA_PREFIX = getattr(settings, 'NEXUS_MEDIA_PREFIX', '/nexus/media/') if getattr(settings, 'NEXUS_USE_DJANGO_MEDIA_URL', False): MEDIA_PREFIX = getattr(settings, 'MEDIA_URL', MEDIA_PREFIX)
import functools def log_info(func): @functools.wraps(func) def wrapper(*args, **kwargs): print("Wywołuję funkcję...") result = func(*args, **kwargs) print("Już po wszystkim :)") return result return wrapper @log_info def calculate_sum(a, b): return a + b def run_...
#!/usr/bin/python3 import sys # dueling generators # two generators, A and B # same algorithm: take prev value, multiply by factor, # divide by 2147483647, keep remainder # generator A uses factor of 16807, B uses 48271 # example: A starts with 65 and B starts with 8921 # if lowest 16 bits of both values match, incr...
from einfachjabber import create_app app = create_app('../development.py') app.run(host='0.0.0.0')
#!/usr/bin/env python """ Integration tests. """ import argparse import difflib import json import logging import subprocess import sys from pathlib import Path from mypy_boto3_builder.utils.nice_path import NicePath ROOT_PATH = Path(__file__).parent.parent.resolve() EXAMPLES_PATH = ROOT_PATH / "examples" PYRIGHT_SNA...
""" Entry point four our twitoff flask app """ #Run this out of TWITOFF folder from .app import create_app #.app porque esta en la misma carpeta APP = create_app()
from numbers import Integral, Real from math import exp, erf, pi, sqrt import h5py import numpy as np from . import WMP_VERSION from .data import K_BOLTZMANN import openmc.checkvalue as cv from openmc.mixin import EqualityMixin # Formalisms _FORM_MLBW = 2 _FORM_RM = 3 # Constants that determine which value to ac...
import io import time from starlette.datastructures import Headers, MutableHeaders from starlette.types import ASGIApp, Message, Receive, Scope, Send class CompressionMiddleware: def __init__( self, app: ASGIApp, compression_registry, minimum_size: int = 500, ) -> None: ...
import sys class HotwordProcess: def __init__(self, args = {}): if args.hotword == "run": print() # Valor da Classe self.value = 0 self.maxIter = 10 def _setup(self): print("Inicializando hotword") def _loop(self): self.value = self.value + 1 print("Iteracao: {} / {}".format(self.value, s...
''' Create a binary file with name and roll number. Search for a given roll number and display the name, if not found display appropriate message. ''' import pickle import os from utils import drive_menu students = {} filename = '' def init(path: str) -> None: ''' Load the file. If file does not exist, creates...
from setuptools import setup, find_packages from os import path from io import open here = path.abspath(path.dirname(__file__)) reqs = [] with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() with open(path.join(here, '.version'), encoding='utf-8') as f: version = f.read...
import os import json import numpy as np from utils import calibrate def read_binary(i_frame, path, config): """ Reads IQ sampled data from one cascade capture device. Returns ADC_samples: shape (chirp_samples, n_chirps, n_capture_transmitters, n_receivers) """ factors = [config['numSamplePerChi...
import torch import utility import data import model import loss from option import args from trainer import Trainer #torch.set_printoptions(profile="full") torch.manual_seed(args.seed) checkpoint = utility.checkpoint(args) if args.data_test == 'video': from videotester import VideoTester model = model.Model...
# Licensed under a 3-clause BSD style license - see LICENSE.rst import pytest import numpy as np from numpy.testing import assert_allclose from astropy.table import Table from gammapy.datasets import Datasets, FluxPointsDataset from gammapy.estimators import FluxPoints from gammapy.modeling import Fit from gammapy.mode...
import os import pickle import torch from torch.utils.data import Dataset from torchtext.datasets import IMDB from torchtext.data import RawField from tqdm import tqdm from datasets import Vocabulary from datasets.utils import TwoWayDict class IMDBDataset(Dataset): def __init__(self, examples, vocab, one_hot=Tr...
"""Tests for Registration.""" from django.test import TestCase from django.urls import reverse from django.contrib.auth.models import User class RegistrationViewTests(TestCase): """Tests for sign in and sign up.""" def setUp(self) -> None: self.credentials = { 'username': 'tester', ...
from __future__ import annotations from typing import List import math import random ## import pytest # Implement Merge Sort Algorithm # ============================== # Constants # --------- INF = math.inf RAND_START = 100 RAND_END = 50300 def mergeSort(l: List) -> List: """ Merge sort algorithm. Sort is d...
#!/usr/bin/env python3 # Day 19: Search in Rotated Sorted Array # # Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. # (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). # You are given a target value to search. If found in the array return its index, otherwise return -...
import unittest import json import pkg_resources from spacenet.schemas.hello_world import HelloWorld from pydantic import ValidationError class TestHelloWorld(unittest.TestCase): def test_good_data(self): good_data = { "message": "Hello World" } hello = HelloWorld(**good_data) self.assertE...
def func(): print("func") def func_interna(): print("func_interna") func_interna() func()
from .base_rating import (ModelRecommendation as Model, LearnerRecommendation as Learner)
# Copyright 2015 NEC Corporation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable l...
# -*- coding: utf-8 -*- import pytest from pyleecan.Classes.Arc2 import Arc2 from pyleecan.Classes.Segment import Segment from pyleecan.Classes.SlotW22 import SlotW22 from numpy import pi, ndarray, cos, sin, arcsin, exp, angle from pyleecan.Classes.SurfLine import SurfLine from pyleecan.Classes.LamSlot import LamSlot...
# Generated by Django 3.0.6 on 2020-05-30 15:12 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('posts', '0005_auto_20200530_1752'), ] operations = [ migrations.AlterModelOptions( name='image', options={'ordering': ['-cre...
# Copyright 2019 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
import pytest from lcs import Perception from lcs.agents.macs.macs import Effect class TestEffect: def test_should_initialize(self): effect = Effect('1???') assert len(effect) == 4 def test_should_build_empty(self): assert Effect.empty(4) == Effect('????') @pytest.mark.parametr...
from typing import cast, Any, Dict from graphql.language import DirectiveLocation from graphql.type import ( GraphQLArgument, GraphQLBoolean, GraphQLEnumType, GraphQLField, GraphQLFloat, GraphQLInputObjectType, GraphQLInt, GraphQLInterfaceType, GraphQLList, GraphQLNonNull, G...
import torch from torch import nn import torchvision.datasets as dsets import torchvision.transforms as transforms import matplotlib.pyplot as plt import os import numpy as np import torch.utils.data as Data # Hyper Parameters EPOCH = 10 # train the training data n times, to save time, we just train 1 ep...
"""Support for EDL21 Smart Meters.""" from __future__ import annotations from datetime import timedelta import logging from sml import SmlGetListResponse from sml.asyncio import SmlProtocol import voluptuous as vol from homeassistant.components.sensor import ( PLATFORM_SCHEMA, SensorDeviceClass, SensorEn...
import os import time import logging import argparse import cv2 import numpy as np import torch import torch.backends.cudnn as cudnn import torch.nn.functional as F import torch.nn.parallel import torch.utils.data import torch.nn as nn from util import dataset, transform, config from util.util import AverageMeter, in...
# Generated by Django 2.2.7 on 2020-06-30 17:25 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='tableThree', fields=[ ('id', models.AutoFie...
import argparse import os from google.protobuf.json_format import MessageToJson from google.protobuf.wrappers_pb2 import Int32Value from farm_ng.core.blobstore import Blobstore from farm_ng.core.programd_pb2 import Program from farm_ng.core.programd_pb2 import ProgramdConfig from farm_ng.core.resource_pb2 import BUCK...
import numpy as np import csv import sys import os from sklearn.feature_extraction.text import TfidfVectorizer from collections import Counter from nltk.corpus import stopwords from snippext.dataset import get_tokenizer stopwords = set(stopwords.words('english')) class Summarizer: """To summarize a data entry p...
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2018, Will Thames <@willthames> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = r''' module: k8s_info short_description...
# -*- coding: utf-8 -*- """ kay.management :Copyright: (c) 2009 Accense Technology, Inc. Takashi Matsuo <tmatsuo@candit.jp>, All rights reserved. :license: BSD, see LICENSE for more details. Taken from django. """ import sys import os from werkzeug.utils import import_st...
# std import argparse import logging from os import fwalk, truncate import subprocess from typing import Optional from PyQt5 import QtCore from PyQt5.QtCore import * from threading import * from argparse import Namespace, ArgumentParser from pathlib import Path from typing import Tuple from PyQt5.QtWidgets import * imp...
from random import randint def opposite_direction(d): if d == 'north': return 'south' elif d == 'south': return 'north' elif d == 'west': return 'east' return 'west' def capitalize(s): return s[0].upper() + s[1:] def is_int(s): try: int(s) return True ...
""" $url rotana.net $type live $region Saudi Arabia """ import logging import re from streamlink.plugin import Plugin, pluginmatcher from streamlink.stream.hls import HLSStream log = logging.getLogger(__name__) @pluginmatcher(re.compile( r'https?://(?:www\.)?rotana\.net/live' )) class Rotana(Plugin): _hls_...
import pygame import os class GameMode: """ This is the GameMode class where other more specialized classes have to be derived from """ def __init__(self, screen, game, message, fps = 60): self.name = None self.game = game # screen properties self.screen = screen s...
import sys from PyQt5.QtWidgets import QMainWindow, QApplication from ui.uiMain import Ui_MainWindow from ui.comms import Comms if __name__ == "__main__": app = QApplication(sys.argv) comms = Comms() MainWindow = QMainWindow() ui = Ui_MainWindow(MainWindow) ui.initComms(comms) ui.initActio...
""" Django settings for example project. Generated by 'django-admin startproject' using Django 2.0.8. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ # Build path...
import datetime import logging from amitools.vamos.log import log_libmgr from amitools.vamos.atypes import Library from amitools.vamos.libcore import VLibManager from amitools.vamos.libnative import ALibManager, LibLoader from .cfg import LibCfg class LibManager(object): """the library manager handles both native...
from formulaic.parser.types import Factor, Term from formulaic.utils.calculus import differentiate_term def test_differentiate_term(): t = Term([Factor("a"), Factor("log(b)")]) assert str(differentiate_term(t, ["a"])) == "log(b)" assert str(differentiate_term(t, ["log(b)"])) == "a" assert str(differe...
from django.core.management.base import BaseCommand import os import traceback import peeringdb_server.models as pdbm import peeringdb_server.rest as pdbr import datetime import time from peeringdb_server.renderers import MetaJSONRenderer from django.conf import settings from optparse import make_option from rest_frame...
""" Hongjian Problem: use taxi flow as an independent view to predict crime. Task: 1. Get graph embedding representation of regions from taxi flow. 2. Use leaveOneOut to test the error of this single view. 3. Return a ML model on this single view, given training region ID. """ import numpy as np import st...
import math import matplotlib.pyplot as plt from .Generaldistribution import Distribution from collections import Counter import seaborn as sns class Triangular(Distribution): """ Triangular distribution class for calculating and visualizing the triangular distribution: a continuous probability distributi...
""" Wrapper for classes like `Paginator`. """ import inspect from mypy_boto3_builder.import_helpers.import_record import ImportRecord from mypy_boto3_builder.import_helpers.import_string import ImportString from mypy_boto3_builder.type_annotations.fake_annotation import FakeAnnotation class TypeClass(FakeAnnotation)...
# # PySNMP MIB module ALTIGA-NAT-STATS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ALTIGA-NAT-STATS-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:21:38 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (defau...
# Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Fixer for execfile. This converts usages of the execfile function into calls to the built-in exec() function. """ from .. import fixer_base from ..fixer_util import (Comma, Name, Call, LParen, RParen, Dot, Node, ...
import logging import torch from . import default_layers _logger = logging.getLogger(__name__) class LayerInfo: def __init__(self, name, module): self.module = module self.name = name self.type = type(module).__name__ self._forward = None class Compressor: """ Abstract b...
# coding: utf-8 import pprint import re import six class AttachEipRequest: """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value i...
# This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild from pkg_resources import parse_version import kaitaistruct from kaitaistruct import KaitaiStruct, KaitaiStream, BytesIO from enum import Enum if parse_version(kaitaistruct.__version__) < parse_version('0.9'): rais...
from django.contrib.auth import get_user_model from django.core.exceptions import SuspiciousOperation from django.db import models from django.dispatch import receiver @receiver(models.signals.pre_delete, sender=get_user_model()) def prevent_delete_user(instance, **kwargs): instance.is_active = False instance...
from .base_options import BaseOptions class TrainOptions(BaseOptions): def initialize(self): BaseOptions.initialize(self) self.parser.add_argument('--phase', type=str, default='train', help='train, val, test, etc') self.parser.add_argument('--dataroot', required=True, help='path to images...
import nose import itertools import numpy as np from climin import Sbfgs from losses import Quadratic, LogisticRegression, Rosenbrock @nose.tools.nottest def test_sbfgs_quadratic(): obj = Quadratic() opt = Sbfgs(obj.pars, obj.f, obj.fprime) for i, info in enumerate(opt): if i > 50: ...
import torch def compute_mae(pred_mask: torch.Tensor, gt_mask: torch.Tensor) -> torch.Tensor: """ :param pred_mask: (H x W) or (B x H x W) a normalized prediction mask with values in [0, 1] :param gt_mask: (H x W) or (B x H x W) a binary ground truth mask with values in {0, 1} """ return torch.mea...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os, sys import argparse from pprint import pprint from core import config from core import utils from modules import fofa from modules import shodan from modules import censys __author__ = '@j3ssiejjj' __version__ = 'v1.0' options = {} def parsing_argument(args...
from typing import Any, Mapping, TypedDict import airtable # Strongly typed fields. class NameFields(TypedDict): name: str class MyFields(NameFields): score: float # Example from the README. at = airtable.Airtable('BASE_ID', 'API_KEY') records = at.get('TABLE_NAME') # Get the fields of a record. record ...
# -*- coding: utf-8 -*- """ Defines unit tests for :mod:`colour.models.rgb.transfer_functions.itur_bt_709` module. """ import numpy as np import unittest from colour.models.rgb.transfer_functions import oetf_BT709, oetf_inverse_BT709 from colour.utilities import domain_range_scale, ignore_numpy_errors __author__ = '...
import unittest from pyalink.alink import * import numpy as np import pandas as pd class TestVectorMinMaxScalerTrainBatchOp(unittest.TestCase): def test_vectorminmaxscalertrainbatchop(self): df = pd.DataFrame([ ["a", "10.0, 100"], ["b", "-2.5, 9"], ["c", "100.2, 1"], ...
import numpy as np import pyproj from shapely.geometry import shape proj_str = '+proj=laea +lat_0={} +lon_0={} +ellps=sphere' def calc_area_of_polygons(clons, clats): """ Calculate the area of lat-lon polygons. We project sphere onto a flat surface using an equal area projection and then calculate ...