text
stringlengths
3.07k
12.6k
import argparse import os import torch import torchvision from torchvision import transforms import numpy as np import pandas as pd from sklearn.metrics.pairwise import euclidean_distances import config from data import WriterData import evaluation from data_transforms import PatchCrop from encoder import ResNet50Enco...
import redis import json import time class Basic_Field(object): def __init__(self): self.field_list = [] def dump(self): return self.field_list def add_fields(self,fields,field_type): if isinstance(fields,list) == False: fields = [fields] for i in field...
#!/usr/bin/python3 import telebot import threading import time import datetime import math import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.dates as mdates from matplotlib.dates import DateFormatter, SECONDLY, rrulewrapper, RRuleLocator, MINUTELY # custom from metricsPooler i...
# -*- coding: utf-8 -*- import matplotlib import matplotlib.pyplot as plt # matplotlib.use('TkAgg') matplotlib.use('agg') from core.file_manager.os_utils import ensure_folder from scripts.utils.saving import save_simulation_details def plot_loss(train_loss, test_loss, figsize=(7,5), save=True, ...
from canvas_workflow_kit import events from canvas_workflow_kit.constants import CHANGE_TYPE from canvas_workflow_kit.protocol import (STATUS_DUE, STATUS_SATISFIED, ClinicalQualityMeasure, ProtocolResult) from canvas_workflow_kit.recomm...
import numpy as np import scipy.spatial.distance from sklearn.cluster import SpectralClustering import heapq from common import baseline_retrieval from utils import tqdm ## CLUE ## def clue(features, queries, select_clusters, k = 200, max_clusters = 10, T = 0.9, min_cluster_size = 2, show_progress = False): "...
from azure.mgmt.resource import ResourceManagementClient from cloudmesh.configuration.Config import Config from cloudmesh.common.Shell import Shell from pprint import pprint import webbrowser import json import textwrap from cloudmesh.compute.libcloud.Provider import Provider from cloudmesh.common.dotdict import dotdic...
# Copyright 2017-2021 IBM Corp. 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 law or...
""" S3TC DXT1/DXT3/DXT5 Texture Decompression Original C# code: https://github.com/notscuffed/repkg/blob/master/RePKG.Application/Texture/Helpers/DXT.cs """ from enums import DXTFlags def unpack565( block: bytes, blockIndex: int, packedOffset: int, colour: bytearray, colourOffset: int, ): # B...
#-*- coding: utf-8 -*- import re import os import sys import requests import random import m3u8 import datetime import argparse import subprocess from pathlib import Path from time import sleep from datetime import datetime as dt from datetime import timedelta from threading import (Event, Thread) parser = argparse....
'''Implements interface to SteamGifts site for entering giveaways''' from __future__ import annotations import json import logging from dataclasses import dataclass import aiohttp import asyncio from tenacity import retry from tenacity.stop import stop_after_attempt from tenacity.wait import wait_fixed, wait_random fr...
from abc import ABC import csv from copy import deepcopy import numpy as np from torch.utils.data import Dataset from megatron import print_rank_0, get_args from megatron.data.mask_creation_utils import make_attention_mask def build_tokens_types_paddings_from_text(src_text, answer_text, tokenizer, max_seq_length, dec...
#!/usr/bin/env python # # Copyright (c) 2005-2009 <NAME> # # Distributed under the MIT license (See accompanying file # LICENSE.txt or copy at http://jagpdf.org/LICENSE.txt) # import jagpdf import os import sys import jag.testlib as testlib g_page_margin = 30 g_pad = 4 g_ptsize = 12 g_boxd = g_ptsize + g_pad def pag...
# -*- coding:utf-8 -*- """ MIT License Copyright (c) 2019 JeffXun 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, modif...
#!/usr/bin/python # # Copyright (c) 2012 <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 Software without restriction, including without limitation the rights # to use, copy, modify...
from django.apps import apps from django.conf import settings from django.db.models import Q from api_basebone.core.admin import BSMAdmin from api_basebone.core.admin import BSMAdminModule from api_basebone.utils import meta, module from api_basebone.utils.meta import get_export_apps from bsm_config.models import Admi...
import os import logging from typing import Optional import json from lxml import etree from pycsw.core import metadata, repository, util import pycsw.core.admin import pycsw.core.config from pygeometa.core import read_mcf from pygeometa.schemas.iso19139 import ISO19139OutputSchema from pystac import Item from registr...
import numpy as np import h5py import os import cv2 as cv def write_hdf5(arr, output): with h5py.File(output, 'w') as f: f.create_dataset('image', data = arr, dtype = arr.dtype) # convert format of GT and masks from .gif to .png, use it only once. ''' def format_conversion(orig_dir, dest_dir): files =...
# Copyright (c) 2021, NVIDIA 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 appli...
import os DASHBOARD_WIDTH = 50 class WebPerformanceDashboard: """ The WebPerformanceDashboard is the producer of content to be written to the console. No stats or complex text formatting here. """ def __init__(self): self.data = {} self.persisted_messages = [] # Co...
""" Periodic water flows using ANUGA, where water driven up a linear sloping beach and time varying boundary. Ref1: <NAME>, Journal of Fluid Mechanics, 1958 Ref2: <NAME>, Int. J. Numerical Methods in Fluids, 2012 """ #------------------------------------------------------------------------------ # Import necessary mo...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Feb 4 20:56:49 2018 @author: hendrawahyu """ import cv2 import numpy as np # ============================================================================= # Setting inside ROI in 2 methods, fixed distance with 300 as default (for frame # or 30pix fo...
""" Collection of utility functions. Mask R-CNN functions are taken/modified from https://debuggercafe.com/instance-segmentation-with-pytorch-and-mask-r-cnn/ """ import os import numpy as np import torch import cv2 from utils.coco_names import COCO_INSTANCE_CATEGORY_NAMES as coco_names # from coco_names import COCO_I...
import os import ntpath import sys import sqlite3 import time import hashlib from openpyxl import Workbook from openpyxl.styles import Font from datetime import datetime """Ritorna il percorso del database""" def getbasefile(): return os.path.splitext(os.path.basename(__file__))[0] """Si connette al db SQLite"""...
from collections import namedtuple import copy import re import json from math import gcd with open(__file__.replace('.py', '.txt')) as f: input = f.read() data = { 'problem': input, '1': """<x=-1, y=0, z=2> <x=2, y=-10, z=-7> <x=4, y=-8, z=8> <x=3, y=5, z=-1>""", '2': """<x=-8, y=-10, z=0> <x=5, y=...
from sgraph import * from sympy import * from sympy.matrices import Matrix, zeros import copy import cmath import numpy as np from numpy.linalg import eigh # Custom function to swap rows in a matrix def swap_rows(i: int, j: int, M: Matrix) -> None: for ind in range(shape(M)[1]): a = copy.deepcopy(M[i, ind...
import os import torch import torch.nn as nn import torch.utils.data as Data import torchvision import numpy as np import matplotlib.pyplot as plt import imageio # Set GPU as device if it is available device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # Hyper parameters EPOCH = 1 BATCH_SIZE = ...
import numpy as np import sys import torch import pickle import string import os # =============================== INFERSENT =============================== class InferSentFeatures: def __init__(self, lang_enc_dir, sentences): sys.path.insert(0, os.path.join(lang_enc_dir, 'InferSent/')) from model...
# Copyright (C) 2015 Twitter, Inc. """Container for all audience management logic used by the Ads API SDK.""" from twitter_ads.enum import TRANSFORM from twitter_ads.resource import resource_property, Resource from twitter_ads.http import Request from twitter_ads.error import BadRequest from twitter_ads.cursor import...
import os.path import sys import getopt import math import pandas as pd import numpy as np from log import logger from Codecs.AdcpCodec import AdcpCodec import Ensemble.Ensemble as Ensemble import matplotlib.pyplot as plt import seaborn as sns class PlotMagnitude: def __init__(self): self.ens_receiver = ...
#import os #os.chdir("C:\\Users\\<NAME>\\Desktop\\598\\a6-movie-trends-JackHannnnnn") import requests import json import pandas as pd from apikeys import TMDB_KEY from datetime import datetime """movie trend functions start here""" def get_genres_dict(): '''Returns a dictitonay whose key is the genre name and whose...
""" Algoritmos de PCS3110 em Python Módulo 2 - Grafos """ from collections import deque class No: """ Nó de uma árvore binária (e ABB). """ def __init__(self, chave, pai = None, filho_esquerda = None, filho_direita = None): self.chave = chave self.pai = pai self.filho_esquerda = filh...
#!/usr/bin/env python """This module contains tools for random password generation. The module contains two functions: - passgen -- generate random password. - main -- the main entry point. """ from __future__ import print_function import string import random import argparse import sys class Generator(): ...
# coding=utf-8 # Licensed Materials - Property of IBM # Copyright IBM Corp. 2017 from builtins import * import unittest import sys import itertools import logging import socket from streamsx.topology.topology import * from streamsx.topology.tester import Tester from streamsx.topology.context import JobConfig from st...
#!/usr/bin/env python3 import math import re import bucket ''' N.B. that we hard-code the assumption that there's only one date within the event's time-frame with a given day of the week. Thus, handing events of duration longer than a week would require non-trivial revision here. This seems to be a limitation of Zamb...
import cairocffi as cairo import math, itertools, csv, collections from drawutils import grid_points from blockplot import plot_household import osm_building def lat2y(a): "Spherical Pseudo-Mercator projection" return a #* -1 #return 180.0/math.pi*math.log(math.tan(math.pi/4.0+a*(math.pi/180.0)/2.0)) d...
from pathlib import Path from typing import Optional, Dict, List, Type, Any, Union import pytorch_lightning as pl import torch from torch import nn as nn from torchmetrics import Metric from schnetpack.model.base import AtomisticModel __all__ = ["ModelOutput", "AtomisticTask"] class ModelOutput(nn.Module): """...
import os import torch.optim as optim import torch.nn as nn from lpd.trainer import Trainer from lpd.callbacks import SchedulerStep, StatsPrint, ModelCheckPoint, LossOptimizerHandler, CallbackMonitor, Tensorboard from lpd.extensions.custom_schedulers import DoNothingToLR from lpd.enums import Phase, State, MonitorType...
"""Wrappers for local and remote AMR parsing client""" import collections import copy import datetime import glob import os import pickle import sys import threading from nltk import sent_tokenize from nltk.tokenize import word_tokenize from amr_verbnet_semantics.grpc_clients.clients import AMRClientTransformer from ...
""" Package to provide support for various objects and modules This module contains functions that don't have an obvious home in a submodule. """ import datetime import logging import os import sys from numpy import array from os import environ, makedirs from os.path import exists from time import sleep, time from n...
# Hardware wallet interaction script import argparse import hid import json from device_ids import trezor_device_ids, keepkey_device_ids, ledger_device_ids,\ digitalbitbox_device_ids from serializations import PSBT # Error codes NO_DEVICE_PATH = -1 NO_DEVICE_TYPE = -2 DEVICE_CONN_ERROR = -3 U...
# coding: utf-8 # <img style='float: left' width="150px" src="http://bostonlightswim.org/wp/wp-content/uploads/2011/08/BLS-front_4-color.jpg"> # <br><br> # # ## [The Boston Light Swim](http://bostonlightswim.org/) # # ### Sea Surface Temperature time-series model skill # ### Load configuration # In[1]: import os...
import torch import torch.nn as nn import torch.nn.functional as F from typing import Callable, List, Union import inspect def filter_inner_params(params: List[nn.Parameter]): return [p for p in params if not hasattr(p, "__conditioner__")] class ConditionalLinearWrapper(nn.Module): @staticmethod def wra...
import asyncio import logging import queue import threading import urllib.request from pathlib import Path from typing import List, NamedTuple try: from typing import Literal except ImportError: from typing_extensions import Literal # type: ignore import av import cv2 import matplotlib.pyplot as plt import n...
# # Copyright (c) 2018 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...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Deep Convolutional GANs # Importing the libraries from __future__ import print_function import torch import torch.nn as nn import torch.nn.parallel import torch.optim as optim import torch.utils.data import torchvision.datasets as dset import torchvision.transforms as ...
""" See main/local_motivation_bert_agg.py module doc """ import json import os import shutil import tempfile from collections import defaultdict import numpy as np from absl import flags from .. import log from ..huggingface.run_classifier import main from ..params import GLUE_TASK_NAMES from ..sync import exists, s...
#!/usr/bin/python # -*- coding: utf-8 -*- # USAGE # There are two available ways to check if schema has been changed. # Both ways are mutually exclusive and '--release' flag has precedence. # Signature: # python schema_change_detector.py [versions|--release] [--no-color] # # Find changes between a current commit and la...
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # =========================================================================== # # Project : ML Studio # # Version : 0.1.14 # # File : test_objectives.py ...
from copy import copy, deepcopy from ctapipe.core.component import Component from inspect import isabstract from traitlets.config.loader import Config from traitlets import CaselessStrEnum class FactoryMeta(type(Component), type): def __new__(mcs, name, bases, dct): # Setup class lookup base = dc...
""" Cisco_IOS_XE_vlan_oper This module contains a collection of YANG definitions for monitoring vlans in a Network Element. Copyright (c) 2016\-2017 by Cisco Systems, Inc. All rights reserved. """ from collections import OrderedDict from ydk.types import Entity, EntityPath, Identity, Enum, YType, YLeaf, YLeafList, ...
# ================================================================= # # Terms and Conditions of Use # # Unless otherwise noted, computer program source code of this # distribution is covered under Crown Copyright, Government of # Canada, and is distributed under the MIT License. # # The Canada wordmark and related grap...
class LogoError(Exception): """ A generic Logo error. It tracks file position and some of the (Logo) traceback. """ def __init__(self, *args, **kw): Exception.__init__(self, *args) # We don't always get the tokenizer immediately, # but sometimes we do... if 'tokeni...
from flask.globals import current_app from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.support.ui import Select from time import sleep from Company import Company from os import listdir, mkdir from urllib.request import Request, urlopen import pdfquery fr...
""" Collection of RTCM helper methods which can be used outside the RTCMMessage or RTCMReader classes Created on 14 Feb 2022 :author: semuadmin :copyright: SEMU Consulting © 2022 :license: BSD 3-Clause """ # pylint: disable=invalid-name import logging from datetime import datetime, timedelta from pyrtc...
""" A tracker class for controlling the Tello: it computes a vector of the ball's direction from the center of the screen. The axes are shown below (assuming a frame width and height of 600x400): +y (0,200) Y (-300, 0) (0,0) (300,0) -Y (0,-200) -X ...
# -*- coding: utf-8 -*- """ Created on Sat Dec 19 16:12:02 2020 @author: <NAME> """ ### Importing the Libraries from flask import Flask, request, render_template import numpy as np import pickle import base64 import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import io from flask...
from shapely.geometry import Point, LineString, MultiLineString from shapely.geometry.polygon import Polygon from matplotlib import pyplot from descartes import PolygonPatch from geometry_tools.shapely_figures import SIZE, GREEN, GRAY, set_limits from math import pi, sin, cos, sqrt, atan2 from numpy import aran...
# oyTrajectoryDrawer by <NAME> (c) 2009 # # v0.1.0 # # Description : # ------------- # draws lines and spheres to the 3D viewport # # the input is the trajectoryPositions array attribute, by filling the attribute # with coordinates you can get your trajectory been drawn # # Version History : # ----------------- # v...
# -*- coding: utf-8 -*- """ decorator utils ~~~~~~~~~~~~~~~ useful (and sometimes critical) decorators, for use inside and outside :py:mod:`canteen`. :author: <NAME> <<EMAIL>> :copyright: (c) <NAME>, 2014 :license: This software makes use of the MIT Open Source License. A copy of this lice...
import math from itertools import combinations, product import numpy as np from tqdm import tqdm from flopt import Variable, Const, CustomExpression, Problem, Sum from flopt import env as flopt_env from .base_dataset import BaseDataset, BaseInstance from flopt.env import setup_logger logger = setup_logger(__name__)...
# Get extrinsic position from aruco marker import cv2 import torch import pickle import numpy as np from PIL import Image from threading import Thread def get_boxes(frame): global box_data, ACTIVE_THREADS ACTIVE_THREADS += 1 # Get prediction bounding boxes results = model(frame, size=320) box_data...
from itertools import combinations IUPAC = { ('A', 'C'): 'M', ('G', 'T'): 'K', ('A', 'G'): 'R', ('C', 'T'): 'Y', ('C', 'G'): 'S', ('A', 'T'): 'W', ('C', 'G', 'T'): 'B', ('A', 'C', 'G'): 'V', ('A', 'G', 'T'): 'D', ('A', 'C', 'T'): 'H', ('A', 'C', 'G', 'T'): 'N'...
import argparse import dali.core as D from dali.data import Lines, Process, DiscoverFiles, BatchBenefactor, IdentityReducer from dali.data.batch import TranslationBatch from dali.data.translation import TranslationFiles, TranslationMapper, build_vocabs, iterate_examples from dali.utils.scoring import bleu, ErrorTracker...
"""MIT License Copyright (c) 2021 gunyu1019 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...
#!/usr/bin/env python import sys import tqdm import time import itertools import numpy as np import h5py MeV = 1.0 mrad = 1.0 joule = 1.0 eV = 1e-6*MeV rad = mrad*1e3 steradian = rad*rad def create_dset(f, name, A): dset = f.create_dataset( name, shape=A.shape, dtype=A.dtype, compression='gzip') dset[...
################################# LICENSE ################################## # Copyright (c) 2009, South African Astronomical Observatory (SAAO) # # All rights reserved. # # # # Redistribu...
import os import math import numpy as np from sklearn.metrics import roc_curve, auc from scipy.stats import ttest_ind, poisson import matplotlib.pyplot as plt import constants import utils def n_pass_hyp(X_test, y_test, model, flip=0, verbose=0): y_score = model.predict(X_test) y_score = y_score[:, 0] if flip...
#!/usr/bin/env python from time import sleep from ansible.module_utils.basic import AnsibleModule import json import math import urllib2 DOCUMENTATION = ''' --- module: wf_source_tags short_description: - Enables interfacing with the Wavefront API to configure source tags requirements: [] author: - Wavefro...
from parsimonious import NodeVisitor from parsimonious.grammar import Grammar from .node import * __all__ = ['parse'] # Operator precedence in JS: # https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence VG_GRAMMAR = r""" start = space expr1 space ########################...
from p4p.client.thread import Context from p4p.nt import NTNDArray, NTScalar from p4p.server import Server, ServerOperation from p4p.server.thread import SharedPV import numpy as np import random import threading class Handler(object): """ A handler for dealing with put requests to our test PVs """ def put(s...
# Copyright 2019 getcarrier.io # 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...
# 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...
from functions.misc_functions_folder.misc_functions import * def gce_reduce(cmd_list, function_name, lock, project, mitigation_name, severity): """ Google Compute Engine function lines of code reducer """ result = {} if function_name in ["gce_firewallrule_log", "gce_firewallrule_traffic"]: res = exec_cmd(cmd...
# -*- coding: utf-8 -*- """curses ui impl for Snake """ import contextlib import curses import itertools from snakai.snake_state_machine import Direction class SnakeUIFramework(object): """ui framework for curses sname game a lower api for drawing. """ def __init__(self, width, height): self._...
# Django Imports from django import forms # HTK Imports from htk.forms.utils import get_combined_form_errors from htk.forms.utils import get_form_errors from htk.forms.utils import set_input_attrs from htk.forms.utils import set_input_placeholder_labels from htk.utils.cache_descriptors import CachedAttribute class A...
import datetime from typing import List, Optional from zoteroxy.config import ZoteroxyConfig def extract_year(datestr: str) -> Optional[str]: for i in range(len(datestr)-3): if datestr[i:i+4].isdigit(): return datestr[i:i+4] return None def from_timestamp(timestamp: Optional[str]) -> d...
import tempfile import math import numbers from pathlib import Path import torch import torchvision import numpy as np import av def load_video_webdata(data, num_frames, duration=None, skip_shorter_seconds=None): with tempfile.TemporaryDirectory() as dname: path = dname + "/sample.mp4" with open(...
"""Django AppSettings package.""" import os from django.core.exceptions import ImproperlyConfigured from django.core.signals import setting_changed from .settings import ( BooleanSetting, CallablePathSetting, DictSetting, FileSetting, FloatSetting, IntegerSetting, IterableSetting, List...
# by <NAME> # This is a direct translation of Yuval Tassa's Matlab code into Python: # https://benjaminmoll.com/wp-content/uploads/2020/06/LCP.m # It solves LCP using a Newton type method # To be consistent across platforms and with Yuval Tassa's code, # I have tried to make as minimal changes as I could, # so this c...
# Copyright 2018 The Cirq Developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
# Copyright: (c) 2021, <NAME> # The MIT License #   # 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, publ...
""" This is a Python implementation of Cocks' identity-based encryption (IBE) system. Helpful resources: 1. <NAME>, "An Identity Based Encryption Scheme Based on Quadratic Residue", Proc. 8th IMA Int'l Conf. on Cryptography and Coding, 2001 2. "Cocks IBE scheme", Wikipedia, https://en.wikipedia.org/wiki/Cocks_IBE_s...
''' Creates and solves a sudoku puzzle Created on Sep 6, 2020 @author: randy ''' import turtle import tkinter as tk import random import sys import os #grid grid = [] grid.append([0, 0, 0, 0, 0, 0, 0, 0, 0]) grid.append([0, 0, 0, 0, 0, 0, 0, 0, 0]) grid.append([0, 0, 0, 0, 0, 0, 0, 0, 0]) grid.append([0, 0, 0, 0, 0, 0...
import base64 from script_runner.config import settings import csv import glob import json import re import tempfile import traceback import os import shutil import subprocess from celery import Celery from distutils.dir_util import copy_tree import jsonpath_ng # Celery -----------------------------------------------...
from whoosh.index import Index as whooshIndex from whoosh.reading import IndexReader as whooshIndexReader from whoosh.matching import Matcher as whooshMatcher import bisect from .manager import StaticIndexManager from .postings import Postings try: from .svbcomp import load2, load2_to_np except ImportError: fro...
""" Contains code for CMB lensing extracted from LensTools by <NAME> (https://lenstools.readthedocs.io/). """ # import matplotlib.pyplot as plt import numpy as np import scipy.interpolate as interp LENS_LMAX = 3500 # Hardcoded value in lenstools def make_lensed_map_flat_sky(unlensed_t_map, phi_fft, npix, pixel_siz...
import functools import logging import traceback from dataclasses import dataclass from typing import Callable, Dict, Iterable, List, Tuple import pika import pika.exceptions from retry import retry from asyncqx.core.base import AQXBase, JSONSerializer from asyncqx.core.types import EventListener, Serializer, Stringa...
import os import pandas as pd class BarseqLayoutItem: def __init__(self, itnum, item_type, experiment_condition): self.__itnum = itnum self.__item_type = item_type self.__experiment_condition = experiment_condition @property def itnum(self): return self.__itnum @prope...
import logging import os from logging.handlers import SMTPHandler, RotatingFileHandler import click from flask import Flask, render_template, request from flask_login import current_user from flask_sqlalchemy import get_debug_queries from flask_wtf.csrf import CSRFError from flask.cli import FlaskGroup from sqlalchemy...
import matplotlib.pyplot as plt from matplotlib import colors import numpy as np from app.tools.curvefit.core.utils import data_translator def plot_fits(generator, prediction_times, sharex, sharey, draw_space, plot_obs=None, plot_uncertainty=False): """ Plot the result and draws from a model generator at some...
'''Losses used in encoder/decoder and d2 encoder. from: KChen @ https://github.com/kchen92/joint-representation/blob/master/lib/losses.py ''' from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import tensorflow.contrib.slim as slim ...
# Customized version of https://github.com/williballenthin/python-ntfs/blob/master/examples/parse_usnjrnl/parse_usnjrnl.py """ Parse a UsnJrnl:$J object into a CSV file. inspired by parser-usnjrnl by <NAME> (http://code.google.com/p/parser-usnjrnl/) """ import struct, datetime from parsers.parser_base import ParserBas...
import csv import numpy as np from torchvision import transforms import torch def regression_refinement(tx, ty, tw, th, cx, cy, cw, ch, indices): # refine the bounding boxes dcx = cw * tx[indices] dcy = ch * ty[indices] rcx = cx + dcx rcy = cy + dcy rcw = cw * np.exp(tw[indices]) rch = c...
import numpy as np import tensorflow as tf import time def add_read_shot_noise( imgs, sig_read=None, sig_shot=None, min_read=-3., max_read=-1.5, min_shot=-2., max_shot=-1.): bsz = tf.shape(imgs)[0] if sig_read is None or sig_shot is None: sig_read = tf.pow(10., tf.random.uniform( ...
# import datetime import hashlib import logging from pathlib import Path from typing import Dict, List # from .. import __package_name__ from .filedata_parser import SpectrumReader from .filename_parser_helpers import filestem_to_sid_and_pos, sID_to_sgrpID, get_fstats logger = logging.getLogger(__name__) #%% # _ex...
#!/usr/bin/env python3 """ This file defines the class inherit from bytearray and providing some methods to set or get data of explicit type , e.g. getUint32 or setInt8 just like buffer module in nodejs. Now this class could provide methods to operate: uint8,16,32,64 , int8,16,32,64 Author: <NAME> Email: <EMAIL> """...
# encoding: utf-8 ''' Created on 2020-04-03 15:40:13 generate_setup tool @author: nonamepand * create package: python setup.py sdist --format=zip ''' from __future__ import unicode_literals, absolute_import, print_function import os import sys import traceback import json from setuptools import setup os.environ["DI...
#! /usr/bin/env python3 #from pathlib import Path from os import path from setuptools import find_packages, setup #from setuptools.config import read_configuration #from subprocess import run #conf_file = path.join (path.dirname (__file__), "setup.cfg") #conf_dict = read_configu...
import requests import untangle import csv import os # Set your API key. Either store this in an environment variable called 'API_KEY', or amend the default value below api_key = os.getenv('API_KEY', 'default_value') base_url = f'http://v1.syndication.nhschoices.nhs.uk/organisations/pharmacies/all.xml?apikey={api_key}...