text
stringlengths
6.04k
39.5k
""" Make synthetic PNW population for CTA 1DC """ import numpy as np import astropy.units as u from astropy.coordinates import SkyCoord from astropy.table import Table, Column from gammapy.astro.population import make_base_catalog_galactic from gammapy.utils.random import get_random_state from gammapy.utils import coor...
import argparse import os import subprocess import eyed3 import re import sys import tempfile from math import ceil from pathlib import Path from typing import Optional, Any, NoReturn """ AUTOMATICALLY GENERATED usage: __main__.py [-h] [-e [REGEX]] [-a] [-c [RESOLUTION]] [-f] [-v] [-d GECKODRIVER] [-s] [input] Extra...
from scipy.stats import wilcoxon # , spearmanr <- this has a bug from scipy.spatial.distance import pdist, squareform from sklearn.model_selection import LeaveOneOut from scipy.stats import mstats_basic from scipy.stats import rankdata, distributions import numpy as np import warnings from .utils import write_to_logge...
# Generate MVM waves with harbingers and such # The actual .pop file has tons of redundancy, which means editing it is tedious. from itertools import cycle # Global defaults - can be overridden per popfile, and provide the # defaults for waves and subwaves. DEFAULTS = { "tank_health": 40000, "tank_speed": 75, "mone...
#!/usr/bin/env python3 import os import sys import shutil import time import math import numpy as np import numpy.random as npr import gc import pickle as pkl import matplotlib.pyplot as plt plt.style.use('bmh') import torch from torch import nn import torch.nn.functional as F from torch.autograd import grad import...
import sys import os import shlex import json def generate_absolute_vector_positions(vector_size, string_syntax): # is empty -> whole vector is used if(string_syntax == ""): return [x for x in range(vector_size)] if(string_syntax[-1] != "]"): raise Exception("Expected vec[formatted_range] a...
# Copyright (c) 2019 Sony 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 applicabl...
import os, sys os.environ['KMP_DUPLICATE_LIB_OK']='True' sys.path.append(os.path.dirname(sys.path[0])) project_dir = os.path.dirname(os.path.dirname(sys.path[0])) sys.path.append(project_dir) sys.path.append(os.path.join(project_dir, 'gym_multi_car_racing')) import gym import torch import torch.nn as nn import tor...
import seafileapi # https://github.com/haiwen/python-seafile/blob/master/doc.md#repo from constants import * import tkinter as tk import os from PIL import Image, ImageTk from tkinter import messagebox import numpy as np import re from message_box import Mbox def resize_img(image, maxsize): r1 = image.size[0] / m...
import numpy as np from tqdm import tqdm from math import exp import os import signal import json import argparse from dataset import CRSdataset, collate_fn from model import Model import torch.nn as nn from torch import optim import torch from nltk.translate.bleu_score import sentence_bleu import nltk import re import...
#!/usr/bin/env python # coding: utf-8 # # This notebook is divided into three main sections: # ### 1. Data Display, Importing and Preprocessing # ### 2. Dimensionality Reduction # ### 3. Unsupervised Classification # ## 1. Data Display, Importing and Preprocessing # ### 1.1 Displaying an RGB image from the given hyp...
""" This file demonstrates writing tests using the unittest module. These will pass when you run "manage.py test". Replace this with more appropriate tests for your application. """ import itertools from datetime import timedelta from unittest.mock import patch import ddt from django.core.exceptions import Validati...
""" Module containing in/out schemas to be used in the main module. """ from datetime import datetime from typing import List, Optional, Union from pydantic import BaseModel, Field, AnyUrl class Message(BaseModel): msg: str class HTTPError(BaseModel): detail: List[Message] class Info(BaseModel): nam...
from collections import defaultdict from typing import Any, List, Tuple, Union, Iterable from weakref import WeakValueDictionary from qtpy.QtGui import QPalette, QBrush from databroker.core import BlueskyRun from qtpy.QtCore import Qt, QAbstractItemModel, QModelIndex, QItemSelectionModel, Signal from qtpy.QtWidgets im...
import cv2 import numpy as np import mediapipe as mp np.random.seed(123) class Point(object): """ Class to denote a joint in 2-D space Arguments: x, y : x-axis and y-axis co-ordinates visibility : visibility score of the joint """ def __init__(self, x=0.0, y=0.0, visibility=0.0): self...
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import os import json import numpy ...
# This is a sample Python script. # Press ⌃R to execute it or replace it with your code. # Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings. import random import threading import time import sys from ui import Ui_MainWindow from PyQt5.QtWidgets import QApplication, QMainWindo...
# For python 3 portability from __future__ import (absolute_import, division, print_function, unicode_literals) from builtins import dict, object, str, open, zip from six import string_types from datetime import datetime from html.parser import HTMLParser from os.path import isfile from tempfi...
# from Bio import SeqIO, AlignIO from Bio.Seq import Seq from itertools import chain from collections import Counter, OrderedDict import numpy as np from distance import hamming import primer3 from tqdm import * import math import datetime import yaml def setup_yaml(): # https://stackoverflow.com/a/8661021 rep...
"""Summarize individual evaluations generated by evaluate_models.py COVID-19 Forecast Hub: https://github.com/reichlab/covid19-forecast-hub Learn more at: https://github.com/youyanggu/covid19-forecast-hub-evaluation To see list of command line options: `python summarize_evaluations.py --help` """ import argparse imp...
from zope.interface import implements from twisted.internet.defer import ( inlineCallbacks, returnValue, maybeDeferred, gatherResults) from vumi import log from vumi.worker import BaseWorker from vumi.application import ApplicationWorker from vumi.blinkenlights.metrics import MetricPublisher, Metric from vumi.conf...
import tensorflow as tf import tensorflow.contrib.slim as slim import sys, os import argparse import numpy as np from functools import partial from config import cfg from tfflat.base import ModelDesc, Trainer from tfflat.utils import mem_info from nets.basemodel import resnet50, resnet_arg_scope, resnet_v1...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ Utilities for working with different 3D coordinate systems """ import copy import math import torch import torch.nn.functional as F from pytorch3d.structures import Meshes from pytorch3d.utils import ico_sphere SHAPENET_MIN_ZMIN = 0.67 SHAPENE...
# -*- coding: utf-8 -*- """ Copyright 2022 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law ...
import math import numpy as np import torch import torch.nn as nn from torch.autograd import Variable def import_class(name): components = name.split('.') mod = __import__(components[0]) for comp in components[1:]: mod = getattr(mod, comp) return mod def conv_branch_init(conv, branches): ...
import numpy as np from itertools import permutations from tvm import te from tvm import autotvm import subprocess cache_sizes = [ int(subprocess.run(['getconf', 'LEVEL1_DCACHE_SIZE'], stdout=subprocess.PIPE).stdout), int(subprocess.run(['getconf', 'LEVEL2_CACHE_SIZE'], stdout=subprocess.PIPE).stdout)...
# ------------------------------------------------------------------------------ # Portions of this code are from # CornerNet (https://github.com/princeton-vl/CornerNet) # Copyright (c) 2018, University of Michigan # Licensed under the BSD 3-Clause License # -------------------------------------------------------------...
''' @FileName : fitting.py @EditTime : 2021-12-13 15:44:09 @Author : <NAME> @Email : <EMAIL> @Description : ''' from __future__ import absolute_import from __future__ import print_function from __future__ import division import sys import os import time import numpy as np import torch import...
#load("tautrel.sage") #load("AllStrata.sage") from sage.all import Graph, prod, Integer, OrderedSetPartitions, Permutations, flatten from stratagraph import StrataGraph import itertools class StrataWithSageGraph(object): def __init__(self, strataG): self.strataG = strataG self.sageG...
"""Periodic pattern mining with a MDL criterion""" # Authors: <NAME> <<EMAIL>> # License: BSD 3 clause import warnings from itertools import groupby import numpy as np import pandas as pd from ..base import BaseMiner, DiscovererMixin, MDLOptimizer from ..bitmaps import Bitmap from ..utils import intersect2d, sliding...
#!/usr/bin/env python import argparse import json import logging import sys import time import boto3 import botocore import yaml import natsort import traceback DISABLED_REASON = "Updated via CLI" DISABLED_REASON_EXCEPTION = "Exception" DISABLED = "DISABLED" INITIAL_WAIT_TIME = 0.1 # initial waiting time used betwe...
# -*- coding: utf-8 -*- """ Useful utilities for testing the 2-D DTCWT with synthetic images License: https://github.com/fbcotter/pytorch_wavelets/blob/master/LICENSE Source: https://github.com/fbcotter/pytorch_wavelets/blob/31d6ac1b51b08f811a6a70eb7b3440f106009da0/pytorch_wavelets/dwt/lowlevel.py # noqa """ import p...
""" A command line utility for interacting with the Hack the Box API """ from htbcli import HTBAPI import argparse from argparse import ArgumentParser from pathlib import Path import configparser import sys from tabulate import tabulate from termcolor import colored from math import floor apiKey = None lab = None machi...
#<NAME>, 2591 import sys import random import pandas as pd import numpy as np import itertools import keyboard import ast from collections import Counter,defaultdict from operator import itemgetter import networkx as nx import matplotlib.pyplot as plt import timeit #Time the whole process start = timeit.default_timer(...
import sys import xml.etree.cElementTree as ET from xml.dom import expatbuilder class Group: def __init__(self, group_id, group_label=None, group_description=None, group_url=None, group_color="#8AB339"): self.group_id = group_id if group_label: self.group_label = group_label ...
import abc import math from collections import deque import Sensor as Sensor import numpy as np import utils as utils from scipy.stats import norm import numpy.random as random import matplotlib.pyplot as plt import seaborn as sns def clamp(x, a, b): y = a if x < a else x y = b if y > b else y return y ...
#!/usr/bin/env/python import pickle import queue import threading from collections import deque from threading import Thread import numpy as np import tensorflow as tf from rdkit import Chem from rdkit.Chem import rdmolops SMALL_NUMBER = 1e-7 LARGE_NUMBER = 1e10 geometry_numbers = [3, 4, 5, 6] # triangle, square, p...
# -*- coding: utf-8 -*- # (C) Copyright 2014 Voyager Search # # 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...
''' Created on Jul 26, 2016 @author: arafferty ''' import beta_bernoulli import numpy as np import numpy.random as nprand import csv from output_format import * from bandit_data_format import * SAMPLE_TIME = 0 ARRIVAL_TIME = 1 ARM_INDEX = 2 IMMEDIATE_REWARD = 3 FINAL_REWARD = 4 def get_thompson_arm_choice(models): ...
# -*- coding: utf-8 -*- import os, re import codepoints import logging _props_loaded = False _grapheme_props = {} _word_props = {} _G_Any = 0 _G_CR = 1 _G_Control = 1 << 1 _G_Extend = 1 << 2 _G_L = 1 << 3 _G_LF =...
"""Plutus related classes and functions.""" from __future__ import annotations import inspect import json from dataclasses import dataclass, field, fields from enum import Enum from typing import ClassVar, List, Optional, Union import cbor2 from cbor2 import CBORTag from nacl.encoding import RawEncoder from nacl.has...
# <NAME> # Portfolio Project # Sudoku class Sudoku: # Constructor that creates the Sudoku starting board (values that cant be changed) and a copy # that will hold the player's entries as well as several other attributes needed to test # their solution def __init__(self): self.base_boar...
# Copyright (c) 2011, <NAME> and <NAME>. # Licensed under the Academic Free License 3.0. import sys import copy import os import Utility import Operation import OperationSetAnalyzer from Utility import configure #from OperationSet import neededOps, neededFws, logicOps def GetArchLang(args): uiInp...
import requests from urllib.parse import quote import json import math import random import hashlib import logging _LOGGER = logging.getLogger(__name__) def compute_md5hash(hashstring): """Return the MD5 Hash of a given string""" m = hashlib.md5() m.update(hashstring.encode('utf-8')) return m.hexdige...
import os import os.path as osp import datetime import numpy as np from glob import glob from tqdm import tqdm_notebook as tqdm from skimage import io import itertools from PIL import Image # Matplotlib import matplotlib.pyplot as plt import imageio from sklearn.metrics import confusion_matrix # Options from options.t...
# This parameter file contains the parameters related to the primitives located # in the primitives_spect.py file, in alphabetical order. from astropy import table, units as u from astropy.io import registry from astrodata import AstroData from geminidr.core import parameters_generic from gempy.library import config, ...
import collections import os def get_entity_attrs(e_idx, words, offset, span_indices, sub_to_words): e_span_indice = span_indices[e_idx] e_words = [] e_offset = [-1, -1] curr_word_idx = -1 for idx in range(e_span_indice[0], e_span_indice[1] + 1): if sub_to_words[idx] != curr_word_idx: ...
#!/usr/bin/env python3 import argparse, subprocess, requests, json, sys, base64, binascii, time, hashlib, re, copy, logging, configparser import dns.resolver, dns.tsigkeyring, dns.update LOGGER = logging.getLogger('acme_dns_tiny') LOGGER.addHandler(logging.StreamHandler()) def get_crt(config, log=LOGGER): def _b6...
import numpy as np import heapq import os import tensorflow as tf from sklearn.metrics import roc_auc_score from layers import Dense, CrossCompressUnit import metrics def test_one_user_v2(rating, pos_items, Ks): r, auc = ranklist_by_sorted_v2(pos_items, rating, Ks) return get_performance(pos_items, r, auc, Ks...
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import import numpy as np import warnings import CoolProp from CoolProp.Plots.Common import IsoLine,BasePlot,interpolate_values_1d from CoolProp.Plots.SimpleCycles import StateContainer class PropertyPlot(BasePlot): def __init__(s...
import pandas as pd import numpy as np import random import os import pickle import datetime import argparse import torch import torch.nn as nn import torch.utils.data as tdata import torchvision.transforms as transforms import pytorch_lightning as pl from sklearn.metrics import cohen_kappa_score from sklearn.metrics ...
# Import useful libraries import cv2 import numpy as np import matplotlib.pyplot as plt from scipy import signal from skimage.measure import compare_ssim as ssim import matplotlib as mpl from mpl_toolkits import mplot3d import csv import os import datetime stamp = datetime.datetime.now().microsecond # Stamp for figure...
# Copyright 2021-2022 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 writi...
#!/usr/bin/python2.7 import torch import numpy as np import random import os import cv2 from PIL import Image from torchvision import transforms as transforms # import PIL.Image as Image class BatchGenerator(object): def __init__(self, img_path,label_path): self.img_path = img_path self.label_...
from __future__ import print_function import json import math import numpy as np import sys import time import clodius.fast as cf def aggregate(in_array, num_to_agg): return cf.aggregate(in_array.astype(np.float32), num_to_agg) def load_entries_from_file(sc, filename, column_names=None, delimiter=None, ...
""" SMC input/output (sequentially Markov coalescent) The SMC data structure is used to describe an ARG using a series of local trees and SPR (subtree pruning and regrafting) operations. """ from contextlib import closing import StringIO import argweaver from compbio import arglib from rasmus import treelib f...
# Copyright Contributors to the Pyro project. # SPDX-License-Identifier: Apache-2.0 """ We use a switching linear dynamical system [1] to model a EEG time series dataset. For inference we use a moment-matching approximation enabled by `funsor.interpreter.interpretation(funsor.terms.moment_matching)`. References [1] ...
# -*- coding: utf-8 -*- #!/usr/bin/env python """ This example uses the "synthetic data" experiment in the paper http://arxiv.org/abs/1511.06429 and illustrates how to use concarne. Note that the file is structured very similarly to the MNIST example for Lasagne in order to facilitate usage of concarne for Lasagne u...
from django.shortcuts import render import pandas as pd import gensim, json from datetime import datetime import requests import numpy as np from sklearn.feature_extraction.text import CountVectorizer from imblearn.over_sampling import ADASYN from sklearn.ensemble import RandomForestClassifier # user date pulled from ...
import itertools import matplotlib.pyplot as plt from matplotlib import cm import networkx as nx import numpy as np from scipy.spatial import Voronoi ######################################################################################################################## # ...
import numpy from amuse.couple import bridge from amuse.units import units, constants, quantities, nbody_system from amuse.ic.brokenimf import new_broken_power_law_mass_distribution from amuse.ic.plummer import new_plummer_sphere from amuse.community.huayno.interface import Huayno from amuse.community.seba.interface im...
# -*- coding: utf-8 -*- # Three possible modes: # 'cli': running from "wandb" command # 'run': we're a script launched by "wandb run" # 'dryrun': we're a script not launched by "wandb run" from __future__ import absolute_import, print_function __author__ = """<NAME>""" __email__ = '<EMAIL>' __version__ =...
""" AE.py (author: <NAME> / git: ankonzoid) Autoencoder class (for both simple & convolutional) """ from .AE_base import AEBase import datetime, os, platform, pylab, time import numpy as np import matplotlib.pyplot as plt from keras.layers import Input, Dense from keras.layers import Conv2D, MaxPooling2D, UpSampl...
# # utils.py # 2021-05-10 # Written by <NAME>, NIRAL, UNC # # Atlasbuilding utilities # import os # To run a shell command : os.system("[shell command]") import sys # to return an exit code import shutil # to remove a non empty directory import json import argparse import csv import copy import xml.etree....
import numpy as np import swarms.commons.utils as U dynamics = ['point', 'unicycle', 'box2d', 'direct', 'unicycle_acc'] class EntityState(object): """physical/external base state of all entities""" def __init__(self): # physical position self.p_pos = None self.p_orientation = None ...
''' This is a supporting library with the code of the model. ''' from __future__ import division import torch import torch.nn as nn from torch.nn import functional as F from torch.autograd import Variable from torch import optim import numpy as np import math, random import sys from collections import defaultdict impo...
import json import re from os.path import dirname, join import pandas as pd from .porter_stemmer import porter_stemmer from .snowball_stemmer import snowball_stemmer from .text import find_string, fingerprint, one_gram, two_gram def text_clustering(x, name_strategy="mostfrequent", key="porter", transformer=None): ...
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ These plugins modify the behavior of py.test and are meant to be imported into conftest.py in the root directory. """ from __future__ import (absolute_import, division, print_function, unicode_literals) from ..extern import six ...
#!/usr/local/bin/python3 ''' libradius(3) wrapper ''' import socket from ctypes import * from ctypes import util from collections import namedtuple from enum import IntEnum, unique RadiusAttribute = namedtuple('RadiusAttribute', ['type', 'data', 'datalen', 'vendor']) class DirctionaryChapter(IntEnum): # allow u...
import re import os import sys import json import logging import requests import xmltodict import ruamel.yaml from ats.easypy import runtime #genie from genie.utils import Dq from genie.testbed import load TIMS_URL = 'http://tims.cisco.com/xml/{}/entity-list.svc' log = logging.getLogger(__name__) ...
""" The implementation below uses code adapted from the `asdict` helper function from the library Dataclasses (https://github.com/ericvsmith/dataclasses). This library is available under the Apache 2.0 license, which can be obtained from http://www.apache.org/licenses/LICENSE-2.0. See the end of this file for the or...
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Name: gameLogs.py # Purpose: retrosheet game log file parsing # # Authors: <NAME> # # Copyright: Copyright © 2015-22 <NAME> / cuthbertLab # License: BSD, see license.txt # ----------------...
import pandas as pd import numpy as np import itertools def _bar2df(bars,data): """ get subset of data according to the location provided by bar_loc @parameters: data -- dataframe first column should be time second column should be price bars -- np.array each element in bars represe...
import torch.nn as nn import torch from typing import List, Union, Optional, Iterable from tqdm import tqdm from .rbm import RestrictedBoltzmannMachine class DeepBoltzmannMachine(nn.Module): ''' | A deep undirected hierarchical probabilistic model | From: [1] <NAME> "LEARNING DEEP GENERATIVE MODELS", ...
import json import os import sys import warnings from ctcdecode import CTCBeamDecoder from copy import deepcopy import cv2 import numpy as np from PIL import Image, ImageDraw, ImageFont from tqdm import tqdm warnings.simplefilter(action="ignore", category=FutureWarning) warnings.filterwarnings("ignore") import loggin...
# Self-Attentive Knowledge Tracing (SAKT) # # Paper: <NAME>, <NAME>. # A Self-Attentive model for Knowledge Tracing. # arXiv:1907.06837v1 [cs.LG] 16 Jul 2019 # # Code is adapted from: # http://nlp.seas.harvard.edu/2018/04/03/attention.html # # For further reference: # Paper: <NAME>, <NAME>, <NAME>, et al. #...
from Checkers.Game import * from Constants import * if USE_PY_GAME: import pygame import time # technical constants ENABLE_LOOP_WAIT = False TICK_RATE = 60 TICK_TIME = 1.0 / TICK_RATE E_RED_PLAYING = "Red's Turn" E_BLACK_PLAYING = "Black's Turn" E_TEXT_COLOR = (0, 0, 0) E_GAME_STATE_X = 10 E_GAME_STATE_Y = 10 ...
#!python3 from __future__ import annotations from . import pages from .pages import models, socketio from .data import ChatMessage, Vote, VoteEntry, Message from flask_socketio import join_room, emit from flask_login import current_user from flask import request from functools import wraps from operator import attrge...
import numpy as np import tensorflow as tf from scipy.misc import logsumexp from tqdm import tqdm from keras import backend as K from event_models import GRUEvent class Results(object): """ placeholder object to store results """ pass class SEM(object): """ This port of SAM's code (done with a diffe...
import numpy as n, string, re, builtins as B, langid def doubleColumn(tablefname): with open(tablefname,"r") as f: lines=f.read() l=lines.replace("\\begin{table}","\\begin{table*}").replace("\\end{table}","\\end{table*}") writeTex(l,tablefname) def fSize(tablefname,ftag="scriptsize",write=False): ...
import calendar import datetime import json import logging from copy import copy from pathlib import Path import numpy as np import pandas as pd import xarray as xr from jsonschema import validate from scipy.interpolate import CubicSpline from ioos_qc.config_creator import fx_parser L = logging.getLogger(__name__) ...
''' This module defines various PP Attachment models and comes with a CLI to train and test them. ''' import sys import codecs import argparse import random import json import numpy from overrides import overrides from keras.layers import Input, Bidirectional from keras.models import Model from encoders import LSTME...
import numpy as np import cmath import torch def rot(euler: tuple) -> torch.tensor: """ General rotation matrix :param euler: (a, b, r) rotation in rad in ZYX :return R: a rotation matrix R """ from math import sin, cos a, b, r = euler[0], euler[1], euler[2] row1 = torch.tensor([c...
#!/usr/bin/env python #============================================================================== # Copyright 2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Amazon Software License (the "License"). You may not use # this file except in compliance with the License. A copy of the...
from pyvirtualdisplay import Display from selenium import webdriver import time, sys, pickle from selenium.webdriver.common.keys import Keys import telegram, requests, json, sys, pickle telegram_token = "<PASSWORD>:AAG8gXOD<PASSWORD>G6LOUApg<PASSWORD>ABJK<PASSWORD>" kingsley_telegram_id = "553991636" bukunmi_telegra...
#!/usr/bin/python3.9 # Copyright (c) 2022 <NAME> # pylint: disable=subprocess-run-check import cProfile import dataclasses import json import logging import os import socket import subprocess import sys import time import traceback from pathlib import Path from typing import Optional import psycopg import redis import...
import numpy as np import pandas as pd import os import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages from utils.definitions import ROOT_DIR from mpl_toolkits.axes_grid1 import host_subplot import mpl_toolkits.axisartist as AA def __list_files_by_name(path, similarity, variable_posit...
''' Define different PyTorch modules for the different targets, including loss functions ''' import numpy as np import torch import torch.nn as nn from torch.distributions import Poisson import torch.nn.functional as F from functools import partial from collections import OrderedDict import math # some basic modules ...
import mock import pytest from _pytest.config import Config from _pytest.junitxml import _NodeReporter from _pytest.python import Function from _pytest.runner import TestReport as PytestReport from pytest_sherlock.binary_tree_search import Root from pytest_sherlock.sherlock import ( Bucket, Collection, She...
""" path finding implementation 1) For each position on the map, create a node representing the position. 2) For each NPC/item, mark nearby nodes as members of that NPC's threat zone (note that they can be members of multiple zones simultaneously). """ import pokemontools.configuration config = pokemontools.config...
#!/usr/bin/env python # # DNSSEC Trust Anchor Fetcher # https://github.com/kirei/get_trust_anchor # # Copyright (c) 2016, <NAME>. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistribution...
""" Code to work with the equation verification dataset from [Arabshahi et al. 2020]. The dataset can be loaded in three formats: - Parentheses: mathematical expressions are provided as a textual sequence in infix order, with parentheses indicating structure (e.g. " ( 2 * y ) + ( x * 3 ) "). - Positional encoding...
# import libraries import pandas as pd import numpy as np from fancyimpute import MICE from sklearn.model_selection import train_test_split # read data churn = pd.read_csv("telecom_churn_data.csv") # Sample Data for Preprocessing churn = churn.head(10) # create backup of data original = churn.copy() # create column ...
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from sklearn.preprocessing import StandardScaler from sklearn.model_selection import cross_val_score from sklearn.ensemble import RandomForestClassifier as RFC from sklearn.metrics import make_scorer, accuracy_score, precision_score, recall_score...
""" Some utilities for wrangling image data """ import numpy as np import scipy.io from matplotlib import pyplot as plt def get_low_pass_filter(DFT_num_samples, filter_parameters): """ Returns the DFT of a lowpass filter that can be applied to an image Parameters ---------- DFT_num_samples : (int, int) ...
#! /usr/local/bin/python3 """ Functions to format the dicts that can appear in the body section """ import os import sys from traceback import print_stack import Any import html_utils from pgconnection import PgConnection if os.getenv('DEBUG_BODY_RULES'): DEBUG = True else: DEBUG = False from format_body_qualif...
import matplotlib as mpl import matplotlib.pylab as plt import numpy as np import pandas as pd mpl.style.use('seaborn-paper') from util.constants import MAX_SEQUENCE_LENGTH_LIST, NB_CLASSES_LIST def load_dataset_at(index, normalize_timeseries=False, verbose=True) -> (np.array, np.array): """ Loads a Univara...
#coding=utf-8 from functools import partial import types import Tkinter as tk import ttk import tkMessageBox from ..variables import BoolVar from ..variables import NotifyStringVar, NotifyNumericVar, NumericVar def setPanelState(frame, state): for child in frame.winfo_children(): if isinstance(child, tk...
# -*- coding: utf-8 -*- import os import time import runpy import scipy import numpy as np import tensorflow as tf import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from pprint import pprint from tensorflow.keras import optimizers from tensorflow.keras.optimizers.schedules import ExponentialDecay ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Oct 7 18:05:50 2020 @author: mints """ import time import joblib import numpy as np from semiphore_public.utils.params import BANDS, LIMITS, EXTINCTIONS from semiphore_public.cuda import gpu import pandas as pd from numba import cuda import math import...