text
stringlengths
3.07k
22.1k
import numpy as np import pandas as pd import matplotlib.pyplot as plt from matplotlib import ticker import seaborn as sns from scipy.interpolate import InterpolatedUnivariateSpline as spl from corner import quantile, hist2d __all__=[ 'get_hdr', 'get_hdr_bounds', 'plot_hdr1d', 'plot_hdr2d', 'plot_...
import csv import itertools import json import logging import os import pickle import sys from pathlib import Path from typing import Callable, Dict, Iterable, List, Tuple, Union import pandas as pd from torch import nn from benchmarker.utils.pregenerated import PregeneratedCustomDataset csv.field_size_limit(sys.max...
# Copyright (C) 2019-2021, TomTom (http://tomtom.com). # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
# Copyright 2021 NVIDIA Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wr...
""" Copyright 2016-2022 by Sophgo Technologies 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 by applicab...
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import json import os from paste import httpserver import sys import webapp2 from jinja2 import Template from data_model import Obstaravanie, Session, Notification, NotificationStatus from utils import obstaravanieToJson, generateReport, getAddressForIco s...
"""Image grasp samplers. Adapted from <NAME>'s code. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from abc import ABCMeta, abstractmethod import numpy as np import scipy.misc import scipy.spatial.distance import scipy.ndimage.filters from PIL impor...
import ctypes import os from typing import List class ORTDeviceInfo: """ Represents picklable ONNXRuntime device info """ def __init__(self, index=None, name=None, total_memory=None, free_memory=None, compute_capability=None): self._index : int = index self._name : str = name ...
import plotly.graph_objs as go from plotly.colors import n_colors # to handle data retrieval import urllib3 from urllib3 import request # to handle certificate verification import certifi # to manage json data import json # for pandas dataframes import pandas as pd base_url = 'https://www.opendata.nhs.scot/api/3/acti...
""" A command-line interpreter for twill. This is an implementation of a command-line interpreter based on the 'Cmd' class in the 'cmd' package of the default Python distribution. """ import cmd import os import traceback from twill import commands, parse, __version__, logconfig, config from . import namespaces logg...
################################################################################ # # Copyright (c) 2009 The MadGraph5_aMC@NLO Development team and Contributors # # This file is a part of the MadGraph5_aMC@NLO project, an application which # automatically generates Feynman diagrams and matrix elements for arbitrary # h...
import numpy as np import yt from yt import derived_field from galaxy_analysis.plot.plot_styles import * import matplotlib.pyplot as plt from scipy.optimize import curve_fit from scipy.interpolate import interp1d from scipy.optimize import brentq import deepdish as dd from galaxy_analysis.analysis import compute_time_a...
import torch import torch.nn as nn from simplex_models import Linear as SimpLinear from simplex_models import Conv2d as SimpConv import math class VGG16(nn.Module): def __init__(self, n_classes=10): super(VGG16, self).__init__() self.relu = nn.ReLU(inplace=True) self.c1 = nn.Conv2...
import os import sys import time import math import inspect import copy import logging import numpy as np import cv2 import torch from torch.autograd import Variable import torch.nn.functional as F from .DaSiamRPN_net import SiamRPNvot, SiamRPNBIG, SiamRPNotb from .run_SiamRPN import generate_anchor, tracker_eval fro...
#!/usr/bin/python3 # # Title: G-code interpreter program # File: main.py # Description: Main program # Author: <NAME> (<EMAIL> # Date: 2022-02-01 # import sys import pdb from machineclient import MachineClient as MC def main(args): pgm_data = dict() if (len(args) != 2): show_usage() r...
#!/usr/bin/env python3 import os import numpy as np from scipy.optimize import curve_fit import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt savedir = './hill-fig/' if not os.path.isdir(savedir): os.makedirs(savedir) np.random.seed(101) def hill(x, ic50, n): x = np.asarray(x) ic50 = n...
from __future__ import unicode_literals from tablib import Dataset from django.conf import settings from django.contrib import admin, messages try: from django.core.urlresolvers import reverse except ImportError: # Django 2.0 from django.urls import reverse from django.http import HttpResponse from django...
# -*- coding: utf-8 -*- import math import numpy as np import cv2 import scipy import utils def compute_various_matching_score(match_dist_all, kpvis2w, dist_thresh_list): assert len(match_dist_all) == len(kpvis2w) # assert kpvis2w.max() == 1.0 if kpvis2w.max() != 1.0: print('[WARN] kpvis2w = {}'....
""" Hardware testing of MinimalModbus using the Delta DTB temperature controller. For use with Delta DTB4824VR. Usage ------------- :: python3 scriptname [-rtu] [-ascii] [-b38400] [-D/dev/ttyUSB0] Arguments: * -b : baud rate * -D : port name NOTE: There should be no space between the option switch and its a...
from __future__ import annotations import pandas as pd from pg_data_etl import Database from .logic_prep import ( assign_node_ids_to_network, add_travel_time_weights_to_network, construct_network, ) from .logic_analyze import analyze_single_poi, get_unique_ids from .logic_qaqc import clean_up_qaqc_table...
""" Author: <NAME> (<EMAIL>) Code for XtremeDistil for distilling massive multi-lingual models. """ from collections import defaultdict from tensorflow.keras.preprocessing import sequence from tensorflow.keras.preprocessing.text import Tokenizer import csv import logging import numpy as np import six imp...
""" Projection classes. A Projection is a connection between two Sheets, generally implemented as a large set of ConnectionFields. Any new Projection classes added to this directory will automatically become available for any model. """ from copy import copy import numpy as np import param # So all Projections ar...
""" OOD single machine simulation """ import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import torch.backends.cudnn as cudnn import torchvision import torchvision.transforms as transforms import os import argparse import copy import numpy as np import pickle from torch.op...
import abc import json import os import re from sympy import lambdify from sympy.abc import x, y from sympy.parsing.sympy_parser import parse_expr from sympy.utilities.iterables import iterable # These settings are considered as default when there is no recent session file SETTINGS_BY_MODES = { 'ARBIT...
import copy, datetime from collections import defaultdict class Document: def __init__(self, title, author=None): self.title = title self.author = author self.clippings = [] # internal housekeeping self._type_idx_map = defaultdict(list) def __repr__(self): return '<Document: "%s"%s, %d clippings>' % ( ...
""" FusionPBX Version: MPL 1.1 The contents of this file are subject to the Mozilla Public License Version 1.1 (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.mozilla.org/MPL/ Software distributed under the License is d...
#!/usr/bin/env python # coding: utf-8 # In[ ]: import speech_recognition as sr from os import path Audio = path.join(path.dirname(path.realpath('__file__')), "finale.wav") #Audio = "english.wav" ip = sr.Recognizer() with sr.AudioFile(Audio) as source: body = ip.record(source) #recognition of body try: print...
################################################################################ # BSD LICENSE # # Copyright(c) 2019-2021 Intel 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: # # *...
from configparser import NoOptionError from flask import Flask, Blueprint, render_template, request, send_file, Response from flask_npm import Npm import io from os import environ import datetime import string import json import sys import os import time import re import operator import urllib.parse from requests impor...
# -*- coding: utf-8 -*- """ Pore-Surface Diffusion Model (PSDM) for ion exchange (IX) Extends HSDMIX. Consult hsdmix.py for details TODO: Use further inheritance or composition (or something) to reduce code duplication with hsdmix @authors: <NAME>, <NAME>, <NAME> """ import timeit import numpy as np ...
from collections import Counter import pickle import re import numpy as np import pandas as pd from tqdm.auto import tqdm from rdkit import Chem from rdkit.Chem.BRICS import reactionDefs import moses from moses.metrics.utils import fragmenter from moses.utils import mapper isotope_re = re.compile(r'\[([0-9]+)[ab]?\*\...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Implementation of the network creation methods. Usage: >>> import pandangas as pg >>> net = pg.create_empty_network() >>> busf = pg.create_bus(net, level="MP", name="BUSF") >>> bus0 = pg.create_bus(net, level="MP", name="BUS0") >>> bus1...
from __future__ import annotations from pathlib import Path import typing as T import logging import re import asyncio import os from operator import itemgetter from .coro import check_urls as check_urls_async from .sync import check_urls as check_urls_sync from . import files # http://www.useragentstring.com USER_AG...
import os, sys import torch import torch.nn.functional as F import numpy as np import model as model_architecture import dataset_maker from torch.utils.data import DataLoader import utils import time import random from run_swag_experiment import ce_with_prior, L2_with_prior, train_splits from botorch.models import Si...
# -*- coding: utf-8 -*- from sst_unittest import * from sst_unittest_support import * from sst_unittest_parameterized import parameterized module_init = 0 module_sema = threading.Semaphore() rdmaNic_test_matrix = [] ################################################################################ # NOTES: # This is a...
import datetime import hashlib import os from django.conf import settings from django.contrib.auth.models import Group, User from django.core.cache import cache from django.db import models from django.db.models import Q from django.dispatch import receiver from django.utils.timezone import utc from airmozilla.base.u...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import torch import torch.nn as nn import torch.optim as optim from torch.utils.tensorboard import SummaryWriter import numpy as np import random import time import os import traceback import opts import mode...
#!/usr/bin/env python3 """Convert a PDF to HTML and then to text.""" import sys import argparse import subprocess import textwrap import regex from math import floor from tempfile import NamedTemporaryFile from collections import defaultdict from bs4 import BeautifulSoup import toml import traiter.util as t_util fr...
# -*- coding: utf-8 -*- """ Created on Fri Feb 4 14:34:52 2022 Credits to: https://www.github.com/MouseLand/suite2p/blob/main/jupyter/run_suite2p_colab_2021.ipynb @author: SimenLab """ import os import numpy as np import pathlib import tifffile import suite2p import shutil import warnings import time import suite2p...
import numpy as np import matplotlib.pyplot as plt import scipy.optimize import multiprocessing as mp import copy import pickle import gasdynamics as gd from heat_flux import heat_flux from plug_nozzle_angelino import plug_nozzle import MOC ## NASA CEA CONSTANTS class CEA_constants(): def __init__(self,gamma,T_c,...
import os import numpy as np import json import multiprocessing import PIL.Image as Image from panopticapi.utils import get_traceback, rgb2id, merge_thing_instances OFFSET = 256 * 256 * 256 VOID = 0 class SemSegStat(): def __init__(self, num_classes): self._num_classes = num_classes self._N = n...
import os import glob import cv2 import numpy as np from dataPath import DATA_PATH # returns image paths in given folder # with extensions as defined in imgExts def getImagePaths(folder, imgExts): imagePaths = [] for x in os.listdir(folder): xPath = os.path.join(folder, x) if os.path.splitext(xPath)[1] in ...
import torch import torch.nn as nn import torch.nn.init as init from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence from ulangel.rnn.dropouts import ( ActivationDropout, ConnectionWeightDropout, EmbeddingDropout, ) class AWD_LSTM(nn.Module): """AWD-LSTM inspired by https://arxiv....
#!/usr/bin/env python #kkonsole script import click import os import requests import json #requests comes with json decoder. #from pampy import match,_ # not used yet import logging; logging.basicConfig(filename='/var/log/kkonsole.log',datefmt='%Y/%m/%d %H:%M:%S',level=logging.INFO) @click.group() def kkonsol...
import argparse import logging from logging.handlers import RotatingFileHandler from os import sys, path import numpy as np from flasgger import Swagger from flask import Flask, request from flask.json import jsonify from flask_ini import FlaskIni sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) f...
#! /usr/bin/env python3 # Copyright (c) 2018-Present Advanced Micro Devices, Inc. See LICENSE.TXT for terms. """build_helpers.py : Contains classes and helper funcs for build automation """ __author__ = "AMD Research" __copyright__ = "Copyright 2019" import os import sys import shutil import subprocess import psut...
from .colors import Color from .types import LabTuple from .blend import blend from typing import List, Any, Tuple, Callable, Union from . import terminal from functools import wraps import math import sys def _binomial(i: int, n: int) -> float: """Binomial coefficient """ return math.factorial(n) / float...
from django.contrib.auth import get_user_model from django.conf import settings from rest_framework import serializers from rest_polymorphic.serializers import PolymorphicSerializer from rest_framework.exceptions import ValidationError from django.core.validators import URLValidator from django.core.exceptions import V...
""" oidc Viewsets module """ import importlib import re from typing import Optional, Tuple from django.conf import settings from django.contrib.auth import get_user_model, login from django.contrib.auth import logout as logout_backend from django.http import ( HttpRequest, HttpResponse, HttpResponseBadRequ...
import json import random import tkinter as tk from tkinter import filedialog as fd import pygame import MazeBuilder from App import App from Button import Button from Grid import Grid from SearchAlgorithms import breadth_first_search, best_first_search, a_star_search tk.Tk().withdraw() open_color = (255, 255, 255)...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (C) 2021 <NAME> # Erasmus Medical Center # Department of Genetic Identification # # License: GNU General Public License v3 or later # A copy of GNU GPL v3 should have been included in this software package in LICENSE.txt. # NestedCV pipeline for Smoking Micr...
""" Script to calculate Level of Travel Time Reliability (LOTTR) per FHWA guidelines. Calculations for Auto/Bus traffic. By <NAME>, Metro, <EMAIL> NOTE: SCRIPT RELIES ON PANDAS v.0.23.0 OR GREATER! """ import os import pandas as pd import numpy as np import datetime as dt def calc_pct_reliability(df_pct): ""...
import alpaca_trade_api as alpaca import numpy as np import pandas as pd import sys import os class Market: '''This class automatically downloads the data for the provided symbols from Alpaca, and simulates the pass of time during a day by providing 1 minute barsets with its method next_barset().''' d...
import os import numpy as np import nltk import tensorflow as tf ############# File Clean-up ################################ ''' Steps: 1. Tag sentence and keep only lemmatized Nouns and Verbs 2. For every entry remove duplicate words. 3. Return number of negative samples and positive samples...
# -*- coding: utf-8 -*- # MIT License # # Copyright (c) 2019 <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, co...
# coding=utf-8 from org.meteothink.math.stats import StatsUtil from org.meteothink.math import ArrayMath, ArrayUtil from org.meteothink.ndarray import Array from numjy.core.multiarray import NDArray import numjy.core.numeric as minum __all__ = [ 'chi2_contingency','chisquare','covariance','cov','pearsonr','spear...
import os from typing import List, Dict, Any, Optional, Tuple import json from collections import defaultdict import typer import questionary from capella_console_client.enumerations import BaseEnum from capella_console_client.cli.client_singleton import CLIENT from capella_console_client.cli.validate import ( ge...
# Copyright 2017 AT&T Intellectual Property. All other 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...
from dragonfly import ( Choice, MappingRule, IntegerRef, Grammar, Dictation ) from lib.dynamic_aenea import ( GlobalDynamicContext, Key, Text, ) from lib.text import SCText DYN_MODULE_TYPE = "programming_language" DYN_MODULE_NAME = "css" INCOMPATIBLE_MODULES = [ 'python', 'rub...
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Purpose Shows how to use the AWS SDK for Python (Boto3) with Amazon Simple Email Service (Amazon SES) to send email. """ import json import logging import smtplib import ssl import boto3 from botocore.excep...
import os import ast from django.http import HttpResponse, HttpResponseRedirect, Http404 from django.shortcuts import render, redirect, get_object_or_404 import plotly.express as px import plotly.graph_objects as go import pandas as pd from .bin2real import * from .forms import * from .models import * # Create your vi...
"""Helper specific to SnowAlert connecting to the database""" from datetime import datetime import json from threading import local from typing import List, Tuple from os import path, getpid from re import match import snowflake.connector from snowflake.connector.constants import FIELD_TYPES from snowflake.connector....
#total_counts Modules import matplotlib import time from matplotlib import pyplot as plt import numpy as np import csv from speccounts import * #utilities Modules import os.path import sys import pandas as pd import math from filterlist_to_filterfiles import filterlist_to_filterfiles def pivot_waveleng...
import numpy as np # Size of the maze maze_size = (250, 400) class Node: # To save the index of the current node node_index = 0 # To save the index of the parent node parent_index = 0 # A list of all the possible actions [North, East, South, West, North-East, South-East, South-West...
# -*- coding: ISO-8859-15 -*- # ============================================================================= # Copyright (c) 2009 <NAME> # # Authors : <NAME> <<EMAIL>> # # Contact email: <EMAIL> # ============================================================================= """ API for OGC Filter Encoding (FE) constr...
"""Elaborate script to fix Any's in bad files created by version 0.5.28 datamodel-code-generator.""" # This relies on datamodel-codegen 0.5.28 to create classes that work, # but don't do much checking. # This is because the generated classes rely on Any - which does no checking. # This script changes the Any's appro...
# image processing utils import numpy as np import cv2 # opencv # from skimage.registration import optical_flow_tvl1 from scipy import ndimage from scipy.ndimage.filters import maximum_filter from scipy.ndimage.morphology import generate_binary_structure, binary_erosion from collections import OrderedDict import copy...
from tkinter import * from math import * def ajuda(): ajuda = Tk() ajuda.title('Ajuda') texto = Label(ajuda, text='Créditos:\n\n\n<NAME>\n\nSite: leonardotoledo.org\n\nE-mail: <EMAIL>\n\n\nReferências:\n\nABNT NBR 6118:2014\n\nABNT NBR 6122:2010\n\nABNT NBR 7480:2007\n\nNotas de aula de Fundações 2\nProf...
""" SiamRPN train""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import argparse import logging import os import time import numpy as np os.environ['MXNET_CUDNN_AUTOTUNE_DEFAULT'] = '0' import mxnet as mx from mx...
"""Project: Eskapade - A python-based package for data analysis. Class: HistogrammarFiller Created: 2017/03/21 Description: Algorithm to fill histogrammar sparse-bin histograms. It is possible to do cleaning of these histograms by rejecting certain keys or removing inconsistent data types. Timestamp ...
# -*- coding: utf-8 -*- from tinydb import TinyDB def main(): from os.path import join, dirname from dotenv import load_dotenv import sys dotenv_path = join(dirname(sys.argv[0]), '.env') load_dotenv(dotenv_path=dotenv_path, verbose=True) def mongo(): main() import os data = { ...
#!/usr/bin/env python # Copyright (c) 2019 Diamond Key Security, NFP # 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, #...
from datetime import timedelta from pathlib import Path from django.db import models from django.core.cache import cache from django.core.files.storage import FileSystemStorage from django.utils.timezone import now class Colors(models.TextChoices): """Couleur d'affichage dans le planning Leur code HTML est hardcod...
import chainer import chainer.functions as F import chainer.links as L from tgan2.models.conv_lstm import ConvLSTM from tgan2.models.resblocks import GenBlock from tgan2.utils import make_batch_normalization import numpy def _expand(option): if isinstance(option, (list, tuple)): return option elif o...
import numpy as np import tensorflow as tf import gym import time from spinup.algos.dqn import core from spinup.algos.dqn.core import get_vars, copy_operation from spinup.utils.logx import EpochLogger class ReplayBuffer: """ A simple FIFO experience replay buffer for DQN agents. """ def __init__(self...
import numpy as np from numpy.linalg import matrix_rank import LUP_rank import other_rank_computers import statistics as stat from time import perf_counter import argparse RANK_COMPUTER = None def run_all_tests(params, threshold, diagnostics, runs): """ It runs all testing functions given within params along...
from models.package import Package import argparse import itertools import json import re import signal seen = [] lowest_cost = -1 best_commands = [] class OutOfTime(Exception): pass def timeout(sig, frame): raise OutOfTime() # all packages that match this constraint def matches(constraint): r = re....
# coding=utf-8 import os import pandas as pd import features import load_data import stance_detect_logit as logit import stance_detect_logit_ord as logit_ord import stance_detector_multitarget as multitarget import stance_detect_nb as nb import utils if not os.path.exists('latex/'): # Create directory to store ta...
from apscheduler.schedulers.blocking import BlockingScheduler import argparse from copy import deepcopy from jinja2 import Environment, PackageLoader import json import logging import os import os.path import shutil import subprocess import sys from .kubernetes_backend import KubernetesBackend class ZorpConfigGenera...
import numpy as np from ..lattice import INVALID, Lattice from .pathfinding import straight_line_length, periodic_straight_line_length, path_between_plaquettes def fluxes_from_bonds(l, bonds, real = True) -> np.ndarray: """ Given a lattice l and a set of bonds = +/-1 defined on the edges of the lattice, calcu...
import datetime import logging import psycopg2 from typing import Union, Dict, List, Tuple, Optional, Any log = logging.getLogger(__name__) log.addHandler(logging.NullHandler()) class SQLDatabaseWrapper: def __init__(self, host: str, port: Union[int, str], user: str, password: str, database: str): """W...
"""This module contains helper functions for plotting.""" from typing import Tuple, Optional import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import helpsk.pandas as hpandas from helpsk.exceptions import HelpskParamValueError STANDARD_WIDTH = 10 GOLDEN_RATIO = 1.6180339887...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright (C) 2020 The SymbiFlow Authors. # # Use of this source code is governed by a ISC-style # license that can be found in the LICENSE file or at # https://opensource.org/licenses/ISC # # SPDX-License-Identifier: ISC import json import os import glob import time...
import numpy as np import scipy.linalg as slinalg import constrained_gaussian_integrals as cgi def joint_min(mu: np.ndarray, var: np.ndarray, with_derivatives: bool=False) -> np.ndarray: """ Computes the probability of every given point (of N representer points) to be the minimum based on the HDR[1] alg...
import os from unittest import mock from primehub.files import _normalize_user_input_path, _normalize_dest_path from tests import BaseTestCase from primehub.utils import create_logger, SharedFileException logger = create_logger('primehub-test') """ Consider folloing files PHFS: / ├── l0.csv └── deep/ ├── l1.csv ...
import time import sorting import bst import timeit import platform import random import numpy as np import pandas as pd import matplotlib.pyplot as plt import heapq import copy random.seed(521) DEFAULT_NUMBER = 100000 # 100k DEFAULT_POPULATION = range(100000) # 1m DEFAULT_SIZES = [10, 100, 1000, 10000, 100000] de...
# Copyright (c) 2022 Exograd SAS. # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WA...
#<NAME>, A.M:2994 #python version 3.8.5 import sys import time import json import math #global list containing all transaction sets transactions = [] #eg transactions = [{5, 8, 3, 1}, {...}, ...] #{5, 8, 3 , 1} is a single transaction set sigfile = [] #contains the signatures for each transaction bitslice = ...
import time import uuid import numpy as np from matplotlib import pyplot as plt from matplotlib.lines import Line2D from functools import partial from perlin2D import generate_fractal_noise_2d, generate_perlin_noise_2d class Line(Line2D): """Custom line class. The line width is defined in the same units as the...
import time from math import atan2, pi, degrees, radians import wx from wx.lib.newevent import NewCommandEvent import pytweening as ptw from aic import ActiveImageControl rs_cmd_event, EVT_RS_CHANGE = NewCommandEvent() class RotarySwitch(ActiveImageControl): def __init__(self, parent, bitmaps, *args, **kwargs...
#!/usr/bin/env python3 import dask import fsspec import geopandas import numcodecs import numpy as np import pandas as pd import regionmask import xarray as xr from dask.distributed import Client from carbonplan_trace.metadata import get_cf_global_attrs from carbonplan_trace.tiles import tiles from carbonplan_trace.u...
# Copyright 2021 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. """Test result related classes.""" from collections import OrderedDict import shard_util import time from result_sink_util import ResultSinkClient _VALID_R...
# Evaluating fitted couplings # Also includes some utility functinos for manipulating and plotting couplings import numpy as np import ot import warnings import matplotlib.pyplot as plt def l2_difference(coupling_1, coupling_2): return np.linalg.norm(coupling_1 - coupling_2, 'fro') def scaled_l2_difference(coup...
''' Implement the API to read & write graph files according to METIS' graph format. ''' import os from os import path import sys import graph from graph import Graph import random import subprocess prefix = "/tmp/place-threads-" ############################################################################### # Pr...
import os from typing import List import numpy as np import pytest import tensorflow as tf import gpflow from gpflow.monitor import ( ExecuteCallback, ImageToTensorBoard, ModelToTensorBoard, Monitor, MonitorTaskGroup, ScalarToTensorBoard, ) class Data: num_data = 20 num_steps = 2 @...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 OpenStack Foundation # # 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 # # Unle...
from __future__ import division from __future__ import print_function import tensorflow as tf import numpy as np from config import FLAGS # from data import fill_feed_dict as fill_feed_dict from utils import fill_feed_dict as fill_feed_dict from sklearn.metrics import precision_score, confusion_matrix, classificatio...
from __future__ import annotations from dataclasses import dataclass from typing import ( Any, Callable, FrozenSet, Iterable, List, Optional, Sequence, Set, Type, TypeVar, Union, ) from pocketutils.core.dot_dict import NestedDotDict from pocketutils.core.exceptions import M...
""" Implementation of binary search trees. """ from __future__ import annotations class Node: def __init__(self, val: int) -> None: self.val = val self.left: Node | None = None self.right: Node | None = None class BinarySearchTree: def __init__(self) -> None: self.root: Node...
# -*- coding: utf-8 -*- """ Detect the dialect with very strict functional tests. This module uses so-called "normal forms" to detect the dialect of CSV files. Normal forms are detected with strict functional tests. The normal forms are used as a pre-test to check if files are simple enough that computing the data ...