text
stringlengths
3.07k
22.1k
from datetime import datetime from app import db # from werkzeug.security import generate_password_hash # from flask import Flask # from flask_sqlalchemy import SQLAlchemy # # app = Flask(__name__) # app.debug = True # # app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db/labpro.db' # app.config['SQLALCHEMY_TRACK_MO...
#!/usr/bin/env python # # abifpy.py # python module for reading abi trace files # http://github.com/bow/abifpy """Python module for reading .ab1 trace files.""" import datetime import struct from os.path import splitext, basename from sys import version_info RELEASE = False __version_info__ = ('1', '0', ) __version...
# -*- coding: utf-8 -*- """ Created on Thu Jun 7 13:17:58 2018 @author: jliubt This is the last version for calculation, checked on Sep-13, 2018 """ # This script is to calculate the one step jump rate of Na ions in Na11Ge2PS12 # There are total 5 Na sites, at differetn z coordinate, Na has differnt distrib...
import tarfile import requests import shutil import binascii import os import neo import struct import asyncio from contextlib import contextmanager from neo.Utils.NeoTestCase import NeoTestCase from neo.Storage.Implementation.DBFactory import getBlockchainDB from neo.Storage.Interface.DBInterface import DBInterface f...
#!/usr/bin/env python """ A Kestrel client library. """ from collections import defaultdict import random import re import threading import memcache class Client(threading.local): """Kestrel queue client.""" def __init__(self, servers): """Constructor. :param servers: The list of servers ...
import math from itertools import * from collections import Iterable, Sequence _srate = 44100.0 def set_srate(srate=44100.0): """Sets the default sampling rate.""" global _srate _srate = srate return _srate def get_srate(default=None): """Gets the default sampling rate.""" if default is No...
import json from django.contrib.admin.models import LogEntry, CHANGE from django.contrib.auth.models import User # Create your views here. from django.db.models import F from .models import Book, Author, BookInstance, Option, BigBlind def index(request): """View function for home page of site.""" # Generate...
#!/usr/bin/python # # Copyright (c) 2012 <NAME> <<EMAIL>> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify...
""" Holds PyTorch models """ from gensim.models import KeyedVectors import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.init import xavier_uniform_ from torch.autograd import Variable import numpy as np from math import floor import random import sys import time from constants import...
# Copyright 2022. <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, softw...
import re import os import json import objc from io import open from subprocess import Popen, PIPE from ..lib.cocoa import * from plotdevice.gui import bundle_path, set_timeout def get_default(label): if not re.match(r'^(NS|Web)', label): label = 'plotdevice:%s'%label pref = NSUserDefaults.standardUse...
"""json_utilities.py. Generates a `Documents` object with methods for accessing the contents of project's `json` folder. Last update: 2021-01-29 """ # Python imports import json import os import operator import re import shutil import tempfile import ipywidgets import pandas as pd import qgrid from IPython.display...
from math import sqrt import pytest from regym.environments import generate_task from regym.environments import EnvType @pytest.fixture def sac_config_dict(): config = dict() config['learning_rate'] = 3e-3 config['memory_size'] = 20000 config['gamma'] = 0.99 config['tau'] = 0.995 config['batch...
# Copyright 2021 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 argparse import logging import sys import torch import torchvision import torch.nn.functional as F from torch.utils.tensorboard import SummaryWriter from utils import data import models, utils def main(args): device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu') utils.setup_ex...
# Copyright 2017 <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...
class ReservationException(Exception): pass class Room: """ Class: as arguments gets the type and amount of free rooms, returns available free rooms type and count. class field 1. room_type: rooms' type (penthouse, double, single, etc - string) class field 2. count: amount of rooms (int) meth...
# coding=UTF-8 """Provides FCO API Client and decorator.""" from functools import wraps from fcoclient.exceptions import (NonRecoverableError, RecoverableError) import requests import json from requests import codes as rsc from time import sleep # REST Client default settings REST_RETRY_COUNT = 5 REST_RETRY_DELAY...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """A command line interface for running and testing classifiers. .. moduleauthor:: <NAME> """ # standard imports from typing import Optional, Iterable import logging import argparse import json import csv # third party imports import numpy as np # toolbox imports impo...
"""Python package colourmap generates an N unique colors from the specified input colormap.""" # Name : colourmap.py # Author : E.Taskesen # Contact : <EMAIL> # Date : Jan. 2020 # Licence : MIT # %% Libraries import matplotlib import matplotlib.pyplot as plt import numpy as np # %% Main d...
from __future__ import annotations import asyncio from math import atan2, pi, radians, degrees, sin, cos from geopy import distance from difflib import get_close_matches import discord from discord.ext import commands from typing import List, Dict, Tuple, TYPE_CHECKING import random if TYPE_CHECKING: from main impo...
from pathlib import Path import mlprocessors as mlpr import spikeextractors as se from spikeforest import SFMdaRecordingExtractor, SFMdaSortingExtractor import os, time, random, string, shutil, sys, shlex, json from mountaintools import client as mt from subprocess import Popen, PIPE, CalledProcessError, call class ...
import numpy as np import pdb def per_pkt_transmission(args, MM, TransmittedSymbols): # Pass the channel and generate samples at the receiver taus = np.sort(np.random.uniform(0,args.maxDelay,(1,MM-1)))[0] taus[-1] = args.maxDelay dd = np.zeros(MM) for idx in np.arange(MM): if idx == 0: ...
import pandas as pd import numpy as np import matplotlib.pyplot as plt import os from pathlib import Path from itertools import islice class My_dict(dict): def __init__(self): self = dict() def add(self, key, value): self[key] = value class Df(): def __init__(self, raw_data_location): ...
import random import inspect # Day 1 Exercise print(""" Day 1 - Exercises ----------------- Alice in the Wonderland - alpha frequency distribution table """) filename = "alice_in_wonderland.txt" file = open(filename, "r") fileContent = file.read().lower() alpha = 'abcdefghijklmnopqrstuvwxyz' frequency = [] for i in ...
# --------------------------------------------------------------------------- # # list.py # # # # Copyright © 2015-2021, <NAME>, original author. # # ...
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without eve...
'''Shared class definitions. LICENSE: Copyright 2019 Rendits 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 deepdab import * def print_info(board_size, policy, num_episodes=None, num_iterations=None, learning_rate=None, min_learning_rate=None, epsilon=None, min_epsilon=None, temperature=None, min_temperature=None, mode='self-play', reward='delayed', updates='online', architecture=None, de...
#!/usr/bin/python # # Copyright (c) 2013 Protectus,LLC. All Rights Reserved. # import sys, time, os, signal from select import select import socket import traceback from datetime import datetime import subprocess from optparse import OptionParser import math import configparser from trafcap.lpjPacket import IpLpjPack...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import tensorflow.contrib.layers as layers import numpy as np from pysc2.lib import features OUT_PUT_SPATIAL_DIM = 9 def build_net(minimap, screen, info, msize, ssize, num_action, nty...
#!/usr/bin/env python import click as ck import numpy as np import pandas as pd import tensorflow as tf import tensorflow_addons as tfa import logging import math import time import sys import os from collections import deque from tensorflow.keras.models import Model, load_model from tensorflow.keras.layers import La...
#<NAME> 10/04/19 #code used from: https://www.pyimagesearch.com/2015/09/14/ball-tracking-with-opencv/ #since sample code used to detect a ball, likely will #struggle on side profile views of cap from collections import deque from imutils.video import VideoStream import numpy as np import argparse import cv2 import im...
''' SWAP convenience functions ''' import json import numpy as np import scipy as sci import interest_rate_base as intbase import interest_rate_capfloor_convenience as capconv import interest_rate_dates as intdate import interest_rate_discount as intdisc import interest_rate_instruments as intrate # import interest_rat...
import argparse, re, os, json from PIL import Image, ImageDraw, ImageFont from termcolor import colored """ RULES: Below are working examples: python main.py python.jpg -fs 60 90 -x 415 455 -y 405 475 --text "Part 43:" "Lambda Functions" --font ubuntu/Ubuntu-Bold ubuntu/Ubuntu-BoldItalic python main.py tkinter.jpg -f...
# Copyright 2015 Observable Networks # # 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 ...
''' Question 2.1 Skeleton Code Here you should implement and evaluate the k-NN classifier. ''' from sklearn.model_selection import KFold import data import numpy as np import collections from datetime import datetime # Import pyplot - plt.imshow is useful! import matplotlib.pyplot as plt class KNearestNe...
from datetime import datetime from typing import Union, Optional from fastapi import FastAPI, Depends, status, Response, HTTPException from pysirix import ( sirix_async, DBType, JsonStoreAsync, Resource, SirixServerError, ) import httpx from . import schemas app = FastAPI() async def get_json_st...
from sympy import MatrixSymbol, Q, ask, Identity, ZeroMatrix, Trace, MatrixSlice from sympy.utilities.pytest import XFAIL from sympy.assumptions import assuming X = MatrixSymbol('X', 2, 2) Y = MatrixSymbol('Y', 2, 3) Z = MatrixSymbol('Z', 2, 2) def test_square(): assert ask(Q.square(X)) assert not ask(Q.squar...
class SumoParams(): def __init__(self, port=None, time_step=0.1, vehicle_arrangement_shuffle=False, starting_position_shuffle=False, emission_path=None, rl_speed_mode='no_collide', human_speed_mod...
# -*- coding: utf-8 -*- """Generate board game charts from ratings data.""" import json import logging import sys from datetime import datetime, timedelta, timezone from itertools import islice, tee from pathlib import Path import numpy as np import pandas as pd from dateutil.rrule import MONTHLY, WEEKLY, YEARLY, ...
"""Test model.""" import argparse import base64 from datetime import datetime import os import shutil import cv2 import numpy as np import socketio import eventlet import eventlet.wsgi from PIL import Image from flask import Flask from io import BytesIO #import lineDetector import torch from torch.autograd import Vari...
# -*- coding: utf-8 -*- import argparse import json from os import listdir from os.path import join import numpy as np import pandas as pd from src.utilities import mkdir_if_needed def read_presentation_type(sequence): """ This function extracts the presentation_type variable from a sequence dictionary. ...
import os import math import json import ntpath import numpy as np import pandas as pd from tensorflow.python.framework.errors_impl import NotFoundError from tensorflow.python.platform import gfile from ..config import config_reader from . import request_util, db_ops from .metrics import train_eval_graphs from .par...
# coding=utf-8 from __future__ import absolute_import, division, unicode_literals import random from datetime import datetime from decimal import Decimal from itertools import chain, repeat, tee try: from unittest import mock except ImportError: import mock import pytest from about_time import about_time, d...
# -*- coding: utf-8 -*- # Copyright 2020 Green Valley Belgium NV # # 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 appl...
""" CompareWidget :Authors: <NAME> """ from PySide.QtGui import QApplication from PySide.QtGui import QWidget from PySide.QtGui import QGridLayout from PySide.QtGui import QLabel from PySide.QtGui import QHBoxLayout from PySide.QtCore import QObject from PySide.QtCore import Slot from PySide.QtCore import Qt from co...
from sys import _current_frames from flask import render_template, request, flash, redirect, url_for from numpy import quantile from app import app from app.LearningForest import LearningForest import pandas as pd import psycopg2 LF = LearningForest() #defining global variables selected_lecture = "" # Page Function...
# -*- coding: utf-8 -*- import logging import pandas as pd import numpy as np import gc import src.features.build_features as feats from pathlib import Path from dotenv import find_dotenv, load_dotenv def summarise_purchase_amount(df, prefix): """ Summarises the purchase amount for each card id in the pro...
""" platformer.py Author: Meg Credit: http://brythonserver.github.io/ggame/#ggame.Sprite.collidingWithSprites https://github.com/HHS-IntroProgramming/Platformer https://runpython.org/?user=BrythonServer&repo=Platformer&name=platformer.py Noah Assignment: Write and submit a program that implements the sandbox platformer...
import abc import math import torch import torch.nn as nn import torch.nn.functional as F from PytorchRouting.CoreLayers import Selection import PytorchRouting.DecisionLayers as ptrdl from PytorchRouting.RewardFunctions.PerAction import RunningAverageCollaborationReward from PytorchRouting.RewardFunctions.PerAction.Per...
from collections.abc import MutableMapping class MapBase(MutableMapping): ''' Abstract base class that includes private _Item Allowing for a Composition deign patter to prompt us to add our own functionality ''' class _Item: __slots__ = '_key', '_value' def __init__(self,k,v): ...
__author__ = 'ssong' from amigo import amigo_init, amigo from yql_analystsummary import yql_analyst_summary_init, yql_analyst_summary from yql_analysttrends import yql_analyst_trends_init, yql_analyst_trends from yql_competitors import yql_competitor_init, yql_competitor from yql_day import yql_day_init, yql_day from y...
import argparse import time import cubework import torch from cubework.distributed import ParallelManager as pm from cubework.distributed.collective import all_reduce from cubework.utils import ( CommProfiler, MemoryTracker, calc_model_size, calc_tflops, clip_grad_norm, get_current_device, ...
from abc import ABC from typing import Any, Dict, List, Optional, Tuple, Union from .util import safer_eval """ This parsing solution has the following structure: 1. Separate header and config file content, if necessary 2. Split up text into lines, if still necessary 3. Parse each line individually 4. Use recursive ...
import struct import socket from pybgp import nlri def decode(bytes, idx=0): flagb, type = struct.unpack_from('BB', bytes, idx) idx += 2 used = 2 if flagb & 16: length, = struct.unpack_from('>H', bytes, idx) idx += 2 used += 2 else: length, = struct.unpack_from('!...
import cv2 as cv import numpy as np from cell_info import CellInfo digit_pic_size = 28 def gaussian_blur(src, kernel_size=(5, 5), sigmaX=0): return cv.GaussianBlur(src, kernel_size, sigmaX) def cross_closing(src): se = cv.getStructuringElement(cv.MORPH_CROSS, (3, 3)) return cv.morphologyEx(src, cv.MORP...
#!/usr/bin/env python # # Copyright 2019 DFKI GmbH. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merg...
# Copyright 2014 Google Inc. 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...
import asyncio from dataclasses import dataclass from typing import Any from unittest import skip import orjson from mock import MagicMock, patch from bxutils.encoding.json_encoder import Case # TODO: remove try-catch when removing py3.7 support try: from asyncio.exceptions import TimeoutError except ImportError...
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. # -*- test-case-name: vertex.test.test_ptcp -*- from __future__ import print_function import random, os from twisted.internet import reactor, protocol, defer, error from twisted.trial import unittest from vertex import ptcp def reallyLossy(meth...
# -*- coding: utf-8 -*- """Module Model.""" # system module import datetime from typing import Any, Dict, Iterator, List, Optional, TYPE_CHECKING, Tuple, Union, cast # community module import sqlalchemy as sa from sqlalchemy import orm from sqlalchemy.ext.hybrid import hybrid_property # project module from .base imp...
# Reddit Image Sync # 2021 <NAME> # Scrapes all subreddits defined in subs.txt for (default) 20k max queries each. # reminder, this is not meant to be a fast operation. Each download takes 2 sec to avoid rate limiting / premature D/C. # Set it and forget it overnight. # install "praw" on pip import praw import...
# coding: utf8 import os, uuid, cStringIO ##@auth.requires_login() def listado(): # registros para paginaciòn reg_por_pagina = 100 # preparo ubicaciones a elegir: [(id_ubicacion, descripcion)] # solo provincias (para listar departamentos dentro de ellas) ubicaciones = msa(msa.ubicaciones.cl...
#!/usr/bin/env python DEFAULT_TABLE_FORMAT = 'ascii.fixed_width' def my_loadtxt(fname, as_table=False, as_dict=False, table_format=DEFAULT_TABLE_FORMAT, **kwargs): """ read a collimated text file and return the data as requested. leverages :meth:`astropy.table.Table.re...
from selenium import webdriver from thonny import get_workbench from selenium.common import exceptions from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from tkinter.simpledialog import askstring from threading import Thread import time class Singleton: """This Singleton class is need...
from argparse import ArgumentParser from copy import deepcopy from pathlib import Path import random from typing import List from joblib import Parallel, delayed, cpu_count from matplotlib import pyplot as plt import numpy as np import open3d as o3d from tqdm import tqdm from dataset.dataset_interface import DatasetI...
import numpy as np from matplotlib import pyplot as plt import torch from torchvision import transforms # from skimage.transform import resize from skimage.transform import resize import cv2 import sys import numpy as np import matplotlib.pyplot as plt import time import os import OpenEXR import Imath from scipy.misc...
# -*- coding: utf-8 -*- """ Helper functions for all tests. """ from pathlib import Path import tempfile from typing import Optional import sys import geopandas as gpd import geopandas.testing as gpd_testing import pygeos import shapely.geometry as sh_geom # Add path so the local geofileops packages are found sys.pa...
import numpy as np import math from numba import jit, cuda, prange from pythonabm import cuda_magnitude @cuda.jit def jkr_forces_gpu(jkr_edges, delete_edges, locations, radii, jkr_forces, poisson, youngs, adhesion_const): """ This just-in-time compiled CUDA kernel performs the actual calculations for the...
from repiet.tracer import Tracer as _Tracer from repiet.util import Node as _Node class StaticEvaluator: """ A static evaluator for Piet. We take the Nodes output by the Tracer, and run them through a specialized virtual machine, producing a new set of Nodes. The Parser and Tracer have two types ...
import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt from skimage import exposure import numpy as np from scipy import misc import base64 import os import shutil import math import zipfile from PIL import Image def histo_equal(image): """ Performs histogram equalization on input image. ...
''' This file includes some util functions. ''' import random import numpy as np import scipy from scipy import sparse from scipy.stats import norm import networkx as nx import community from generator import ER_generator import logging from scipy.special import comb from math import factorial np.seterr...
import asyncio import copy import io import math import os import pathlib import sys import threading from typing import Mapping, Optional import aiohttp import vpype as vp import watchgod from kivy.app import App from kivy.clock import Clock, ClockEvent from kivy.logger import Logger from kivy.properties import ( ...
import torch.nn.functional as F import torch import torch.nn as nn from torch.nn import Parameter from tools.model_utils import get_laplace_mat class GIN(nn.Module): def __init__(self, in_channels, out_channels, layer_num=2, mid_channels=256, ...
# coding: utf-8 import base64 import ldap import random import re import textwrap from datetime import datetime, timedelta from django.utils import timezone from django.contrib import messages from django.db import transaction from django.views.generic import TemplateView, View from django.contrib.auth.models import Us...
''' This module allows to load texture and to sample from it ''' import numpy as np from vulkbare import load_image, resize_image from vulk import vulkanobject as vo from vulk import vulkanconstant as vc from vulk.util import mipmap_size, mipmap_levels class RawTexture(): """A Raw texture is not initialized with...
""" ENVI reader tools. """ import numpy as np import os ext_list = ['', '.img', '.raw', '.hyspex', '.bsq', 'bil', 'bip'] """ ENVI data type Reference: https://www.harrisgeospatial.com/docs/ENVIHeaderFiles.html The type of data representation: 1 = Byte: 8-bit unsigned integer 2 = Integer: 16-bi...
""" FILE: discreteFourierBesselTrafo.py Module implementing functions to compute Fourier-Bessel function (zero order Hankel transform) in terms of a rapidly convergent Fourier-Bessel expansion of the function of interest. The algorithmic procedure follows the method detailed in Ref. [1]. The theory and operational ...
# -*- coding: utf-8 -*- # Copyright 2018 <NAME> <<EMAIL>> # # 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 list of conditions and th...
from vkrine_stickerbot.eventlistener import MessageListener import vkrine_stickerbot.utils as utils import shlex import vkrine_stickerbot.exceptions as exceptions import sys import re import traceback class CommandHandler(MessageListener): def __init__(self, bot): super().__init__() self.__bot__ =...
import numpy as np import pandas as pd import re import nltk from nltk.corpus import stopwords from nltk.stem.wordnet import WordNetLemmatizer from nltk.tokenize import word_tokenize from sklearn.feature_extraction.text import TfidfVectorizer nltk.download('punkt') nltk.download('stopwords') nltk.download('wordnet') ...
import sys import webbrowser from ui.app_state import app_state class InvalidInputException(Exception): pass class CommandStoppedException(Exception): pass class Command: def __init__(self, io, service=None): self.io = io self.service = service def execute(self, argv): se...
''' Copyright 2021 <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...
# coding: utf-8 import numpy as np from psydac.utilities.quadratures import gauss_legendre from psydac.core.bsplines import quadrature_grid from psydac.core.bsplines import find_span from psydac.core.bsplines import basis_funs_all_ders from psydac.core.bsplines import basis_ders_o...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import zipfile import os.path import os import time import shutil import subprocess import plistlib signextensions = ['.framework/','.dylib','.appex/','.app/'] bundleidentifierkey = 'CFBundleIdentifier' replaceplistkey = 'BundleIdentifier' oldbundleId = N...
""" Requests history (episode/chapter) for an anime/manga entry This requires authentication (username/password) and selenium, since this info isn't accessible from the API """ import os import re import json import time from itertools import islice from urllib.parse import urlparse, parse_qs from pathlib import Path...
# films/api_views.py from rest_framework import viewsets, status, mixins, generics from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from rest_framework.request import Request from django...
# -*- coding: UTF-8 -*- """Separable fully-connected layer, as described in https://www.biorxiv.org/content/10.1101/146431v3 """ from keras import backend as K try: from keras import initializers as initializations except Exception as e: print(e) from keras import initializations from keras.layers impo...
import os import pygame, sys from pygame.locals import K_a, K_s,K_w,K_d,K_LEFTBRACKET,K_RIGHTBRACKET, K_RIGHT, K_LEFT, QUIT from PIL import Image pygame.init() ''' main() sets these (perhaps differently), so make changes down there. If you cut/copy this code somewhere you need these variables globally, or make it a...
""" Regression test for general EOS 1D Riemann problems. """ # Modules import logging import sys import numpy as np import scripts.utils.athena as athena import scripts.utils.comparison as comparison from scripts.utils.RiemannSolver.riemann import riemann_problem from .eos_riemann import _tests, _thresh, _states sys.p...
import argparse import os import sys parser = argparse.ArgumentParser() parser.add_argument('--epochs', type=int, default=100) parser.add_argument('--batch_size', type=int, default=32) parser.add_argument('--lr', type=float, default=1e-2) parser.add_argument('--gpu', type=int, default=0) parser.add_argument('--trai...
import os from unittest import TestCase from nidus.log import ( Log, LogEntry, Page, PageEmptyException, PageFullException, Pager, append_entries, ) class PageTestCases(TestCase): def test_load(self): entry1 = LogEntry(term=1, item="hello").to_bytes() entry2 = LogEntry...
# coding=UTF-8 import tensorflow as tf from google.protobuf import text_format from utils.common_info import CommonInfo class SimpleModel: ''' model info class ''' def __init__(self): self.model_name = '' self.nodes = set() self.inputs = set() self.outputs = set() ...
import numpy as np import cv2 as cv import time, math, copy, uuid, sys def get_fret_coords(frame): (height, width, _) = frame.shape bottomScale = 0.27 topScale = 0.425 heightScale = 0.46 bottomL = width*bottomScale bottomR = width - bottomL bottomY = height - 2 topL = width*topScale...
# add oversampling # new image format # inceptionresV2 import glob import os import warnings warnings.filterwarnings("ignore") import numpy as np import torch from torch.autograd import Variable from tqdm import tqdm import pandas as pd from HPAdataset_01 import HPADataset from torch import nn fro...
#!/usr/bin/env python3 import subprocess import glob import os import shutil import sys import tarfile import itertools import hashlib import platform from pathlib import Path try: from urllib.request import urlopen except ImportError: raise Exception("Must be using Python 3") VERSION = "10.0.1" #SOURCE_URL =...
#!/usr/bin/python # -*- coding= utf-8 -*- #file: xml_to_dict.py #from xml.dom import * from xml.dom.minidom import Document,parseString,Node from json import load as json_load from json import dumps as json_dumps from os import linesep as oslinesep #from debug_utils import * def xml_node_to_dict(node): ...
import torch import torch.nn as nn import math """ from functools import partial, wraps from utils import default # This function is for reversible layer def cache_method_decorator(cache_attr, cache_key, execute_in_cache=False): def inner_fn(fn): @wraps(fn) def wrapper(self, *args, namespace=None,...
import os import glob import argparse import shutil import urllib import datetime import time import multiprocessing import itertools import zipfile import pickle import pandas as pd from string import digits as string_digits from string import punctuation as string_punctuation from collections import defaultdict imp...