text
stringlengths
3.07k
22.1k
""" Taken from vithursant's repo: https://github.com/vithursant/MagnetLoss-PyTorch/blob/master/magnet_loss/magnet_loss.py """ import numpy as np import torch import torch.nn as nn from torch.autograd import Variable import torch.nn.functional as F class MagnetLoss(nn.Module): """ Magnet loss technique presen...
r"""Distributed TensorFlow with Monitored Training Session. This implements the 1a image recognition benchmark task, see https://mlbench.readthedocs.io/en/latest/benchmark-tasks.html#a-image-classification-resnet-cifar-10 for more details Adapted from official tutorial:: https://www.tensorflow.org/deploy/distrib...
# Copyright 2019 Google LLC. 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 applicable law or a...
from typing import Any, Dict, List import networkx as nx import numpy as np import partridge as ptg from .graph import (generate_empty_md_graph, generate_summary_graph_elements, make_synthetic_system_network, populate_graph) from .synthetic import SyntheticTransitNetwork from .toolkit import gener...
import random import time from collections import namedtuple import pytest import torch import numpy as np from easydict import EasyDict from functools import partial import gym from ding.envs.env.base_env import BaseEnvTimestep from ding.envs.env_manager.base_env_manager import EnvState from ding.envs.env_manager imp...
# coding=utf-8 # Copyright 2020 The TensorFlow Datasets Authors and the HuggingFace Datasets 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/LI...
import os import re import sys import json import time import math import errno import random import select import signal import socket import logging from six import reraise from six.moves import _thread as thread from six.moves.http_client import OK, TEMPORARY_REDIRECT, SERVICE_UNAVAILABLE from six.moves.urllib.parse...
import torch.nn as nn class StyleClassifier(nn.Module): # classifies NPI outputs def __init__(self, n=200, m=768, k=1): """ input_activs_shape: tuple of (b, n, m, 1) b is the number of batches n x m x 1 slices contain the elements of the original activations, flattened into...
import json import logging from abc import ABC from aiohttp import web from tellus.tell import Tell, InvalidAliasException from tellus.tells import Teller, TheresNoTellingException from tellus.tellus_utils import now_string, TellusException from hotsocket.timer import DurableTimer from tellus.configuration import TELL...
import topogenesis as tg import numpy as np import pandas as pd # Environment class class environment(): def __init__(self, avail_lattice : tg.lattice ,lattices : dict, agents_dict : dict, stencils: dict): self.lattices = lattices self.lattice_names = [lattices.keys()] self.avail_lattice = ...
""" Invoke tasks for imageio-ffmpeg """ import os import sys import shutil import importlib import subprocess from urllib.request import urlopen from invoke import task # ---------- Per project config ---------- NAME = "imageio-ffmpeg" LIBNAME = NAME.replace("-", "_") PY_PATHS = [LIBNAME, "tests", "tasks.py", "setu...
#!/usr/bin/env python3 from typing import TYPE_CHECKING from tensorflow import keras from tensorflow.keras import layers if TYPE_CHECKING: from typing import Any, Optional, Union from typing import Literal from typing import Sequence, List from typing import Mapping, Dict from ..functional import or...
from datetime import datetime import flask import re import time from distutils.util import strtobool from flask_restful import Resource from flask_sqlalchemy_session import current_session from cirrus import GoogleCloudManager from cirrus.config import config as cirrus_config from fence.config import config from fen...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/3/21 6:23 PM __author__ = '<NAME>' import sys import scipy.stats as sts import matplotlib.gridspec as gridspec import matplotlib.pyplot as plt import numpy as np import pylab from mpl_axes_aligner import align from .Constant import COLOR from .mRNA impo...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ annot_variants.py generates a dataframe that stores annotations for each variant in the specified locus and genome that tell us whether the variant generates allele-specific sgRNA sites for the Cas variety/varieties specified. Written in Python v 3.6.1. <NAME> et al. ...
import numpy as np import tensorflow as tf import gym from gym.spaces import Box, Discrete import time class Memory: """ Buffer to store visited transitions """ def __init__(self, size, obs_dim, act_dim): """ Class (replay) memory constructor - size is the maximum n...
# cython: auto_cpdef=True '''Python code for reading AVRO files''' # This code is a modified version of the code at # http://svn.apache.org/viewvc/avro/trunk/lang/py/src/avro/ which is under # Apache 2.0 license (http://www.apache.org/licenses/LICENSE-2.0) import json from os import SEEK_CUR from struct import pack,...
import numpy as np from skimage.filters import threshold_otsu from scipy import ndimage as ndi from skimage.measure import regionprops import skimage.color as color from skimage.exposure import rescale_intensity from skimage.morphology import binary_erosion, binary_dilation, selem from skimage.transform import rescale ...
# MUST SUDO FOR THIS TO WORK - ELSE PERMISSION DENIED import json import subprocess as s import os from pathlib import Path from time import sleep as zzz from colorama import Fore, Style def welcome(): print(f"{Fore.MAGENTA} ") print(r""" _____ _____ _____ _ _ | __ \_ _/ ____| | | ...
''' Item Recommender April 2021 <EMAIL> ''' import os import sys import math import datetime import numpy as np import tensorflow as tf from layer_util import * from data_reader import DataReader from hyper_param import param_dict as pd os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' tf.compat.v1.disable_eager_execution()...
''' Gui/Views/Crosslink_Discoverer/input_files __________________________________________ Input files widget for CrossLink Discoverer. :copyright: (c) 2015 The Regents of the University of California. :license: GNU GPL, see licenses/GNU GPLv3.txt for more details. ''' # load modules/submodules im...
import inspect from collections import Counter from re import compile as re_compile from re import sub as re_sub from re import UNICODE from re import match import sys import ctypes from os.path import dirname, realpath from os import getcwd def get_hash(arg): if isinstance(arg, list) or isinstance(arg, set) or i...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 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 Licens...
from flask import Flask, render_template, request, redirect, url_for, session from tinydb import TinyDB, Query from mastodon import Mastodon from wordcloud import WordCloud from datetime import datetime from numpy.random import * from xml.sax.saxutils import unescape import re import json import requests import MeCab ...
# -*- coding: utf-8 -*- # # Copyright (C) 2006 <NAME> <<EMAIL>> # Copyright (C) 2011 <NAME> <<EMAIL>> # Copyright (C) 2011-2014 <NAME> <<EMAIL>> # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. # import re from genshi.builder import tag as ...
# -*- coding: utf-8 -*- """Contains functions that help create tasks. All functions contained herein are intended for use with :meth:`anadama2.workflow.Workflow.add_task`. This means that the functions in here don't immediately do what they say; they return functions that, when called, do that they say (they're closure...
# Copyright 2014 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 writing, so...
"""Data loading utilities.""" import glob import os import numpy as np import portalocker import torch from utils.vocabulary import OpenAIVocab, Vocab class LMOrderedIterator: def __init__(self, data, bsz, bptt, device='cpu', ext_len=None): """ data -- LongTensor -- the LongTensor is strict...
from typing import List RANK_STR = ['2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A'] SUIT_STR = ['S', 'C', 'D', 'H'] def get_card(card_id : int): rank_id = card_id % 13 suit_id = int((card_id - rank_id) / 13) return (rank_id, suit_id) def get_cardid_from_card(card: tuple): (rank_id, s...
from codecs import getdecoder from email.headerregistry import Address import locale import os from pathlib import Path import sys import traceback from typing import Any, ContextManager, Optional, Tuple, Union import attr import click import daemon from daemon.daemon import DaemonError from mailbits import ContentType...
# -*- coding:utf-8 -*- # @Author : <EMAIL> # @Data: 2020/3/11 15:48 # @File : fortify_engine.py # @Software: PyCharm from xml.dom.minidom import parse from .config import report_path import xml.dom.minidom import os import subprocess import signal from .utils import md5, random_generator, clean_dir from .engine impor...
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2021, Shuup Commerce Inc. All rights reserved. # # This source code is licensed under the Shuup Commerce Inc - # SELF HOSTED SOFTWARE LICENSE AGREEMENT executed by Shuup Commerce Inc, DBA as SHUUP® # and the Licensee. from __future__ import un...
import logging from pathlib import Path from typing import Callable, Sequence, Union, Optional import numpy as np import tensorflow as tf from dataclasses import dataclass, field from tqdm.autonotebook import tqdm from .logger import Logger @dataclass class BaseBot: """Base Interface to Model Training and Infer...
import os import platform import subprocess import webbrowser from datetime import datetime from .input_validation import input_validation from .logger import * from .print_manager import * Log = LogManager(developer_mode=True) def exit_application(text=None, enter_quit=False): if text: mcprint(text=tex...
import torch from torch import nn import numpy as np torch.manual_seed(1) from logger import setup_logger import os import traceback from torch import optim as Optimzer import collections from torch.utils.data import DataLoader, dataset import hashlib import os import os.path as osp import logging import time import da...
import os import subprocess import discord from discord.ext import tasks from datetime import datetime import requests import random from dotenv import load_dotenv import markov load_dotenv() client = discord.Client() DISCORD_TOKEN = os.environ["DISCORD_TOKEN"] SERVICE_ACCOUNT_ID = os.environ["SERVICE_ACCOUNT_ID"] ...
import cv2 as cv import numpy as np import torch from skimage import io from torchvision.transforms import functional as F from ..utils import craft_utils, imgproc from ..utils import box_utils def load_image(path): img = io.imread(path) # RGB order if img.shape[0] == 2: img = img[0] if len(img.shape) =...
# Custom-built fanfiction.net API import concurrent.futures import json import os import threading import time from dataclasses import dataclass import requests from bs4 import BeautifulSoup from fanfiction_apis.api import API, Query, Story, User from fanfiction_apis.string_lib import * @dataclass class FFNUser(Use...
#!/usr/bin/env python import rospy import smach import tf import actionlib import smach_ros from geometry_msgs.msg import PoseWithCovarianceStamped from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal, MoveBaseResult ##----------------------------------------------------------------------------------- ##Exampl...
import threading import time import html from datetime import datetime from typing import Dict, List from xml.dom import minidom import xmltodict from lxml import etree from requests.exceptions import HTTPError from snakesist.exist_client import ExistClient from models import EntityMeta from .helpers import xml_to_en...
from django.contrib import admin from django_countries.filters import CountryFilter as BaseCountryFilter from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.models import User from chat.models import Chat from accounts.models import District, Municipality, UserProfile from django.u...
# -*- coding: utf-8 -*- import logging import sys import functools from string import Formatter from collections import OrderedDict from collections.abc import Iterable from collections import namedtuple as _namedtuple from itertools import chain as iter_chain from abc import abstractmethod from inspect import is...
############################################################################## # # Copyright (c) 2008 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOF...
import sys import os import numpy as np import pandas as pd import matplotlib.pyplot as plt from matplotlib.ticker import FormatStrFormatter plt.rcParams['font.size'] = 6 root_path = os.path.dirname(os.path.abspath('__file__')) # root_path = os.path.abspath(os.path.join(root_path,os.path.pardir)) graphs_path = root_pat...
import mxnet as mx def vgg16_pool3(input): conv1_1 = mx.sym.Convolution(data=input, kernel=(3,3), pad=(100,100), num_filter=64, name="conv1_1") relu1_1 = mx.sym.Activation(data=conv1_1, act_type="relu", name="relu1_1") conv1_2 = mx.sym.Convol...
import rospy import actionlib from std_msgs.msg import Empty from kobuki_msgs.msg import Sound, AutoDockingAction, AutoDockingGoal from geometry_msgs.msg import Twist, Vector3, PoseStamped, Quaternion from sensor_msgs.msg import JointState from nav_msgs.msg import Odometry from move_base_msgs.msg import MoveBaseAction,...
serverko.trace('INFO: layout.py') def layout_script_userJoined(userID) : serverko.trace("JS:layout_script_userJoined " + userID) #layout.send(userID) # define layout area class LayoutArea: type = 'dummy' id = 'dummy' x = -111111 y = -111111 w = -111111 h = -111111 layout = 'hor' state = 'dummy' owner...
# the goal of the file is to develop the ada_boost algorithm import pandas as pd import numpy as np import os import time import matplotlib.pyplot as plt import multiprocessing from joblib import Parallel, delayed t0 = time.time() def beta_cal(epsolon): beta = 1/((1-epsolon)/epsolon) return beta def weight_...
import collections import re import inspect import copy from functools import wraps from flask import request from flask_restful import Resource, reqparse, inputs # python3 compatibility try: basestring except NameError: basestring = str class ValidationError(ValueError): pass def auth(api_key, endpo...
import theano import theano.tensor as tensor import numpy as np import cPickle as pickle import timeit import utils class LSTM(object): def __init__(self, hidden_size): self.hidden_size = hidden_size # lstm W matrices, Wf, Wi, Wo, Wc respectively, all config.floatX type self.W = theano....
from __future__ import print_function from __future__ import division from __future__ import unicode_literals from __future__ import absolute_import from builtins import * # NOQA from future import standard_library standard_library.install_aliases() # NOQA import argparse import functools import os import chainer fr...
#!/usr/bin/python3 """ Inspect a set of markdown files, and warn if there are: - duplicate links - malformed links """ import argparse import bs4 import logging import markdown import os import re import sys import urllib LOG = logging.getLogger(__name__) LOG.setLevel(logging.INFO) class Warnings: """ A single...
#!/usr/bin/env python3 # # This script recursively finds the log files produced by apalache and TLC # and collect them into a CSV file. It assumes that the directory layout # is similar to the one produced by mk-script, that is: # # out/1/detailed.log # out/2/tlc.out # ... # # <NAME>, 2019 import argparse import csv i...
# -*- coding: utf-8 -*- # ELEKTRONN3 - Neural Network Toolkit # # Copyright (c) 2017 - now # Max Planck Institute of Neurobiology, Munich, Germany # Authors: <NAME>, <NAME>, <NAME> import logging import time import warnings from typing import Dict import matplotlib.pyplot as plt import numpy as np import torch from ...
# -*- coding:utf-8 -*- import json import math import numpy as np import itertools # from mediapipe/python/solutions/face_mesh.py # https://github.com/google/mediapipe/blob/v0.8.6/mediapipe/python/solutions/face_mesh.py # this source code is redistributed under the Apache 2.0 License; # # Copyright 2020 The MediaPi...
""" The Microchip (Atmel) AVR family has 9 (nine) incompatible programming interfaces. The vendor provides no overview, compatibility matrix, or (for most interfaces) documentation other than descriptions in MCU datasheets, so this document has to fill in the blanks. The table below contains the summary of all necessa...
import multiprocessing import tensorflow as tf from tensorflow.python.ops.signal.fft_ops import ifft2d, fft2d, fft, ifft def tf_mp_ifft(kspace): k_shape_x = tf.shape(kspace)[-1] batched_kspace = tf.reshape(kspace, (-1, k_shape_x)) batched_image = tf.map_fn( ifft, batched_kspace, pa...
# # Copyright (c) 2013-2018 Quarkslab. # This file is part of IRMA project. # # 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 in the top-level directory # of this distribution and at: # # http:...
# imports import datetime as dt from isitfit.utils import SECONDS_IN_ONE_DAY import pandas as pd import boto3 from isitfit.utils import logger, NoCloudwatchException def raise_noCwExc(rc_id): raise NoCloudwatchException("No cloudwatch data for %s"%rc_id) import numpy as np class CloudwatchAssistant: """ Ma...
from __future__ import unicode_literals, division, print_function, absolute_import from builtins import zip import os import random import numpy as np from scipy.sparse import csr_matrix, lil_matrix from sklearn.svm import LinearSVC from sklearn.linear_model import LogisticRegression as logreg import sklearn.metrics as...
#!/usr/bin/python import socket, sys, os, re, random, optparse, time if sys.version_info.major <= 2:import httplib else:import http.client as httplib ## COLORS ############### wi="\033[1;37m" #>>White# rd="\033[1;31m" #>Red # gr="\033[1;32m" #>Green # yl="\033[1;33m" #>Yellow# ######################### os.system("c...
import matplotlib import numpy as np import pandas as pd from singlecellmultiomics.utils import is_main_chromosome, get_contig_list_from_fasta import matplotlib.gridspec as gridspec import matplotlib.pyplot as plt import pysam import seaborn as sns from matplotlib.patches import Circle from itertools import product imp...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Oct 10 18:03:32 2018 This file is the new version for calculating the uncertainty value in each patch It's better because: 1. It's a dynamic way of chosing most uncertain patch, since the provided patch can have overlapping for the adjacent pixels ...
import os import sys import logging import argparse import textwrap # Set up logger logging.basicConfig( format="%(asctime)s %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s", level=logging.INFO, datefmt="%H:%M:%S", stream=sys.stderr, ) logger = logging.getLogger(__name__) logger.setLevel(logging....
from typing import Tuple, Optional, List import numpy from PIL import Image from shapely import affinity from shapely.geometry import Polygon from gameengine.gameactors import Velocity from proto_gen.gamemaster_pb2 import ImageFrame, PaddleType, GameState, Actor, ScoreCard, ActorType def color_integer_to_rgb(color_...
# -*- coding: utf-8 -*- from __future__ import absolute_import from capsul import engine import os import six #import glob #import os.path as osp #import weakref ##import subprocess # Only in case of matlab call (auto_configuration func) #from soma.controller import Controller #from traits.api import Directory, Unde...
import collections import logging import os import tempfile from functools import wraps from typing import Optional, Tuple, Callable, OrderedDict import dace import onnx import torch import torch.nn as nn from torch.onnx import TrainingMode from daceml.autodiff.pytorch import make_backward_function from daceml.onnx i...
from __future__ import division from numpy import isclose from svgpathtools import Path, CubicBezier, Line, disvg, wsvg from svgpathtools.path import inv_arclength from options4rings import try_to_open_svgs_in_browser disvg = disvg if try_to_open_svgs_in_browser else wsvg def is_differentiable(path, tol=1e-8, return...
from datetime import datetime from django.core.exceptions import ObjectDoesNotExist, ValidationError from django.core.validators import validate_email from django.db import models class Profiles(models.Model): Username = models.CharField(max_length=30,unique=True) Email = models.CharField(max_length=254) Password =...
# -*- coding:utf-8 -*- from flask import current_app, jsonify,g from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, SignatureExpired, \ BadSignature from app.libs.redprint import Redprint from app.block.permission.validator import ClientForm, TokenForm, UidForm from app.libs.enums import Clien...
"""" My first version of a text-based flashcard program, uses only an in-program dictionary that can't be saved elsewhere. Bugs encountered and lessons learned: experienced the need for encapsulation by separating the quiz functions from the main game code for improved readability Learned to examine the code for repe...
import tensorflow as tf import numpy as np import pandas as pd import matplotlib.pyplot as plt from keras import backend as K from keras.preprocessing import sequence import Levenshtein import pickle # The custom accuracy metric used for this task def accuracy(y_true, y_pred): y = tf.argmax(y_true, axis =- 1) ...
""" train.py - Trains a model with a dataset 7/24/2019 Holiday Pettijohn """ import argparse import glob import json import subprocess import os import tensorflow as tf import xml_to_tfr def trainModel(model_location, train_dir="", test_dir="", config_location="default.config", out_dir="detector_trai...
from iidxrank import models from update import calculatedb # to use model from iidxrank import iidx # a simple common func def avg(ar): if (len(ar) == 0): # div by 0 error return 0 return sum(ar) / float(len(ar)) def safeInt(v): if (v == None): return 0 try: return int(v) except: return 0 #############...
import warnings import pprint from contextlib import suppress from bonobo.config import Option, Service, Configurable from cromulent import model, vocab import pipeline.execution from pipeline.util import implode_date, timespan_from_outer_bounds, timespan_from_bound_components from pipeline.util.cleaners import pars...
'''\ Get output from KubeEdge and Docker, and process it into readable format ''' import sys import logging import copy import numpy as np import pandas as pd from datetime import datetime def get_endpoint_output(config, machines, container_names): """Get the output of endpoint docker containers. Args: ...
""" Virtual machine for wirebus IoT PLC This project is a part of wirebus computing system. For more info refer to https://github.com/vt77/wirebus Author: <NAME> License: MIT """ import logging from functools import partial logger = logging.getLogger(__name__) ''' Simple iot assmbler commands and types C - ...
# Author: <NAME> import numpy as np import scipy.optimize from sklearn.utils import shuffle try: import cPickle as pickle except: import pickle from sklearn.metrics import confusion_matrix import os from scipy.optimize import minimize from scipy.stats import norm from scipy.stats import truncnorm from functools i...
"""HST/ACS Cosmos generator.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from . import astroimage_utils from tensor2tensor.data_generators import generator_utils from tensor2tensor.data_generators import image_utils from tensor2tensor.data_generator...
import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt import seaborn as sns import pandas as pd, numpy as np sns.set(style="ticks") sns.set_context("poster") plt.rcParams["font.family"] = "Helvetica" from nested_dict import nested_dict import argparse import util from scipy import stats import torch ...
from typing import Optional, Tuple from torch_geometric.typing import Adj, OptTensor, PairTensor import torch from torch import Tensor from torch.nn import Parameter from torch_scatter import scatter_add from torch_sparse import SparseTensor, matmul, fill_diag, sum, mul_ from torch_geometric.nn.conv import MessagePass...
import functools configuration = { "privateActions":True, "useFullStates":1, "nTo1Mapping":1, "truePrivIDs":False } ### Variable ### def getVarHash(var): return composeVarHash(var.agentID,var.varID,var.isPrivate) def composeVarHash(agent,varID,private): if private: return s...
import os import sys import copy import time import threading as mt import radical.utils as ru from .. import Session, TaskDescription from .. import utils as rpu from .. import states as rps from .. import constants as rpc from .request import Request def out(msg): sys.stdout.write('%s\n'...
import eth_tester import logging import pytest import web3 from functools import wraps from eth_tester import ( EthereumTester, ) from eth_tester.exceptions import ( TransactionFailed ) from web3.providers.eth_tester import ( EthereumTesterProvider, ) from web3 import ( Web3, ) from web3.contract imp...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import argparse import time from abc import abstractmethod from itertools import chain fr...
import json import logging import os import sys LOG = logging.getLogger(__name__) runtimeValues = {} # Depth of credscan credscan_depth = "2" DEPSCAN_CMD = "/usr/local/bin/depscan" # Flag to disable telemetry DISABLE_TELEMETRY = False # Telemetry server if required here TELEMETRY_URL = "" """ Supported language...
import numpy as np from datetime import datetime as py_dtime from datetime import timedelta import pandas as pd import requests import re from bs4 import BeautifulSoup as bs4 from bqplot import LinearScale, Axis, Lines, Figure, DateScale from bqplot.interacts import HandDraw from ipywidgets import widgets from IPython...
# Copyright 2019 <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...
""" Flask Servers ============= """ from __future__ import annotations import asyncio import json import logging from asyncio import Queue as AsyncQueue from queue import Queue as ThreadQueue from threading import Event as ThreadEvent from threading import Thread from typing import Any, Callable, Dict, NamedTuple, Opt...
#!/usr/bin/python # -*- coding: utf-8 -*- # # Developed by <NAME> <<EMAIL>> import torch.backends.cudnn import torch.utils.data import utils.data_loaders import utils.data_transforms import utils.network_utils from losses.multiscaleloss import * import torchvision import numpy as np import scipy.io as io from time...
import random import math def line(x1,y1,x2,y2, char): #draws line from.(x1,y1) to (x2,y2) both points included using char #if char == 'auto' selects /\|- according to orientation #if char is 'random' pick a random char! buffer = '' if x2 < x1: xoff = x2 else: xoff = x1 ...
# Import Elasticsearch package from elasticsearch import Elasticsearch import random, uuid, time, json, sys import time # Connect to the elastic cluster es=Elasticsearch([{'host':'elasticsearch','port':9200}]) e1={ } def get_random_words(words_list, total=1): ran_words = [] # enumerate over specified numb...
# === Start Python 2/3 compatibility from __future__ import absolute_import, division, print_function, unicode_literals from future.builtins import * # noqa pylint: disable=W0401, W0614 from future.builtins.disabled import * # noqa pylint: disable=W0401, W0614 # === End Python 2/3 compatibility from future import...
# coding: utf-8 """ Tests of the isentropic package. References ---------- 1. NACA-TR-1135 http://hdl.handle.net/2060/19930091059 2. Anderson, J.D.: "Modern compressible flow", 3rd edition. """ from __future__ import division, absolute_import import numpy as np import numpy.testing import pytest from skaero.gasd...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import re from fnmatch import fnmatch from ipaddress import ip_address from typing import AnyStr from urllib.parse import urlparse from string import ascii_letters from pathlib import Path from enum import Enum from refinery.units.pattern import arg, PatternExtractor fro...
#!/usr/bin/env python3 """ Author: Fredhappyface Date: 2020/02/19 Cat an image to the console. Inspired by img2txt https://github.com/hit9/img2txt.git by <NAME> """ from __future__ import annotations import argparse import urllib.request from pathlib import Path from sys import stdout from typing import Any, Callable...
#!/usr/bin/env python import numpy as np from scipy.interpolate import interp1d, RectBivariateSpline from pytz import timezone from astroplan import Observer from astropy.utils.data import download_file import astropy.units as u from astropy import coordinates as coord from tollan.utils.log import get_logger from a...
import _init_paths import os.path as osp import os import numpy as np from sacred import Experiment import torch from torch.autograd import Variable import torch.nn.functional as F import cv2 from PIL import Image import matplotlib.pyplot as plt from model.config import cfg as frcnn_cfg from tracker.config import g...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Script to generate tables from summary files Metrics, experiments, methods, and datasets are hard-coded as a means of validation. For the "best" experiment, the RBOCPDMS method is excluded because it fails too often. For the other experiments, datasets with incompl...
import enum import numpy as np from rig.place_and_route import Cores, SDRAM import struct from nengo_spinnaker.builder.netlist import netlistspec from nengo_spinnaker.builder.ports import InputPort, OutputPort from nengo_spinnaker import regions from nengo_spinnaker.regions.utils import Args from nengo_spinnaker.regio...