text
stringlengths
3.07k
12.6k
import json import os.path as osp from collections import namedtuple, OrderedDict, defaultdict from enum import Enum from numbers import Number import numpy as np GitInfo = namedtuple( 'GitInfo', [ 'directory', 'code_diff', 'code_diff_staged', 'commit_hash', 'branch_nam...
import os from dataclasses import dataclass, field from itertools import combinations from typing import Any, TextIO import numpy as np from parse import parse from pyrr import Matrix33, Vector3 class ScannerMatched(Exception): pass ROTATIONS = [ Matrix33.from_eulers((0, 0, 0), dtype=np.int_), Matrix33...
''' For processing MARC/XML Uses SAX for streaming process Notice however, possible security vulnerabilities: https://docs.python.org/3/library/xml.html#xml-vulnerabilities ''' import re from collections import defaultdict, OrderedDict import unicodedata import warnings import xml.parsers.expat from versa import I, ...
""" This module implements classes and utility functions to manage STC project. Any command that can act on list of objects (ports, devices, emulations etc.) should be implemented by StcProject. """ import time from typing import Dict, List from trafficgenerator.tgn_tcl import build_obj_ref_list from testcenter.stc_...
"""Script to download all the data we need for GPV experiments""" import argparse import logging import tarfile import tempfile from os import makedirs from os.path import exists, join from gpv2 import file_paths from gpv2.data.dataset import Task from gpv2.data.dce_dataset import DceDataset from gpv2.utils import py...
import abc from dataclasses import dataclass import math import torch from .basedist import ExponentialFamily from .basedist import ConjugateLikelihood __all__ = ['NormalDiagonalCovariance', 'NormalDiagonalCovarianceStdParams', 'NormalFixedDiagonalCovarianceLikelihood'] @dataclass class NormalFixedDiagona...
#!/usr/bin/env python from keras.applications.vgg16 import VGG16, preprocess_input, decode_predictions from keras.preprocessing import image from keras.layers.core import Lambda from keras.models import Sequential, load_model from tensorflow.python.framework import ops import keras.backend as K import tensorflow as tf...
import random import operator from . import storage from .core import command class Quotes(storage.SelectableStorage): lib = 'pmx' @classmethod def initialize(cls): cls.store = cls.from_URI() cls._finalizers.append(cls.finalize) @classmethod def finalize(cls): del cls.store @staticmethod def split_nu...
import math import global_number def get_solar_radiation_on_inclined_surfaces( normal_surface_direct_radiation: float, horizontal_surface_sky_radiation: float, solar_altitude: float, solar_azimuth: float, surface_tilt_angle: float, surface_azimuth: float) -> float: """ 傾斜面日射量を求める関数 :param ...
from pathlib import Path import numpy as np from skimage.draw import disk from skimage.io import imsave from PIL import Image from tqdm import tqdm import tables from skimage.transform import rescale, resize, downscale_local_mean import sys sys.path.append("../") from derive_dataset import get_max_r2 PATH = "/mn...
import pytest from unittest.mock import MagicMock, patch import base64 import os import requests import time import gen3.auth from gen3.auth import Gen3Auth test_endpoint = "https://localhost" test_key = { "api_key": "whatever." + base64.urlsafe_b64encode( ('{"iss": "%s", "exp": %d }' % (test_endpoint...
""" File name: health_agents.py Author: <NAME> (u6617017) Date: 8 March 2018 Description: This file contains agents which fight disease. It is used in Exercise 4 of Assignment 0. """ import random class HealthAgent: """ A simple disease fighting agent. """ def __in...
"""Routines for Stage Three of CUSP: Generative Model Search.""" import numpy as np from multiprocessing import Pool from cirq import Circuit, MeasurementGate, ParamResolver from cirq.ops import * from cirq.google import ExpWGate, ExpZGate, XmonSimulator from cirq.circuits import InsertStrategy from cirq.contrib.job...
import math import random import numpy as np N_CLASSES = 10 N_AMOSTRAS = 100 TEMPO_ENTRE_CHEGADA = 5 TEMPO_ENTRE_SERVICO = 5 TAMANHO_MAX_FILA = 10 def gera_amostras_exponencial(tam, param_lambda): amostras = [] for i in range(0, tam): amostras.append(math.floor(np.random.exponential(param_lambda))) ...
from datetime import date from telegram import ParseMode from modules.utils import load_config import modules.graphs as graphs import modules.c19api as c19api cfg = load_config() settings = cfg["bot"] def chatid(update, context): context.bot.send_message( chat_id=update.message.chat_id, text=f"Ch...
# standard libraries import datetime import itertools from collections import defaultdict # external libraries import pandas as pd from sklearn.cluster import MeanShift # internal libraries from hysynth.utils.hybrid_system import HybridSystemPolyhedral from hysynth.pwl.library import check_clustering_bandwidth from h...
from __future__ import absolute_import import struct from collections import namedtuple from . import _enum_base ofp_oxm_class = type("ofp_oxm_class", (_enum_base,), { "prefix": "OFPXMC", "numbers": { "NXM_0": 0x0000, "NXM_1": 0x0001, "OPENFLOW_BASIC": 0x8000, "EXPERIMENTER": 0xFFFF } })...
# SPDX-License-Identifier: Apache-2.0 # # The OpenSearch Contributors require contributions made to # this file be licensed under the Apache-2.0 license or a # compatible open source license. # Modifications Copyright OpenSearch Contributors. See # GitHub history for details. # Licensed to Elasticsearch B.V. under one ...
#!/usr/bin/env python3 import ipaddress import json import logging import os import os.path import socket import ssl import sys from pathlib import Path from time import sleep import dns.resolver import dns.zone import requests import requests_cache from cryptography import x509 from cryptography.hazmat.backends impo...
#! /usr/bin/env python3 import subprocess import yaml import time import os import threading import logging import argparse parser = argparse.ArgumentParser() parser.add_argument('--file', required=False, default="spike_log.csv", help="Output CSV file name with logs", dest="log_file") def creat...
import os from leapp.libraries.actor import multipathconfupdate from leapp.libraries.common import multipathutil from leapp.models import MultipathConfig, MultipathConfigOption CUR_DIR = os.path.dirname(os.path.abspath(__file__)) def build_config(val): all_devs_options_val = [] for name_val, value_val in va...
#!/usr/bin/env python3 import re import os import subprocess import csv from lxml import etree def split_qname(name): if name[0] == '{': return name[1:].split('}') else: return [None, name] def check_order(): """ Checks that order.txt and ./svg dir has the same files """ fi...
#!/usr/bin/env python """ This submits a SLURM "srun" command to launch the 'step2_generatemodel' script, Note: If argument '--no_slurm' is passed, then it will try to run the optimization locally. Example usage command: >> ./bin/run_scripts/slurm_batch_subrunner1_study.py --dryrun -cf ~/bayota_ws_0.1a1.dev4/contro...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Compress DSF files into WavPack DSD format is preserved """ import argparse import sys import shlex from pathlib import Path from vsutillib import config from vsutillib.misc import staticVars from vsutillib.process import RunCommand from vsutillib.files import getFi...
import numpy as np import nibabel as nib from nilearn.image import resample_to_img from scipy.interpolate import Rbf from spimagine import volshow, volfig from spimagine.utils.quaternion import Quaternion # _t suffix in names means tuple # _l suffix in names means list def spimagine_show_volume_numpy(numpy_array, sta...
from JumpScale import j import inspect class CuisineBase: def __init__(self, executor, cuisine): self._p_cache = None self.__classname = None self._executor = executor self._cuisine = cuisine # maybe best to still show the cuisine, is easier self.cuisine = cuisine...
import math import numpy as np import shapely.geometry as geom from shapely import affinity import itertools from matplotlib import pyplot as plt from matplotlib import patches from descartes import PolygonPatch class Environment: def __init__(self, obstacles, start, goal_region, bounds=None): self.enviro...
# Copyright 2020 <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 or agreed to in writing, softw...
""" A set of large-scale tests which test code updates against previously-run "golden" results. The idea here is that any new updates (except for major versions) should be non-breaking; firstly, they should not break the API, so that the tests should run without crashing without being changed. Secondly, the actual res...
import os import logging import torch class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self, name, fmt=":f"): self.name = name self.fmt = fmt self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum =...
''' Created on Jan 5, 2011 Updated 29 April 2016 to deal with infernal 1.1.1 Updated 10 October 2016 to fix bug failing to identify abundant ncRNAs (>1000) @author: <NAME> Used to parse output from cmsearch to give output identifiers with each Model If a read looks like more than one Model - the lowest bitscore wins ...
import requests import yaml import json import os import amplitude import utils import datetime from ua_parser import user_agent_parser headers = {"Content-Type": "application/json", "Accept": "*/*"} r = requests.post("https://api.amplitude.com/2/httpapi", params={}, headers=headers) def gen_user(current_server_ses...
from random import gauss from utilities.degree_math import sin, cos, tan, sqrt, atan from utilities.geometry_utils import generate_lines class Hardware: def __init__(self, initial_position, initial_angle, map_size, rects, config_values, position_changed_signal, rotation_changed_signal): self.pos = initia...
#!/usr/bin/env python3 from pathlib import Path from typing import List, Set, Tuple import subprocess import sys from shutil import get_terminal_size from dependency import DependencyTree settings = { 'compilers': { '.cpp': 'g++', '.c++': 'g++', '.c': 'gcc' }, 'compiler_args': { ...
# ====================================================================================== # Copyright and other protections apply. Please see the accompanying LICENSE file for # rights and restrictions governing use of this software. All rights not expressly # waived or licensed are reserved. If that file is missing or ...
# Based on code taken from https://github.com/weiaicunzai/pytorch-cifar100 """vgg in pytorch [1] <NAME>, <NAME> Very Deep Convolutional Networks for Large-Scale Image Recognition. https://arxiv.org/abs/1409.1556v6 """ '''VGG11/13/16/19 in Pytorch.''' import torch import torch.nn as nn from Layers import la...
''' Created on Jan 21, 2016 @author: jim ''' import subprocess """ 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...
import logging import matplotlib.pyplot as plt from matplotlib.lines import Line2D import numpy as np import os import seaborn as sns import yaml import torch from model.training import build_lr_scheduler sns.set_style('whitegrid', {'axes.edgecolor': '.2'}) sns.set('poster', rc={"xtick.bottom": True, "ytick.left": T...
#!/usr/bin/env python3 # Copyright 2019 The Fuchsia Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ A script used to populate a sysroot include directory exactly as specified by an input .json file. Note that the script will ensure ...
import argparse import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn from models import modules, net, resnet, densenet, senet import net_mask import loaddata import util import numpy as np import os import matplotlib import matplotlib.image matplotlib.rcParams['image.cmap...
import typing import urllib3 import base64 import struct import anonlink from flask import Response from structlog import get_logger from entityservice.object_store import connect_to_object_store from entityservice.settings import Config as config from entityservice.utils import chunks, safe_fail_request import con...
#!/usr/bin/env python3 import os import logging import time import connexion # from connexion.resolver import RestyResolver from typing import List, Optional, Dict # noqa # pylint: disable=unused-import from flask_sqlalchemy import SQLAlchemy from flask_sqlalchemy import __version__ as __sqlalchemy_version__ from f...
""" HappyBase utility module. These functions are not part of the public API. """ import re import asyncio from functools import lru_cache from typing import ( Dict, List, Tuple, Any, AnyStr, Optional, TypeVar, Callable, Iterable, Iterator, Union, Coroutine, ) from Hbas...
from IMLearn.utils import split_train_test from IMLearn.learners.regressors import LinearRegression from typing import NoReturn import numpy as np import pandas as pd import plotly.graph_objects as go import plotly.express as px import plotly.io as pio pio.templates.default = "simple_white" def load_data(filename: ...
"""losses # losses for heatmap residule # use it if you're computing residual loss. # current disable residual loss """ # losse import torch def print_var(points): print("points: ", points.shape) print("points: ", points) pass # from utils.losses import pts_to_bbox def pts_to_bbox(points, patch_size): ...
from tqdm import tqdm from multiwoz_utils import * import json import copy def parse_data(args, from_dir, to_dir): with open(f"{from_dir}/valListFile.txt", 'r') as f: valid_list = f.readlines() with open(f"{from_dir}/testListFile.txt", 'r') as f: test_list = f.readlines() valid_list = [va...
# -*- coding: utf-8 -*- import sys import time import configparser from selenium import webdriver from selenium.webdriver.chrome.options import Options from colorama import init, Fore, Style # import getpass init(autoreset=True) opts = Options() # options for chromedriver opts.add_argument("--window-size=1000,1000"...
from aparse import click, ConditionalType import os import tqdm import json from typing import Optional from collections import OrderedDict from itertools import chain import tensorflow as tf from viewformer.utils.tensorflow import load_model from viewformer.data.loaders import get_loaders from viewformer.data._common ...
#all the imports needed #python import re #expressions régulières #django from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth import authenticate, login, logout from django.http import HttpResponse, Http404, HttpResponseRedirect from django.contrib.auth.decorators import login_re...
## # @file parallel_planes.py # \brief 1-D radiative solver, ray tracing, python (slow) # ################################################################################ import numpy as np from typing import Tuple, Any from nptyping import NDArray sigma = 5.670367E-8 # Stephan-Boltzmann constant def I_IT(x: ...
import uuid from datetime import date from django.db import models from django.urls import reverse from django.contrib.auth.models import User from django.utils import timezone from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth import get_user_model from user...
#!/usr/bin/env python # coding: utf-8 # Author: <NAME> & <NAME> import torch import os import json import torch.nn.functional as F def torch_load_cpu(load_path): return torch.load(load_path, map_location=lambda storage, loc: storage) # Load on CPU def move_to(var, device): if isinstance(var, dict): ...
import arabic_reshaper import math import matplotlib.pyplot as plt import numpy as np import os import pandas as pd import pickle import seaborn as sns import sys import warnings from bidi.algorithm import get_display from matplotlib.backends import backend_gtk3 from matplotlib.patches import Rectangle from iran_stoc...
from __future__ import division import json import os import subprocess from pbase.ptext.field import Field, NestedField from pbase.ptext.attribute import Attribute from pbase.papp.argument import Argument from pbase.papp.trainer import Trainer from zoo.ner.model.ner_tensorflow import NERModel pid = os.getpid() cl...
#!/usr/bin/env python """ Polarization integrals are computed on the CPU (with double precision) and GPU (with single precision) and are compared. To profile the GPU kernel use $ nvprof --metrics achieved_occupancy,branch_efficiency,flop_count_sp,flop_count_dp,flop_sp_efficiency,flop_dp_efficiency -fo log_sp.nvprof p...
import datetime from django.shortcuts import render, get_object_or_404, HttpResponseRedirect from django.views import generic from django.utils import timezone from django.urls import reverse from django.core.paginator import Paginator from .models_questions import Question, QuestionComment, Answer from .forms import...
import argparse import time import boto3 import botocore.config import os, shutil import json # Get script configuration parameters from lambda environment variables. # TODO If SSM is used, replace env vars for SSM parameters. S3_bucket = os.environ['FORENSICS_BUCKET'] S3_evidence_path = os.environ['FORENSICS_EVIDENC...
import numpy as np import pytest from stardist import star_dist3D, Rays_GoldenSpiral, relabel_image_stardist3D from utils import random_image, real_image3d, check_similar, circle_image, Timer from time import time @pytest.mark.parametrize('img', (real_image3d()[1], random_image((33, 44, 55)))) @pytest.mark.parametrize...
#!/usr/bin/env python3.9 """ This program gets the number of runs verified and rejected by a given user (argv[1]) and optionally limits the count to runs from 1 or 2 given games (argv[2] and argv[3]). """ import json from collections import defaultdict from datetime import datetime from fcntl import LOCK_EX, LOCK_NB,...
from __future__ import unicode_literals # Django from django.conf import settings from django.contrib import admin from django.core.urlresolvers import reverse from django.utils.safestring import mark_safe # Local Apps from grapevine.admin.base import BaseModelAdmin, SendableAdminMixin from .models import Email, Emai...
import cv2 import numpy as np import statistics as stat def adjust_gamma(image): # Load in the image using the typical imread function using our watch_folder path, and the fileName passed in, then set the final output image to our current image for now # Set thresholds. Here, we are using the Hue, Saturation, ...
# -*- coding: utf-8 -*- import os import sys from pyhdf.SD import SD import yaml import numpy as np from PIL import Image import warnings # !!!! VALUE = 255 : Fill Data--no Data expected For pixel # !!!! VALUE = 254 : Saturated MODIS sensor detector # !!!! VALUE = 240 : NATIONAL OR PROVINCIAL BOUNDARIES # !!!! ...
import sys import unittest from unittest.case import TestCase import pytest sys.path.append("../../../") from datetime import date, datetime, timedelta from plugins.TodayAtMun.DiaryUtil import DiaryUtil from plugins.TodayAtMun.__init__ import TodayAtMun class TestDateMethods(unittest.TestCase): """Testing TodayA...
# Copyright 2014 Open Source Robotics Foundation, 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...
from __future__ import print_function import logging logger = logging.getLogger(__file__) logging.basicConfig( format="[%(asctime)s - %(filename)s:line %(lineno)s] %(message)s", datefmt='%d %b %H:%M:%S') logger.setLevel(logging.INFO) import os import sys import numpy as np from keras.utils import generic_util...
#!/usr/bin/env python3 """ @author: <NAME>, <NAME> """ import argparse import csv import os import shutil import subprocess import sys import signal import tempfile try: import ConfigParser except ImportError: import configparser as ConfigParser import json BASE_DIRECTORY = os.path.dirname(os.path.dirname(os....
import pickle import re from datetime import datetime from threading import Thread import nltk from bs4 import BeautifulSoup from nltk.tokenize import sent_tokenize from tika import parser def start_new_thread(function): def decorator(*args, **kwargs): t = Thread(target=function, args=args, kwargs=kwargs...
# take <sos> tag and give to the latent and just generate from their import random import argparse import time import math import os import torch import torch.nn as nn import torch.onnx from torch.autograd import Variable import data_loader as data import model_VAE as model parser = argparse.ArgumentParser(descript...
import tensorflow as tf slim = tf.contrib.slim import sys import os #import matplotlib.pyplot as plt import numpy as np import os from nets import inception from preprocessing import inception_preprocessing from os import listdir from os.path import isfile, join from os import walk import cv2 import cam_utils import Gu...
import requests import json import pprint import re INCLUDEPAPERP = re.compile(r"\\includepaper\{chapters/(.*?)\}") BOOKAUTHORP = re.compile(r"\\author{(.*?)}") LASTAND = re.compile(r"(\\lastand|\\and)") CHAPTERAUTHORP = re.compile(r"\\author{(.*?) *\\affiliation{(.*)}") TITLEP = re.compile(r"\\title{(.*?)}") ISBNP...
import torch import numpy as np from torch.utils.data import DataLoader from transformers import AutoTokenizer from transformers import AdamW, get_linear_schedule_with_warmup from sklearn.metrics import accuracy_score from tqdm import tqdm from loading import Loader, CustomerDataset, collate_fn from config import Param...
# Licensed under a 3-clause BSD style license - see LICENSE.rst import tables import numpy as np from astropy.table import Table from Chandra.Time import DateTime import pickle from ..paths import IDX_CMDS_PATH, PARS_DICT_PATH __all__ = ['filter'] class LazyVal(object): def __init__(self, load_func): ...
from optparse import OptionParser, OptionGroup, OptionValueError from . import helpers from .version import VERSION def _command_name_to_metavar(command_name): """Transforms a command name to a better metaname (used for -h).""" return command_name.replace("set_", "").upper() def _check_color(option, opt_st...
"""Util functions to cleanup disk space.""" import types from sbws.util.filelock import DirectoryLock from sbws.globals import fail_hard from sbws.util.timestamp import unixts_to_dt_obj from argparse import ArgumentDefaultsHelpFormatter from datetime import datetime from datetime import timedelta import os import gzip...
import discord import asyncio import csv import yokocalc as yoko import clothing import sys if len(sys.argv) < 2: print ("Please pass in the bot token as a command line argument.") sys.exit() hair = yoko.load_wardrobe('wardrobe/hair.csv') dresses = yoko.load_wardrobe('wardrobe/dresses.csv') coats = yoko.load_wardro...
#! /usr/bin/env python3 """ This is the "helios_common.py" module So far, it provides "UpdateMounted," "GetPasswd," "AptSourceReplace," "AptSourceRestore," "SendNotice," "SendError," "Warning," and "Die" """ from psutil import disk_partitions from yad import YAD from io import StringIO from time import...
import torch.nn as nn import torch import torch.nn.functional as F from torch.nn import init class Linear(nn.Module): """ Wrapper class of torch.nn.Linear Weight initialize by xavier initialization and bias initialize to zeros. """ def __init__(self, in_features, out_features, bias= True): ...
from pprint import pprint from multiprocessing import Lock import subprocess from time import sleep import random import os import threading import imagecache from traceback import print_exc from cdconfig import genconf,rmconf bakeconfsdir = '/tmp/bakeconfs' bakepoollock = Lock() bakepool = {} def squash...
"""Copyright 2018 <NAME> and <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 or agreed to in writing, software d...
#!/usr/bin/env python import rospy # OpenCV2 for saving an image from cv_bridge import CvBridge, CvBridgeError import cv2 from geometry_msgs.msg import Twist from sensor_msgs.msg import LaserScan from std_msgs.msg import Empty from nav_msgs.msg import Odometry import time import sys, select, tty, os, os.path import num...
from PySide6.QtCore import QLine, QPoint, Qt, QTimer, Slot, Signal from PySide6.QtWidgets import QApplication, QWidget, QFrame from PySide6.QtGui import QPainter from PySide6 import QtGui import math class Line(QLine): def length(self): return (self.dx()**2 + self.dy()**2)**.5 class ImageW(QWidget): ...
import os import time import json import signal import logging import multiprocessing from uuid import uuid4 from contextlib import AbstractContextManager from concurrent.futures import ThreadPoolExecutor from concurrent.futures import ProcessPoolExecutor, Future, as_completed from typing import Any, Tuple, Dict, IO, B...
import os import tensorflow as tf import json from lxml import etree from absl import app from absl import flags import logging FLAGS = flags.FLAGS flags.DEFINE_string('input_dir', 'data', 'Path to images') flags.DEFINE_string('output_dir', 'records', 'Path to save the tfrecords') flags.DEFINE_list('num_shards', [10, ...
import csv import os import glob import datasets import pandas as pd import numpy as np from typing import Dict from datasets.tasks import TextClassification from sklearn.model_selection import train_test_split _CITATION = """\ """ _DESCRIPTION = """\ TREC Incident Stream Dataset: REC-IS provides multiple Twitter...
#!/usr/bin/env python from __future__ import print_function from getopt import gnu_getopt as get_args from json import load as load_json from json.decoder import JSONDecodeError import logging, os, sys, re def _build_logger(label, err = None, out = None): obj = logging.getLogger(label) obj.setLevel(logging.DE...
import os import re import sys import librosa import librosa.display from random import shuffle import numpy as np from typing import Tuple import pickle import pandas as pd from sklearn.externals import joblib from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler def f...
import os import sys import random import string import subprocess import re import math from time import sleep # # Tester for procprog # Example: make debug && ./procprog python3 self-test.py $(tput cols) # print("hello") def cursorPos(): _ = "" sys.stdout.write("\x1b[6n") sys.stdout.flush() while n...
# -*- coding: UTF-8 -*- """ 此脚本用于展示使用sklearn搭建线性回归模型 """ import os import sys import numpy as np import matplotlib.pyplot as plt import pandas as pd from sklearn import linear_model def evaluate_model(model, test_data, features, labels): """ 计算线性模型的均方差和决定系数 参数 ---- model : LinearRegression, 训练...
from typing import Callable, Tuple, TypeVar import jax.numpy as jnp from jax import jit, lax, random from jax_md import dataclasses, quantity, util, space Array = util.Array f32 = util.f32 T = TypeVar('T') ShiftFn = space.ShiftFn InitFn = Callable[..., T] ApplyFn = Callable[[T], T] Simulator = Tuple[InitFn, ApplyFn] ...
""" :Authors: <NAME> :Date: 10/14/2016 :TL;DR: this module converts relational data of several forms to a pandas DataFrame, infer and adjust columns types and splits the data for train and test """ import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from pyds import consta...
"""Routes for logged-in application.""" from flask import Blueprint, render_template, redirect, jsonify, request from appdb import db from datetime import date, timedelta, datetime, timezone from databases.models import Sales, Funnels, Emails import requests from decimal import Decimal from collections import Counter ...
import logging import os from collections import defaultdict, namedtuple from datetime import datetime import yaml from dbnd._core.configuration.dbnd_config import config from dbnd._core.utils.string_utils import pluralize from dbnd._core.utils.timezone import make_aware from dbnd.api import scheduler_api_client fro...
import json from uuid import uuid4 as gen_uuid from collections import defaultdict import numpy as np import rdflib import rdflib import pdb import pandas as pd from urllib.parse import quote_plus from functools import reduce from operator import itemgetter import rdflib from rdflib import Namespace, Graph from jason...
"""Forward-backward algorithm loss inference, and Viterbi Decoding for linear- chain CRF models. The main implementation comes from Flair. """ import numpy as np import torch from torch import Tensor import torch.nn as nn def log_sum_exp_batch(vecs): maxi = torch.max(vecs, 1)[0] maxi_bc = maxi[:, None].repeat...
import os import numpy as np def load_tub_npz( dirs, base_dir="", max_images=None, verbose=False, aux_name=None, pilot=False, cte=False ): """ Load images from pre-processed tub.npz files. dirs should be a list of tub names load each: base_dir + tub_name + '.npz' (extension is added if needed) ...
''' Initial conditions for the sctipt "int_sis_1.py" ''' import sympy as sym from sympy.utilities.lambdify import lambdify import numpy as np import math from scipy.constants import c as c_luz #metros/segundos c_luz_km = c_luz/1000; import os import git path_git = git.Repo('.', search_parent_directories=True).working...
from co2_diag.operations.time import ensure_datetime64_array, ensure_cftime_array, monthlist, dt2t from co2_diag.operations.convert import co2_kgfrac_to_ppm from co2_diag.operations.utils import print_var_summary, assert_expected_dimensions from co2_diag.operations.Confrontation import extract_site_data_from_dataset im...
#!/usr/bin/env python #coding: utf-8 import sys, os, re from pprint import pprint from collections import defaultdict, namedtuple import matplotlib from functools import reduce matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.colors as colors import matplotlib.cm as cmx import numpy as np Recor...
import os import pprint import shutil import pandas as pd from tqdm import tqdm, trange import numpy as np import torch import torch.nn.functional as F from common.utils.load import smart_load_model_state_dict from common.trainer import to_cuda from common.utils.create_logger import create_logger from vcr.data.build ...
from decimal import Decimal from django.contrib import messages from django.urls import reverse_lazy, reverse from django.http import HttpResponseRedirect from django.views.generic import FormView from wtforms import SelectField, BooleanField, validators, StringField, DecimalField, widgets from web_payments.forms impo...