text
stringlengths
3.07k
12.6k
import warnings from .exceptions import ( ValidationError, TooManyConditions, InvalidPriority, InvalidTimeToLive, InvalidDataKey, ) INVALID_DATA_KEYS = frozenset(( 'from', 'to', 'registration_ids', 'condition', 'notification_key', 'collapse_key', 'priority', 'conten...
import re import time import requests from pandas import DataFrame from pandas import read_csv import os.path as op # for PyCharm # from src.helpers.mylogger import get_handler from ..mylogger import get_handler import logging handler = get_handler(log_type="module") log = logging.getLogger(__name__) log.handlers...
import random from collections import defaultdict class InconsistencyError(Exception): pass class Collapser(object): def __init__(self, nodes, states): self.valid = {} self.dirty = {} self.states = frozenset(states) self.nodes = nodes for n in nodes: r = s...
from copy import copy, deepcopy from random import choice, uniform from numpy import array from algorithms.common.neural_network.activation_function import _NON_LINEAR_ACTIVATION_FUNCTIONS from algorithms.common.neural_network.connection import Connection from algorithms.common.neural_network.node import Neuron, Sens...
#!/usr/bin/env python import tensorflow as tf import numpy as np import scipy.signal from scipy import misc import scipy.io from PIL import Image import json import os from offline_feature import * from bbox_tool import * import glob from reward_function import * from semantic_environment import * from shortest_path im...
"""Autoencoder PyTorch example. Here we'll train an autoencoder based on the MNIST dataset. """ # Import import pathlib import time import torch import torch.utils.data import torchvision.datasets import torchvision.transforms import matplotlib.pyplot as plt def main(): # Determine if we're running on the CPU ...
import os from unittest import TestCase import vcr from erpbrasil.assinatura.certificado import Certificado from erpbrasil.base import misc from erpbrasil.transmissao import TransmissaoSOAP from requests import Session from erpbrasil.edoc.provedores.cidades import NFSeFactory try: from nfselib.ginfes.v3_01.servi...
import os import time import torch import numpy as np from elegantrl_helloworld.env import build_env from elegantrl_helloworld.agent import ReplayBuffer, ReplayBufferList def train_agent(args): args.init_before_training() gpu_id = args.learner_gpus '''init''' env = build_env(args.env_func, args.env_...
from Bio import Entrez from Bio import SeqIO import numpy as np import sys import os import json import csv from collections import defaultdict, OrderedDict import re from markdown2 import Markdown from scipy import stats from utils import importData, reference_retreive, div0 def map_PTMs(options, data, refProt...
from time import time from typing import Union from logging import getLogger from networkx import DiGraph, NetworkXException, has_path from numpy import ndarray from numpy.random import RandomState LOG = getLogger(__name__) def check(G, max_res=None, min_res=None, direction=None, ...
""" Usage: update.py [options] Options: --profile PROFILE profile to use for AWS access. Note that you can update multiple accounts by using a wildcard '*' in the profile name, like this: python update.py --profi...
#!/usr/bin/python3 # This file is part of becalm-station # https://github.com/idatis-org/becalm-station # Copyright: Copyright (C) 2020 <NAME> <<EMAIL>> # License: Apache License Version 2.0, January 2004 # The full text of the Apache License is available here # http://www.apache.org/licenses/ ...
import requests from datetime import datetime from celery.task import task from django.conf import settings from django.utils import timezone from .models import ( Flow, DailyFlowRuns, Group, DailyGroupCount, DailyChannelCount, Channel, Label, LabelMessage, ) def get_all_results(next_...
# -*- coding: utf-8 -*- # Copyright © 2007-2008 Stockholm TreeAligner Project # Author: <NAME> <<EMAIL>> # Licensed under the GNU GPLv2 import cPickle import cStringIO import zlib from nltk_contrib.tiger.graph import NodeType, TigerGraph, NonterminalNode, TerminalNode __all__ = ("GraphSerializer", "GraphDeserializer"...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import os import re from collections import defaultdict def path_splitter(path): """ Split a path into its constituent parts. Might be better written as a recursive function. :param path: The path to split. :retu...
import copy import logging import os.path import pathlib import re import shutil import tempfile import mkhost.cfg import mkhost.cfg_parser import mkhost.common re_key_value = re.compile( '^(\w+)\s+(\S+)\s*$', re.ASCII) OPENDKIM_CONFIG = { "AllowSHA1Only" : False, "KeyTable" : mkhost.cfg.OPEND...
from google.appengine.ext import ndb from ..models import SportModel, EventModel, MatchModel, BetModel from random import randint from XMLOddsParser import parseXMLOdds import MatchValidator def populate_odds(): sports = parseXMLOdds() for sport in sports: if sport["name"] in ["Football"...
import os import uuid from glob import glob from typing import TYPE_CHECKING, Union import gin import yaml from tqdm import trange from colosseum.utils.miscellanea import ensure_folder if TYPE_CHECKING: from colosseum.mdps import MDP def find_hardness_report_file( mdp: "MDP", hardness_reports_folder="hardn...
#!/usr/bin/env python3 # # DirDigger # --------- # A simple Python script that tries to do something like DIRB or DirBuster. # # Coded by: <NAME> (<EMAIL>) # import argparse import getopt import os import re import requests import signal import socket import subprocess import sys import time import urllib3 import val...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (...
import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as f from torch.autograd import Variable import os import numpy as np from tqdm import tqdm import sys def reparameterize(mu, logvar): eps = Variable(torch.randn(mu.size(0), mu.size(1))).cuda() z = mu + eps * ...
import pytest from datahub.omis.order.test.factories import ( OrderAssigneeFactory, OrderCancelledFactory, OrderCompleteFactory, OrderFactory, OrderPaidFactory, OrderSubscriberFactory, OrderWithAcceptedQuoteFactory, ) from datahub.search.omis import OrderSearchApp from datahub.search.omis.m...
import time import pytest import json import re import autoposter from autoposter import select_threads, Poster import api class TestAutoposter: @pytest.fixture(autouse=True) def fake_opts(self, monkeypatch): monkeypatch.setattr(autoposter, 'OPTS', OptsFake()) @pytest.fixture() def fake_request_for_select(self...
import urllib.request import xmltodict, json #import pygrib import numpy as np import pandas as pd from datetime import datetime import time # Query to extract parameter forecasts for one particular place (point) # # http://data.fmi.fi/fmi-apikey/f96cb70b-64d1-4bbc-9044-283f62a8c734/wfs? # request=getFeature&storedq...
# Copyright 2021, <NAME>, mailto:<EMAIL> # # 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 w...
# Copyright (c) 2017 Ansible by Red Hat # All Rights Reserved. from __future__ import unicode_literals import kombu import six import uuid import msgpack import socket import threading import datetime import jsonpickle from asgiref.base_layer import BaseChannelLayer from collections import deque from kombu.pools im...
import matplotlib import math import collections import re import sys from Line import Line from Bar import Bar def getGoldenRatioDimensions(width): goldenRatio = (math.sqrt(5) - 1.0) / 2.0 return (width, goldenRatio * width) def getXYValsFromFile(filename, regex, postFunction=None, auto...
import numpy as np from sklearn.preprocessing import StandardScaler from sklearn.linear_model import Lasso, LogisticRegression from penlm.base_estimators import BaseClassifier, BaseRegressor from typing import Dict class Rel...
# Importing some modules and setting up a few properties import sys import os import csv from zipfile import ZipFile sys.path.append(os.getcwd()) os.environ["DJANGO_SETTINGS_MODULE"] = "tsdb_app.settings" import django django.setup() from core.models import Tag, FundSource, Organization, Strategy, Initiative, SocialP...
# import os # # os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # see issue #152 # os.environ["CUDA_VISIBLE_DEVICES"] = "0" import tensorflow as tf import tensorflow.compat.v1 as tf tf.disable_v2_behavior() from keras.backend.tensorflow_backend import set_session config = tf.ConfigProto() config.gpu_options.allow_grow...
import logging import time from .shell_utils import run logging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s') logger = logging.getLogger() logger.setLevel(logging.INFO) def _get_resource_info( resource_type="pod", labels={}, json_path="{.items[].metadata.name}", error...
import random from sqlalchemy.exc import IntegrityError from app import app, db, photos from flask import render_template, redirect, url_for, session, flash from models import * from forms import * from app_func import * from mail_client import * #Index @app.route('/') def index(): products = Product.query.a...
import os from skimage import io, transform import torch import torchvision from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as F from torch.utils.data import Dataset, DataLoader from torchvision import transforms#, utils import cv2 # import torch.optim as optim from data import test...
import asyncio from aiohttp import ( web, ClientSession, ClientRequest, ClientResponse, ClientError, ClientTimeout, ) import json from time import sleep ###################################################################### # coroutine utilities ################################################...
import os import boto3 import zipfile import logging import json import decimal from botocore.exceptions import ClientError import decimal from app.utils import utility_dynamo from app.utils import config, helpers logger = logging.getLogger() logger.setLevel(logging.INFO) s3 = boto3.client("s3", use_ssl=False) # tab...
import numbers import collections.abc import warnings import numpy import numpy.random import numpy.lib.recfunctions from logging import getLogger _log = getLogger(__name__) __all__ = ["sample"] def __generate_points(rng, N, lower, upper, ndim): ret = numpy.zeros((sum(N), ndim + 2)) _log.debug('{} points ...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ *t4mon* - T4 monitoring base test functions for functional tests """ import sys import pickle import shutil import logging import tempfile import unittest from os import path import numpy as np import pandas as pd from t4mon import logger from t4mon.arguments import ...
# import face_recognition import os import time from milvus import Milvus, DataType import psycopg2 import numpy as np import random from faker import Faker fake = Faker() MILVUS_collection = 'mixe_query' PG_TABLE_NAME = 'mixe_query' FILE_PATH = 'bigann_base.bvecs' VEC_NUM = 1000000 BASE_LEN = 100000 VEC_DIM =...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # pe_patch.py # # Copyright 2017 <NAME> <<EMAIL>> # # 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 copyri...
from django import forms from django.conf.urls import * from django.forms import BaseInlineFormSet from django.contrib import admin, messages from django.http import HttpResponseRedirect from django.contrib.auth.admin import UserAdmin from django.contrib.auth.forms import ReadOnlyPasswordHashField from squad_pantry_app...
import argparse import datetime import logging import os import sys import dateutil.parser import pytz import requests from influxdb import InfluxDBClient # sys.path.append(os.path.dirname(os.path.realpath(__file__))) from config.config import API_KEY, API_URL, KPLIST UNITS = {"s": 1, "m": 60, "h": 3600, "d": 86400,...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Module for computing markov transition probability matrices from nucleotide sequence stored as text files. compute() is the main function that wraps around smaller modular functions. @author: pranay """ # Import calls from pathlib import Path from random import choi...
from datetime import timedelta from django.db import transaction from django.db.models import F, Sum from django.utils import timezone from rest_framework import serializers from care.facility.models import ( FacilityInventoryBurnRate, FacilityInventoryItem, FacilityInventoryItemTag, FacilityInventory...
""" Convert 3DPW to TFRecords. 3DPW is NOT used for training. Therefore this script only saves the test tfrecords. Rectifies the 3DPW data so that camera is identity. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import pickle import os from os.path...
""" BaseDataset class """ from typing import Sequence, Union, Dict from pathlib import Path import random import re import yaml import torch import pandas as pd import numpy as np SequenceOrTensor = Union[Sequence, torch.tensor] class Attribute: """ class Attribute """ def __init__(self, d: Dict[s...
#-----------------------# i = 10 # #-----------------------# import subprocess # import time # import os # import requests #-------------# from terminaltables import SingleTable# #-------------------------------------# #log function def log(): log = datetime.datetime.now().time() handle = open("....
import copy import math import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable def clones(module, N): # Produce N identical layers. return nn.ModuleList([copy.deepcopy(module) for _ in range(N)]) class LayerNorm(nn.Module): """Construct a L...
from collections import namedtuple import torch import torch.nn as nn import torch.nn.functional as F __all__ = ['Inception3', 'inception_v3'] model_urls = { # Inception v3 ported from TensorFlow 'inception_v3_google': 'https://download.pytorch.org/models/inception_v3_google-1a9a5a14.pth', } _InceptionOuput...
from flask import request from flask_jwt_extended import jwt_required, get_jwt_identity from flask_restplus import Resource from api.middlewares.base_validator import ValidationError from api.models import Favorite, Category, Audit from api.schemas.favorite_schema import FavoriteSchema from api.utilities.helpers.respo...
#!/usr/bin/env python # coding: UTF-8 # # @package SimulationPanel # @author <NAME> # @date 08/10/2020 # # Class for presenting the simulation in a graphical form. # ## from random import randint from Disease import Disease from tkinter import Tk, Canvas from MyWorld import MyWorld from Timer import Timer from mapper ...
import sys, logging, os, random, math, open_color, arcade, time #check to make sure we are running the right version of Python version = (3,7) assert sys.version_info >= version, "This script requires at least Python {0}.{1}".format(version[0],version[1]) #turn on logging, in case we have to leave ourselves debugging...
''' Analysis of COVID-19 data This module is only used with tweeter.py and is no longer being updated. All plots are generated using JHU github repository data that is imported into a pandas DataFrame and plotted with matplotlib to create image files that are tweeted daily by tweeter.py in the package. ''' import date...
from variables import * import matplotlib.pyplot as plt from Launching import final_velocity_calculation def coef_calculation(c, p, A, mass): coef = 0.5 * c * p * A / mass return coef coef = coef_calculation(c, p, A, fruit_weight) def traj_fr(coef, angle, v0, inity): # function that computes trajectory f...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Este script se encarga de generar el archivo de misión con los datos que ingrese el usuario""" # Imports import os import cgi # globales CARPETA_MISION = "" AUTOR = '"ZR Army - Dept. Tecnico y Diseño";' NOMBRE_MISION = '"TEMPLATE ZR";' QUIERE_FOTO = False FOTO_MISION...
# Copyright 2012-2015 MongoDB, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writin...
from dataclasses import dataclass, field import sys import random from typing import List, Sequence, Set, Tuple from itertools import combinations, product import timeit import matplotlib.pyplot as plt from models import Instance @dataclass class Solver: @dataclass class Solution: _solver: 'Solver' ...
from datetime import datetime as DateTime, timedelta as TimeDelta from enum import Enum from collections import namedtuple from structdict import named_fixed_struct_dict import numpy as np from utils.matrix_utils import atleast_2d_col _TARIFF_TYPES = ['low_off_peak', 'low_stnd', 'low_...
import numpy as np import matplotlib.pyplot as plt import json import operator generos = { '0': 'Masculino', '1': 'Feminino' } candidatos = { '0': '<NAME>', '1': '<NAME>', '2': '<NAME>', '3': 'Eymael', '4': '<NAME>', '5': '<NAME>', '6': '<NAME>', '7': '<NAME>', '8': '<NAME>...
# Import required module/s import csv def readMarkSheet(file_name): """Reads the input CSV file of Mark Sheet and creates a mapping of student name with his/her marks for each subject. Parameters ---------- file_name : str CSV file name of Mark Sheet Returns ------- dict Mapping of each student's name and...
# !/bin/python # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """State Machine Router module""" import os.path import botocore import boto3 from state_machine.utils.logger import Logger from state_machine.state_machine_handler import ( TransitGateway, ...
#*************************************************************************************************** # Imports #*************************************************************************************************** # Global imports import os import threading from typing import Union import json # Project imports import m...
import torch from torch import nn from torch.distributions import Normal, Bernoulli, MultivariateNormal import numpy as np class NormalProposal(nn.Module): # this doesn't need to be a module, but other proposal # distributions will have learned parameters so might as # well start here def __init__(sel...
import os import pytest from botocore.stub import Stubber from unittest.mock import patch from AwAws.Organizations.accounts import Accounts mock_acc = 'AwAws.Organizations.accounts.Accounts' @pytest.fixture def env(): os.environ['AW_MASTER'] = '987659876512' yield os.environ.pop('AW_MASTER') def test...
import json import logging import os from cryptoadvance.specter.managers.genericdata_manager import GenericDataManager from cryptoadvance.specter.managers.singleton import ConfigurableSingleton from cryptoadvance.specter.specter_error import SpecterError from cryptoadvance.specter.user import User logger = logging.ge...
# linear_transform.py # <NAME> School of Design Engineering from manim import * """ (1) FOR R, ENTER THE TRANSFORMATION SCALAR BELOW: """ scalar = -2 """ Then, render with: manim -pqh linear_transform.py R (2) FOR R2, ENTER THE TRANSFORMATION MATRIX BELOW: """ M2 = np.array([ [1, 2], ...
from pathlib import Path from typing import * import torch import torch.optim as optim import numpy as np import pandas as pd from functools import partial from overrides import overrides from allennlp.data import Instance from allennlp.data.token_indexers import TokenIndexer from allennlp.data.tokenizers import Token...
import importlib import imp from .s3_sync import * from .custom_losses import * from .metrics import * def get_w1_w0_training(args,train_generator): w1=args.w1 w0=args.w0 if (args.w1_w0_file is not None) and (args.w1_w0_file.startswith('s3://')): w1_w0_file=download_s3_file(args.w1_w0_file) el...
import gzip import csv import math import argparse import datetime import os import subprocess def differ(l1, l2): for i in range(len(l1)): if (i % 2 == 1 and abs(l2[i] - l1[i]) > 1e-8) or (i % 2 == 0 and abs(l2[i] - l1[i]) > 0.01): if i % 2 == 1 and (l2[i] - l1[i]) > 1e-8: if ...
import collections import filecmp import os import sys import pytest import munge import munge.codec.all this_dir = os.path.dirname(__file__) data_dir = os.path.join(this_dir, "data") test_codecs = [] for tags, cls in list(munge.get_codecs().items()): if any(name in ("json", "toml", "yaml") for name in tags): ...
# These function can return and Column Expression or a list of columns expression # Must return None if the data type can not be handle # from dask_cudf.core import DataFrame as DaskCUDFDataFrame import cudf from optimus.engines.base.functions import Functions from dask_cudf import Series import random import stri...
import pdb import argparse import csv import os from tqdm import tqdm import torch import torch.nn as nn from torch.autograd import Variable import torch.backends.cudnn as cudnn from torchvision import datasets, transforms from utils import Cutout from models import * from utils import progress_bar dataset_option...
import json import numpy as np import pickle import argparse import os import neptune import torch import torch.nn as nn from torch.utils.data import Dataset, DataLoader from torchvision.models import resnet18 from module.load_module import load_model, load_loss, load_optimizer, load_scheduler from utili...
import sys, os import re, string import requests, urllib.request import colorama import socket, socks import asyncio, aiohttp, time, concurrent, random from termcolor import colored from bs4 import BeautifulSoup from fake_useragent import UserAgent from proxybroker import Broker CONFIG_FILE = '_config.xml' colorama.i...
"""Copy files to remote, using earlier collected host-information. Use ``shelephant_hostinfo`` to collect host-information. By default the back-end is ``rysnc -a --from-file="temp" source_dir host:dest_dir``. Alternatively ``scp -p source_file host:dest_file`` can be used. Typically, *rsync* will be faster, especially...
"""Provides ray analogue to `multiprocessing.Manager` class.""" import abc from collections import deque import time from typing import Generic, TypeVar import ray from ray.experimental.queue import Empty, Full, Queue V = TypeVar("V") class Value(Generic[V]): @abc.abstractproperty def value(self) -> V: ...
# -*- coding: utf-8 -*- """ @author: <NAME> <<EMAIL>> """ import torch import torch.nn as nn import torch.nn.functional as F class BasicConvResBlock(nn.Module): def __init__(self, input_dim=128, n_filters=256, kernel_size=3, padding=1, stride=1, shortcut=False, downsample=None): super(BasicConvResBlock,...
# Run a whole brain searchlight # Import libraries import nibabel as nib import numpy as np from mpi4py import MPI from brainiak.searchlight.searchlight import Searchlight from sklearn.model_selection import StratifiedShuffleSplit, GridSearchCV from sklearn.svm import SVC from scipy.spatial.distance import euclidean i...
# -*- coding: utf-8 -*- """Align the OBO Foundry with the Bioregistry.""" import requests import requests.exceptions import requests_ftp from ..external import get_obofoundry from ..utils import norm, secho, updater requests_ftp.monkeypatch_session() session = requests.Session() OBO_KEYS = { 'id', 'prefix'...
import pygame import sys import numpy as np pygame.init() WIDTH = 600 HEIGHT = 600 LINE_WIDTH = 15 WIN_LINE_WIDTH = 15 BOARD_ROWS = 3 BOARD_COLS = 3 SQUARE_SIZE = 200 CIRCLE_RADIUS = 60 CIRCLE_WIDTH = 15 CROSS_WIDTH = 25 SPACE = 55 BG_COLOR = (255,0,0) LINE_COLOR = (0,0,0) CIRCLE_COLOR = (239, 231...
# coding=utf-8 """A collection of utility functions non-specific to mapi's domain logic.""" import random import re from os import path from sys import version_info import requests_cache from appdirs import user_cache_dir from requests.adapters import HTTPAdapter from mapi import log from mapi.compatibility import ...
"""Commonly used calculations on electrical quantities.""" from __future__ import division import numpy as np import math import cmath import sys import time import six import scipy.io as sio #from numba import jit def Uunbalance_calc(ua,ub,uc): """Calculate voltage/current unbalance.""" uavg = (ua...
import requests, os, time, math, glob, argparse from threading import Thread from urllib.parse import urlparse class Globals: def __init__(self): self.contained = {} def put(self,name,value): self.contained[name] = value def get(self,name): return self.contained[name] def has...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Oct 19 09:42:17 2021 @author: philippbst """ import torch import torch.nn as nn import torch.nn.functional as F from torch.optim import Adam from torch.utils.data import DataLoader from torch.optim.lr_scheduler import StepLR import numpy as np from neu...
"""Functions to read and process data from a LittleChef repository""" import os import simplejson as json from littlechef import runner, lib, chef from logbook import Logger from kitchen.settings import REPO, REPO_BASE_PATH from kitchen.backends.plugins import plugins log = Logger(__name__) KITCHEN_DIR = os.path.jo...
#!/usr/bin/env python # -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright (c) 2017 - <NAME> - MIT License # ----------------------------------------------------------------------------- import re from docutils import nodes from docutils.parsers.rst import ...
import errno import fnmatch import os import os.path import shutil import subprocess import sys import tarfile import requests import stat import dbt.compat import dbt.exceptions from dbt.logger import GLOBAL_LOGGER as logger def find_matching(root_path, relative_paths_to_search, ...
import os import json import datetime import requests from binance.enums import * from loguru import logger from crypto_bot.crypto import get_price_changes, get_top_crypto from crypto_bot.aws import S3 from crypto_bot.binance import binance INITIAL_BALANCE = 500 BUCKET_NAME = "cryptobotmetadata" BALANCE_PATH = "ba...
#!/usr/bin/env python ###################################################################################### # AUTHOR: <NAME> <<EMAIL>> # CONTRIBUTORS: <NAME> <<EMAIL>>, <NAME> <<EMAIL>> # DESCRIPTION: Perform a correlation analysis of two datasets. ######################################################################...
""" The MIT License (MIT) Copyright (c) 2015-present Rapptz 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,...
import pytest import serverly.utils from serverly.utils import * def test_parse_role_hierarchy(): e1 = { "normal": "normal", "admin": "normal" } e2 = { "normal": "normal", "admin": "normal", "staff": "admin", "root": "staff", "god": "staff", } ...
# emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the NiBabel package for the # copyright and license terms. # ### ### ### #...
import os import re import json import pandas as pd import tqdm.notebook as tq from collections import namedtuple def parse_squad(raw_squad): """ function used to parse the squad dataset """ def fix_index(context, idx, step=1): """ function used to fix an index of an answer such that it covers the w...
#!/usr/bin/env python3 # coding: utf8 # Author: <NAME>, 2019 """ Retrieve similar strings based on cosine distance of s-grams. """ from __future__ import unicode_literals import itertools as it from collections import Counter import numpy as np from scipy.sparse import csr_matrix __version__ = '1.0.0' # Py2...
import argparse import ast import importlib from typing import * import albumentations as A import numpy as np import torch import yaml from albumentations.pytorch import ToTensorV2 from omegaconf import DictConfig from PIL import Image from pytorch_retinanet.retinanet.models import Retinanet from torch import nn from...
r"""Evaluate language model on dataset. Tool for evaluating language model on dataset. Pre-trained model are used to calculate perplexity on dataset. This script serve as model validation, and it is usually run after training model. All evaluation results will be shown on both CLI and tensorboard. Use ``pipenv run ten...
import copy import datetime import logging from sys import stderr import numpy as np import torch from sklearn.metrics import f1_score, precision_score, recall_score, accuracy_score # logger = logging.getLogger(__name__) def debug(*msg, sep=' '): print(sep.join((str(m) for m in msg))) def evaluate_loss(model,...
import numpy as np import pandas as pd from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score from sklearn.metrics import confusion_matrix import itertools import matplotlib.pyplot as plt import tensorflow as tf from tensorflow.keras import Sequential from tensorflow.keras.models import loa...
import csv from .postgre_model import Postgres_DB import datetime PROPERTIES_OF_TABLE = [ { "table_name": "Inventory", "column_1": "Brand", "column_2": "Batch ID" }, { "table_name": "Sales", "column_1": "<NAME>", "column_2": "Current Loyalty Points" }, ...
# ActivitySim # See full license in LICENSE.txt. import logging import os import numpy as np import pandas as pd logger = logging.getLogger(__name__) def undupe_column_names(df, template="{} ({})"): """ rename df column names so there are no duplicates (in place) e.g. if there are two columns named "...
from microgridRLsimulator.agent.agent import Agent from collections import namedtuple from collections import defaultdict import math import random from microgridRLsimulator.simulate.simulatorMCTS import SimulatorMCTS from microgridRLsimulator.utils import time_string_for_storing_results microgrid_node = namedtuple("m...