text stringlengths 3.07k 12.6k |
|---|
# coding: utf8
import torch.utils.model_zoo as model_zoo
from torchvision.models.resnet import BasicBlock
from torch import nn
import math
import timm
import urllib
from PIL import Image
from timm.data import resolve_data_config
from timm.data.transforms_factory import create_transform
import torch.nn.functional as F
... |
'''Integration test of finite simulation of a system
'''
import pytest
import os
from fjarrsyn.simulation.simulator import FiniteSystemRunner
from fjarrsyn.simulation.sampler import AgentSampler, SystemIO
from fjarrsyn.core.agent import Agent
from fjarrsyn.core.agent_ms import AgentManagementSystem
from fjarrsyn.co... |
from pprint import pformat
import re
import time
from collections import OrderedDict
import requests
from elifetools import utils as etoolsutils
REMOVE_TITLE_TAGS = ["b", "i", "sub", "sup"]
REMOVE_ABSTRACT_TAGS = ["a", "b", "i", "span", "sub", "sup"]
def substitute_math_tags(string, replacement="[Formula: see text]... |
#!/usr/bin/pypy3
#!/usr/bin/python3
import json
import selenium
import socket
import os
import threading
from random import randint
from time import sleep
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from datetime import datetime
queue = []
def website():
global queue
... |
from tensorflow.python.util import compat
from . import _layers
from . import _layers_common
_CORE_OPS = {
# core
'Abs': _layers.abs,
'Add': _layers.add,
'AddV2': _layers.add,
'ArgMax': _layers.argmax,
'AvgPool': _layers.avgpool,
'BatchNormWithGlobalNormalization': _layers.batchnorm,
'BatchToSpaceND': ... |
import os
import torch
import pickle
import numpy as np
import pandas as pd
import sklearn.metrics
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
import matplotlib
import mlflow
from datetime import timedelta
from airflow import DAG
from airflow.operators.p... |
import tensorflow as tf
import numpy as np
from src.model import model
from src.utl.load_param import *
from src.utl.utl import *
import math
import time
from src.create_dataset_csv import create_dataset_csv
from src.eval_viseme import eval_viseme
def load_graph(frozen_graph_filename):
# Load the protobuf file t... |
import functools
import torch.nn as nn
class ResnetGenerator(nn.Module):
"""Resnet-based generator that consists of Resnet blocks between a few downsampling/upsampling operations.
We adapt Torch code and idea from <NAME>'s neural style transfer project(https://github.com/jcjohnson/fast-neural-style)
"""... |
from jet20.frontend.expression import Expression, Constraint
from jet20.frontend.variable import Variable, Array
from jet20.frontend.const import *
from jet20.frontend.backends import jet20_default_backend_func
from typing import List, Union, Callable
from functools import wraps
import numpy as np
import re
def asser... |
# Original work Copyright 2012-2018 <NAME> (MIT)
# See ThirdPartyNotices.txt in the project root for license information.
# All modifications Copyright (c) Robocorp Technologies Inc.
# All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in complianc... |
import discord, time, asyncio, os, random, json, unidecode
from discord.ext import commands, tasks
from discord.ext.commands import has_permissions, cooldown, MissingPermissions, check
from discord.utils import get
from termcolor import colored
class App(commands.Cog):
def __init__(self, client):
self.clie... |
#!/usr/bin/python
"""
Runs coffea processors on the LPC via either condor or dask.
Author(s): <NAME>, <NAME>
"""
import uproot
from coffea.nanoevents import BaseSchema
from coffea import nanoevents
from coffea import processor
import pickle
import argparse
nanoevents.NanoAODSchema.nested_index_items["FatJetAK15_p... |
#!/usr/bin/env python3
# ====================================
# Copyright (c) Microsoft Corporation. All rights reserved.
# ====================================
"""Sandbox module."""
import os
import sys
import time
import traceback
from queue import Queue, Empty
import util
# append worker binary source path
sys.p... |
import os
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Optional
from yarl import URL
@dataclass(frozen=True)
class ServerConfig:
host: str = "0.0.0.0"
port: int = 8080
name: str = "Docker Registry"
@dataclass(frozen=True)
class AuthConfig:
server_endpoint_u... |
import torch
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
LAMBDA_COORD = 5
LAMBDA_NOOBJ = 0.5
def calc_loss(inp , target, opt):
if inp.size(0) != target.size(0):
raise Exception("Batch size does not match")
total_loss = torch.tensor(0.0)
#total_loss = total_loss.dtype(te... |
import torch
from tqdm import tqdm
from transformers import AutoTokenizer, AutoModel
import logging
from torch.nn import ConstantPad3d, ConstantPad2d
from layers.utils import set_model_device, set_tensor_device
'''
tutorial4 tokenization
https://mccormickml.com/2019/07/22/BERT-fine-tuning/
how to use clinical ... |
from . import types
import ctypes
from ctypes import wintypes
class TypeWrap:
@staticmethod
def _common_name(name: str):
key = getattr(wintypes, name)
value = getattr(types.win32, name)
return {key: value}
@staticmethod
def _reversed_common_name(name: str):
key = geta... |
# -*- coding: utf-8 -*-
import click
import logging
from pathlib import Path
from dotenv import find_dotenv, load_dotenv
import pandas as pd
@click.command()
@click.argument('input_filepath', type=click.Path(exists=True))
@click.argument('output_filepath', type=click.Path())
def main(input_filepath, output_filepath... |
# -*- coding: utf-8 -*-
import numpy as np
import scipy.ndimage
import scipy.special
import sklearn.neighbors
def mutual_information(x, y, method="varoquaux", bins=256, sigma=1, normalized=True):
"""Mutual Information (MI)
Computes the (normalized) mutual information (MI) between two vectors from a joint his... |
import numpy as np
import scipy.stats as stats
import librosa
from alcokit.util import normalize
from alcokit.transform.spectrum import frame, running_agg
from librosa.segment import recurrence_matrix
from librosa.util import localmax
from scipy.ndimage import convolve
def from_recurrence_matrix(X,
... |
import json
import urlparse
import urllib
from protocol.encoder import WriteEncoder, CreateEncoder, ReadEncoder
from protocol.query.builder import QueryBuilder
from response import Response, SensorPointsResponse, DeleteDatapointsResponse
from response import RuleResponse, DeviceResponse, ResponseException
from endpoint... |
"""Common methods for input / output file and data processing."""
import configparser
import os
import tarfile
from pathlib import Path
import requests
from cmatools.definitions import CONFIGFILE, CONFIGLOGS, ROOT_DIR
# Read from user-editable config file
config = configparser.ConfigParser()
config.read(CONFIGFILE)... |
import random
from src.tipboard.app.properties import COLOR_TAB
# Datasets is always an arrays with the always the same possible value for different chart
# Every dataset is a dict, go to chartJS documentation to see the possibility
# "datasets": [
# {
# "label": "Series 1",
# "fill": true,
# ... |
import numpy as np
import h5py
import os
#最远点采样
def farthest_point_sample(xyz, npoint):
N, C = xyz.shape
centroids = np.zeros(npoint)
distance = np.ones(N) * 1e10
farthest = np.random.randint(0, N)# random select one as centroid
for i in range(npoint):
centroids[i] = farthest
... |
# MCTSDetermizer: Handles determinising and redeterminising player hands
from pyhanabi import HanabiCard
import random
class MCTSDeterminizer(object):
def __init__(self):
self.deck = HanabiDeck()
def valid_card(self, player, card_index, player_hands, discard_pile, fireworks
, card_knowledge=N... |
from pathlib import Path
import pandas
import numpy
def _febrl_load_data(filename):
# Internal function for loading febrl data
filepath = Path(
Path(__file__).parent,
'febrl',
filename
)
febrl_data = pandas.read_csv(filepath,
index_col="rec_... |
# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
# -*- coding: utf-8 -*-
import tensorflow as tf
# modification of aligned crop and resize from tensorpack
@tf.function(experimental_relax_shapes=True)
def transform_fpcoor_for_tf(boxes, image_shape, crop_sha... |
# represent html as using a PDA
# nested query calls is the and stack
# for loops are the or-stack
# the output should be stored globally, but how to store the sources of output?
import re
from proof_constructor.graph import Graph
class HtmlParser(object):
def __init__(self, src_filename):
self.graph = Gr... |
#NAME: guilineFollowOperationalTest.py
#DATE: 08/02/2019
#AUTH: <NAME>, EEE Undergraduate, Queen's University Belfast
#DESC: A python function for navigating the wheelchair with an XBOX 360 game controller avoiding obstacles
#COPY: Copyright 2019, All Rights Reserved, <NAME>
from control import Control
from urllib.req... |
from __future__ import annotations
import sys
from pylox.errors import LoxError
from pylox.lox_types import LoxType, Number
from pylox.tokens import EOF, KEYWORD_TOKENS, Token, TokenType
class LexError(LoxError):
...
class LexIncompleteError(LexError):
...
class Lexer:
def __init__(self, source: str... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
"""
Module is containing all necessary global variables for the package.
Module also has the ability to read user-defined data from following paths:
- ``SETTINGS_PATH`` env variable file pointer to .json file.
- ``$HOME/_SETTINGS_PATH``
- ``/etc/_SETTINGS_PATH``
See :... |
"""
Need something to make sense of a bunch of downloaded images....
Vid-000512014-00-03-2009-12-17-17-42.jpg
Site Identifier
CameraID (may have more than one camera in the future)
ViewID
GMT Timestamp....
"""
from __future__ import print_function
# std... |
# Software License Agreement (BSD License)
#
# copyright (c) 2014-2015 roslint contributors
# all rights reserved
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the a... |
# import the necessary packages
from sklearn.model_selection import ParameterGrid
from imutils import face_utils
from utils import config
from imutils import paths
import multiprocessing
import numpy as np
import random
import time
import dlib
import json
import cv2
import os
def evaluate_model_acc(xmlPath, predPath):... |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 5 23:14:16 2021
@author: kkrao
"""
import os
import itertools
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import sklearn.ensemble
import sklearn.metrics
import sklearn.model_selection
import statsmodels.api as sm
imp... |
# -*- coding: utf-8 -*-
"""
@author: fornax
"""
import os
import pandas as pd
import json
import prepare_data1 as prep
DATA_PATH = prep.DATA_PATH
INTERVALS = ['2H', '6H', '12H', '1D']
FUNCTIONS = ['mean', 'std', 'count']
def resample(df, df_name='generic', intervals=INTERVALS, functions=FUNCTIONS, cols=None):
"... |
# Copyright 2020 The TensorFlow Probability Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
import numpy as np
#简单数据集上应用adaBoosting
def loadSimpData():
'''
创建简单数据集
'''
dataMat = np.matrix([[1., 2.1],
[2., 1.1],
[1.3, 1 ],
[1. , 1.],
[2. , 1.]])
classLabels = [1.0, 1.0, -1.0, -1.0, 1.0]
return dataMat, classLabels
def stumpClassify(dataMatrix, dimen, threshVal... |
# -*- coding: utf-8 -*-
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
##########################################################################
# MediPy - Copyright (C) Universite de Strasbourg
# Distributed under the terms of the CeCILL-B license, as published by
# the CEA-CNRS-INRIA. Refer to the LICENSE file or to
# http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
# for de... |
'''
Creates the Automl classification model using dataset on bucket
'''
import argparse
import os
import shutil
import time
from google.cloud import automl_v1beta1 as automl
from google.cloud import storage
DATE_STR = time.strftime("%Y%m%d%H%M%S")
AUTOML_CLIENT = automl.AutoMlClient()
STORAGE_CLIENT = storage.Client... |
import nni
import torch
import argparse
import pretty_errors
from tqdm import tqdm
from time import time_ns
import GCL.utils.simple_param as SP
from torch.optim import Adam
from torch.utils.tensorboard import SummaryWriter
from GCL.eval import LR_classification
from GCL.utils import seed_everything
from utils import... |
from collections import OrderedDict
from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
from io import BytesIO
from logging import getLogger as get_logger
from threading import Lock
from typing import NamedTuple, Optional
from megfile.errors import raise_s3_error
from megfile.interfaces import Wri... |
import os
import csv
import datetime
import numpy as np
import sounddevice as sd
import soundfile as sf
import librosa
from keras.models import load_model
import feature_extraction_scripts.feature_extraction_functions as featfun
import feature_extraction_scripts.prep_noise as pn
def get_date():
time = datetime.da... |
#!/usr/bin/env python3
# coding=utf-8
from bs4 import BeautifulSoup
from bs4.element import Tag
from requests_filecache import get
import argparse
ENDPOINT = 'https://unchartedwaters.fandom.com'
def parse_args():
""" Разбор аргументов """
parser = argparse.ArgumentParser()
parser.add_argument('--region'... |
# coding=utf-8
from __future__ import unicode_literals
import os
import glob
import json
import pinyin
from collections import defaultdict
from jinja2 import Environment, FileSystemLoader
import codecs
from collections import OrderedDict
DEST_FOLDER = os.path.join('js', 'shape-with-internal-borders')
DEST_GEOJSON_FOL... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Script to extract an ESE database catalog."""
import argparse
import logging
import os
import sys
from esedbrc import catalog_extractor
from esedbrc import definitions
from esedbrc import database
class Sqlite3OutputWriter(object):
"""SQLite3 output writer."""
def _... |
from rest_framework import viewsets, generics
from rest_framework.permissions import IsAuthenticated
from cinema_notification.models import Notification
from managecinema.models import CinemaArrangeSlot, CinemaDeck, Cinema
from .models import *
from .serializers import *
from rest_framework.response import Response
fro... |
# coding: utf-8
"""
Provides test-related code that can be used by all tests.
"""
import os
import pystache
from pystache import defaults
from pystache.tests import examples
# Save a reference to the original function to avoid recursion.
_DEFAULT_TAG_ESCAPE = defaults.TAG_ESCAPE
_TESTS_DIR = os.path.dirname(pystac... |
from argparse import ArgumentParser, Namespace
from operator import itemgetter
from os import path
import matplotlib.pyplot as plt
import numpy as np
import pandas
from matplotlib.figure import Figure
from pandas import DataFrame
from sklearn.metrics import r2_score
def getArgparse() -> Namespace:
parser: Argume... |
import numpy as np
import pandas as pd
from pandas.api.types import is_numeric_dtype
import matplotlib.pyplot as plt
from matplotlib import rcParams
import seaborn as sns
from .utils import *
from .utils import _make_iterable, _is_iter
def _plot_grid(plot_func, data, x, y, color=None, **kwargs):
MSG_ONLY_2D = "... |
# coding=utf-8
# Copyright 2019 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... |
import gensim.models as models
import pickle
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from gensim.models import CoherenceModel
from data_preparation import remove_low_high_frequent_words, get_tfidf, extract_important_words_tfidf
import pyLDAvis.gensim
def train_lda_model(data, num_top... |
import cv2
from sklearn import svm
import os
import numpy as np
from sklearn.externals import joblib
from skimage.feature import hog
from sklearn.utils import shuffle
import sys
import argparse
import random
MAX_HARD_NEGATIVES = 20000
parser = argparse.ArgumentParser(description='Parse Training Directory')
parser.add... |
# Copyright 2020 The TensorFlow Authors. 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 applica... |
import regex
import argparse
import requests
import os
import threading
currentPath = os.path.dirname(__file__)
CANARY_TEXT = 'CANARY049'
CANARY_DOMAIN = 'canaryredirect.fr'
FUZZ_PLACE_HOLDER = '??????'
TIMEOUT_DELAY = 1.75
LOCK = threading.Lock()
parser = argparse.ArgumentParser()
parser.add_argument("--file", "-f... |
import numpy as np
from functools import reduce
from metagraph import concrete_algorithm, NodeID
from .types import NumpyVector, NumpyNodeMap, NumpyNodeSet
from typing import Any, Callable, Optional
from .. import has_numba
if has_numba:
import numba
@concrete_algorithm("util.nodeset.choose_random")
def np_nodes... |
#! /usr/bin/env python3
import pysam
import pandas as pd
from collections import defaultdict
import re
from pathlib import Path
from scipy import stats
import sys
def binomial_ci(x, n, alpha=0.05):
#Clopper-Pearson interval for binomial distribution
#x is number of successes, n is number of trials, alpha the... |
import numpy as np
import sys
import logging
import os
import time
import json
import base64
def softmax(y, axis=-1):
"""Calculates the softmax distribution.
Parameters
----------
y : ndarray
Log-probabilities.
"""
yp = y - y.max(axis=axis, keepdims=True)
epy = np.exp(yp)
ret... |
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in the "license... |
#!/usr/local/bin/python
import time, sys, os
import numpy as np
np.errstate(invalid='ignore')
from prospect.models import model_setup
from prospect.io import write_results
from prospect.io import read_results as pr
from prospect import fitting
from prospect.likelihood import lnlike_spec, lnlike_phot, write_log, chi_s... |
class HyperBand:
"""Abstract Class Encapsulation of HyperBand algorithm for hyperparameter optimization
Directly implemented from the HyperBand paper (Li et. al 2017)
Mainly for reference and not for use
"""
def __init__(self):
if type(self) == HyperBand:
raise Exception("Can't ... |
from collections import OrderedDict
from math import pi
from .. import cq
from .geom import Vector
from .shapes import Shape, Edge, Face, sortWiresByBuildOrder, DEG2RAD
import ezdxf
from OCP.STEPControl import STEPControl_Reader
from OCP.ShapeAnalysis import ShapeAnalysis_FreeBounds
from OCP.TopTools import TopTools... |
""" Built-in utilities to process inputs.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from numpy import pi
import tensorflow as tf
import tensorflow.python.keras as k
import tensorflow.python.keras.backend as K
# interface for s... |
from torch import nn
import torch
from torchvision.models import vgg
import numpy as np
from torch.nn import init
import functools
from torch.optim import lr_scheduler
##########################################################
#Fonctions used for networks initialisation
################################################... |
# Python3 module
"""
module comprenant diverses fonctions pour générer des éléments SVG
sous forme de chaînes.
Ces chaînes doivent être écrites dans un fichier en respectant la
structure SVG pour obtenir une image.
"""
def ouverture_image(largeur, hauteur):
"""
génère la balise ouvrante pour décrire une ima... |
"""
Plots the velocities along the centerlines of the 2D cavity at Reynolds number
3200 and compares with the numerical data reported in Ghia et al. (1982).
_References:_
* <NAME>., <NAME>., & <NAME>. (1982).
High-Re solutions for incompressible flow using the Navier-Stokes equations
and a multigrid method.
Jour... |
# Copyright (C) 2019 Cancer Care Associates 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... |
#!/usr/bin/env python
# coding:utf8
"""
@Time : 2020/2/16
@Author : fls
@Contact : <EMAIL>
@Desc : ez工具类-faker数据
@Modify Time @Author @Version @Desciption
------------ ------- -------- -----------
2020/2/16 8:16 fls 1.0 create
"""
from faker import... |
"""Unit tests for the tasks/dep module."""
import pathlib
import tempfile
from ldp.parse import ptb, representations
from ldp.tasks import dep
import h5py
import pytest
import torch
WORDS = (
'word-a',
'word-b',
'word-c',
'word-d',
'word-e',
)
SAMPLES = (
ptb.Sample(
(WORDS[0], WORDS... |
#!/usr/bin/env python
"""
log_parser
tools to parse log_train and log_err
"""
from __future__ import absolute_import
from __future__ import print_function
import numpy as np
import os
import re
import sys
__author__ = "<NAME>"
__email__ = "<EMAIL>"
__copyright__ = "Copyright 2020, Xin Wang"
def f_read_log_err(fil... |
import json
import keyword
import textwrap
import operator
import re
prologue_template = """
# XXX This code file has been automatically generated. Do not edit it.
import requests as _requests_
from .base import EndPoint, register_endpoint
from .. import resources as _resources_
"""
def generate_prologue():
pri... |
import argparse
import logging
from typing import Any, Dict, List, Optional
import requests
from annofabapi.dataclass.task import Task
from annofabapi.models import ProjectMemberRole, TaskStatus
import annofabcli
from annofabcli import AnnofabApiFacade
from annofabcli.common.cli import AbstractCommandLineInterface, A... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
# -*- coding: utf-8 -*-
# @Author : BoPo
# @Time : 2021/10/11 17:28
# @Function:
import json
import httpx
import pandas as pd
from tenacity import stop_after_attempt, wait_fixed, retry
from mootdx.consts import return_last_value
@retry(wait=wait_fixed(2), retry_error_callback=return_last_value, stop=stop_after_... |
import torch
from adabelief_pytorch import AdaBelief
from TorchDiffEqPack import odesolve
import numpy as np
from matplotlib import pyplot as plt
from scipy.io import loadmat
import os
import torch.nn as nn
import numpy as np
import pandas as pd
import torch.nn.functional as F
from torch.optim import Adam
from scipy im... |
import mysql.connector as mariadb
def create_open_database(host,port,user,password,db_name = 'ksapriori'):
conn = None
try:
connection = mariadb.connect(host=host,port=port,user=user,password=password)
cursor = connection.cursor()
cursor.execute("select * from information_schema.... |
"""
Requirements:
如需运行本模块, 请先安装 Qt 5.0+ (推荐 5.15) 完整版.
本模块所用到的离线文件读取自:
"{YourQtProgram}/Docs/Qt-{version}/qtdoc/modules-qml.html".
"""
from bs4 import BeautifulSoup
from lk_utils import read_and_write
def main(file_i: str, file_o):
"""
Args:
file_i: "~/blueprint/resources/no1_all_qml_m... |
# -*- coding: utf-8 -*-
r"""
Created on Mon Jul 22 14:03:27 2019
@author: <NAME>, florian\obersteiner\\kit\edu
"""
import re
###############################################################################
class NumStr:
"""
class to hold methods for working with numbers in string format.
... |
#!/home/dlee/.virtualenvs/fh/bin/python
# -*- coding: utf-8 -*-
# Streamflow NETwoK (SNETK)
import numpy as np
import gdal
import osr
def adBoundary(fdir):
vempty = np.zeros([1, fdir.shape[1]])
hempty = np.zeros([fdir.shape[0]+2, 1])
fdir = np.vstack([vempty, fdir, vempty])
fdir = np.hstack([hempty,... |
"""
This module contains all the procedures necessary for
loading the data.
"""
import pickle as pkl
import numpy as np
import logging
import sklearn
from sklearn.model_selection import train_test_split
# DATA_FOLDER = "data/"
EXTENSION = ".pkl"
DATA_SETS = {
"fonollosa": {0: "B1-system",
... |
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions a... |
"""
@Author: <NAME>
@Since: 12/24/2021 3:12 PM
"""
import copy
import json
import streamlit as st
import pandas as pd
import base64
import numpy as np
import PIL.Image as Image
import requests
import io
from NCFModel import NCFModel
from imdb_request import get_film_info, get_title_id
model = NCFModel()
st.se... |
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 11 14:37:58 2016
@author: <NAME>
"""
import numpy as np
import struct
import os
from pyoti.data.datasource import DataSource
class CNLabViewBinData(DataSource):
def __init__(self, filename, directory=None, parafile=None, datext='.bin',
parext='_par... |
from pyspark import SparkContext, SparkConf
import pyspark
from pyspark.sql import SQLContext
from pyspark.sql.functions import max, col, avg, sum
from cassandra.cluster import Cluster
import os.path
import json
import numpy as np
from collections import defaultdict
import pandas as pd
def getStationsIds(stations)... |
from werkzeug.exceptions import abort, InternalServerError, HTTPException, default_exceptions
from werkzeug.wrappers import Request, Response
from werkzeug.routing import Map, Rule
from werkzeug.contrib.securecookie import SecureCookie
from werkzeug.local import LocalStack, LocalProxy
_request_ctx_stack = LocalStack()... |
from collections import OrderedDict as OrdD, defaultdict as dd
from dataclasses import dataclass
from math import ceil, floor, log
from typing import List, OrderedDict
import numpy as np
from .base import Strategy, StrategyConfig, _get_arm, _notify_initial_error
from .._logging import get_logger
from ..embedding impo... |
"""
API harvester for ClinicalTrials.gov for the SHARE Notification Service
http://clinicaltrials.gov/ct2/results?lup_s=04%2F26%2F2015%2F&lup_e=04%2F27%2F2015&displayxml=true
iindividual result: http://ClinicalTrials.gov/show/NCT02425332?displayxml=true
"""
from __future__ import unicode_literals
import time
import... |
"""Show augmented samples from training runs
by slicing the saved training samples.
"""
import os
from os.path import join
import yaml
from glob import glob
from pathlib import Path
import torch
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pylab as plt
from PIL import Image
mpl.rcPa... |
from typing import Any, Dict, Optional
import pytest
from aiohttp import ClientResponseError
from aries_cloudcontroller import AcaPyClient
from assertpy import assert_that
from httpx import AsyncClient
from app.admin.governance.multitenant_wallet.wallet_admin import (
UpdateWalletRequest,
get_subwallet,
g... |
"""A module to handle generic operations.
"""
import mimetypes
import os
import sys
import typing as ty
from functools import wraps
if ty.TYPE_CHECKING:
import typing_extensions as ty_ext
else:
ty_ext = ty
AnyStr = ty.TypeVar('AnyStr', bytes, str)
T = ty.TypeVar("T")
if sys.version_info >= (3, 8): #PY38+
Literal... |
import numpy as np
import random
from collections import namedtuple, deque
from model import QNetwork
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
STEPS = 4
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
def MSELoss(targets, predictions):
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 19 20:45:54 2019
@author: User
"""
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from qiskit.compiler import transpile
import numpy as np
import collections
import random
import matplotlib.pyplot as plt
import os
plt.ioff()
'''
... |
# coding: utf-8
#
# Copyright 2021 The Oppia Authors. 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 requi... |
import pytest
from icevision.all import *
@pytest.fixture
def coco_bbox_parser(coco_dir):
return parsers.COCOBBoxParser(coco_dir / "annotations.json", coco_dir / "images")
@pytest.fixture
def coco_mask_parser(coco_dir):
return parsers.COCOMaskParser(coco_dir / "annotations.json", coco_dir / "images")
def ... |
#! /usr/bin/env python
#
# Copyright (C) 2017 Apple Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this l... |
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
def plot_map(visited: list):
"""
Plots the map constructing a matrix.
Remember that x = row index, y = column index.
"""
# Colors mapping for matshow library me... |
"""Tests for a simple dense neural network search space.
Copyright 2018 The AdaNet Authors. 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
https://www.apache.org/licenses... |
'''
Author: <NAME>
Date: March 13, 2020
@: University of Tulsa
Description: see README.md
( the coronavirus hit so we were sent home from college ... I had the idea to finally code this last week and finished the
first working code @ DFW ... I have touched it up now and put it on github)
'''
# Import... |
import numpy as np
import math
import cv2
import os
import json
# from scipy.special import expit
# from utils.box import BoundBox, box_iou, prob_compare
# from utils.box import prob_compare2, box_intersection
from ...utils.box import BoundBox
from ...cython_utils.cy_yolo2_findboxes import box_constructor
# from .sort... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.