text
stringlengths
3.07k
22.1k
import os os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide" import pygame from pygame import sprite import random import cards from gamestate import * X = 0 Y = 1 class EnemyFleet(sprite.Group): def __init__(self): super().__init__() def draw_rect(self, screen): for s in self.sprites(): ...
#!/usr/bin/env python ############################################################################### # Copyright Kitware Inc. and Contributors # Distributed under the Apache License, 2.0 (apache.org/licenses/LICENSE-2.0) # See accompanying Copyright.txt and LICENSE files for details ##################################...
# -*- coding: utf-8 -*- """ 游戏运行环境 @author: 江胤佐 """ from __future__ import annotations import abc from functools import wraps from random import shuffle from typing import List, Iterator, Union, Set, Tuple import numpy as np from duguai import mode from ..card.cards import cards_view from ..card.combo import Combo f...
import sys import numpy as np from PyQt5.QtWidgets import QWidget, QApplication, QPushButton from PyQt5.QtGui import QPainter, QColor from PyQt5.QtCore import QTimer class Game: # class Game - логика игры # отвечает за взаимодействие с объектамми # основной объект - карта, заполненная 0 # объекты на ...
import autograd import autograd.numpy as np import sys import pickle from autograd.scipy.misc import logsumexp from numpy.linalg.linalg import LinAlgError from scipy.optimize import minimize from counterfactualgp.autodiff import packing_funcs, vec_mvn_logpdf from counterfactualgp.mpp import action_log_likelihood cl...
import os import yaml import logging import copy import prettytable as pt from aves2_client.aves2_api import job as job_api from aves2_client.utils import print_warning, print_success, sleep_and_print from aves2_client.settings import aves2_cfg aves2_cfg = aves2_cfg.dict() logger = logging.getLogger(__name__) JOB...
import gc from micropython import const from pyb import Pin, SPI import time RF_RECEIVER = const(0) RF_SYNTHESIZER = const(1) RF_STANDBY = const(2) RF_SLEEP = const(3) RF_STOP = const(0x01) RF_BUSY ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Simple script that converts a list of domains/subdomains to DNS A Records (IPV4) and DNS AAAA Records (IPV6). Does optional JSON an HTML output also. Requires pyperclip to copy the json result to the clipboard: pip3 install pyperclip Requires validators to validate do...
import logging import numpy as np import pandas as pd import torch import torch.utils.data from ..custom_types import * from ..utils import with_default, flat_filter, apply_oneormore, fold_oneormore from ..operator import Operator, LambdaOperator, FillMissing, Categorize, Normalize from ..field import * logger = log...
import torch import torch_scatter from torch import nn from torch_geometric.nn.conv.gcn_conv import gcn_norm from torch_geometric.utils import dropout_adj, subgraph from torch_geometric.utils.num_nodes import maybe_num_nodes # implemented based on GCNModel: https://github.com/DropEdge/DropEdge/blob/master/src/models....
# -*- coding: utf-8 -*- import unittest from bs4 import BeautifulSoup # verse number # paragraphs # intercession # lines # tipography # inflexion (*+) --> <sup> def t2bs(data): return BeautifulSoup(data, 'html5lib') def bs2t(data): return str(data.body)[6:-7] def bs(func, data, *args, **kwargs): soup = t2bs(data...
#!/usr/bin/python ##################################################################################### # Copyright (c) 2021 <NAME>, <NAME>, Carnegie Mellon University # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and # associated documentation files (the "Software"...
################################### # CALIBRATION DETECTION AND CORRECTION # ################################### # This file includes functionality for identification and correction of calibration events. # Functions include detection based on edges or persistence restricted by day of week and hour of day, identificati...
import scipy.io import scipy.fftpack import numpy as np import math import colorsys import random import matplotlib.pyplot as plt trans = [139.62,119.43,36.48,14.5] mdata = [] def avgWaveSpeed(data,ampStart,ampEnd,freq,transducers,index1,index2): total = 0 count = 0 #print(data) zer = highestPoint(da...
#!/usr/bin/python3 env print("setup the envirement ...") #!git clone https://github.com/MED-YAHYAOUI/style-transfer-pytorch #!pip install -e ./style-transfer-pytorch #!cd style-transfer-pytorch/ #import the necessary package and class from style_transfer import StyleTransfer from style_transfer import srgb_profil...
"""Radio Resource Allocation dataset obtention and processing. This script generates the radio resource management synthetic dataset into Networkx graphs, to use in iGNNition example. For the script to work, the following additional packages are needed: - tqdm -> https://github.com/tqdm/tqdm References: - <NAME>, ...
# -*- coding: utf-8 -*- """ Test of the functions in masci_tools.util.xml.converters """ import pytest from masci_tools.util.constants import FLEUR_DEFINED_CONSTANTS from masci_tools.io.parsers.fleur_schema import AttributeType import logging LOGGER = logging.getLogger(__name__) def test_convert_from_fortran_bool():...
""" Run combination benchmarks with various codes. By default use 20 arrays, 2048x2048 and float32, 16Mb per array, 320Mb for the 20 arrays (x2 if using also the variance plane). """ import argparse import statistics from functools import wraps from pathlib import Path from time import time import matplotlib.pyplot...
import json import os import shutil import tempfile import warnings from datetime import datetime from pathlib import Path import cv2 from moviepy.editor import ImageSequenceClip from natsort import natsorted from nd2reader import ND2Reader import numpy as np from pims import Frame import rainbow VID_FILE_EXT =...
# @Author: yican.kz # @Date: 2019-08-18 23:45:03 # @Last Modified by: yican.kz # @Last Modified time: 2019-08-18 23:45:03 # Standard libraries import json import argparse from itertools import chain # Third party libraries import numpy as np import pandas as pd from IPython.display import display INT8_MIN = np.iin...
# # This file is part of LiteX. # # Copyright (c) 2015-2022 <NAME> <<EMAIL>> # SPDX-License-Identifier: BSD-2-Clause import math from migen import * from migen.fhdl.specials import Tristate from migen.genlib.cdc import MultiReg from litex.soc.interconnect import stream from litex.build.io import SDRTristate # Layo...
# ROUBOT # Author: <NAME> - <EMAIL> from PIL import ImageGrab, ImageEnhance, ImageFilter, ImageOps import PIL import win32api, win32con, win32gui import pytesseract import keyboard from easysettings import EasySettings import datetime, time, json, os # ------------- Globals ------------- # # load the config config...
from tkinter import E import cv2 import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg from time import time import sys from pythonosc import udp_client import torch #model = torch.hub.load('ultralytics/yolov5', 'custom', path='best.pt',force_reload=True) #model.conf = 0.25 # NMS confide...
''' LSTM is inserted at the concatenation path ''' import torch import torch.nn as nn import torch.nn.functional as F import torchvision import numpy as np from blocks import simple_block, Down_sample, Up_sample from model import init_U_Net from RNN import ConvLSTMCell, ConvLayer from CenterLSTM import C...
""" Idles applications to save resources. Idling is performed by scaling down a deployment to zero replicas (no pods running). Only apps with the given label (`LABEL_SELECTOR`) and that are not using more than the given CPU threshold (`CPU_ACTIVITY_THRESHOLD`) will be idled. See https://kubernetes.io/docs/concepts/o...
import re import subprocess import sys from functools import lru_cache from pathlib import Path import fileinput from typing import Callable, Set from parsers.util import compress, OUTPUT_PATH # MS-DOS eof character that needs to be specially handled in some files DOS_EOF = chr(26) RETROSHEET_PATH = Path("retroshee...
import ast import collections import hashlib import itertools import multiprocessing import operator import os import pickle import subprocess import numpy as np import pandas as pd import pymzn import scipy.stats from statsmodels import robust from data_loader import get_best_result def cached_feature_matrix(probl...
import os from fastapi.datastructures import UploadFile from numpy.lib.function_base import delete from tensorflow.python.keras.backend import set_session from tensorflow.keras.applications.imagenet_utils import decode_predictions import cv2 import matplotlib as plt from tensorflow import keras import imutils import t...
# -*- coding: UTF-8 -*- __author__ = "d01" __email__ = "<EMAIL>" __copyright__ = "Copyright (C) 2013-21, <NAME>" __license__ = "MIT" __version__ = "0.3.0" __date__ = "2021-05-06" # Created: 2013-08-04 24:00 import threading import multiprocessing import multiprocessing.pool import os import datetime from flotils.loa...
from __future__ import print_function import sys, os import fnmatch from glob import glob import unittest from distutils.core import setup, Command def get_relative_path(): return os.path.dirname(os.path.abspath(os.path.join(os.getcwd(), sys.argv[0]))) def get_test_names(search_path, search_pattern, base_dir): ...
import logging import shlex import typing as t from typing import Iterable from prompt_toolkit import HTML from prompt_toolkit.completion import Completer, CompleteEvent, Completion, WordCompleter from prompt_toolkit.completion.nested import NestedDict from prompt_toolkit.document import Document import dimensigon.ds...
#!/usr/bin/env python """Creates JADE configuration for stage 1 of pydss_simulation pipeline.""" import logging import sys from datetime import timedelta import click from jade.common import CONFIG_FILE from jade.loggers import setup_logging from jade.utils.utils import load_data from PyDSS.common import SnapshotTi...
import numpy as np import hexy as hx from prism import * from helpers import * def get_hex_grid_centers(num_hexes_radius, mini_hex_radius): """Creates a large hexagonal grid of mini-hexagons. Returns the 2D xy centerpoint for each hexagon. Args: num_hexes_radius: the radius of the hexagonal grid. A sin...
# -*- coding: utf-8 -*- # File: batch_norm.py import re import six import tensorflow as tf from tensorflow.contrib.framework import add_model_variable from tensorflow.python.training import moving_averages import logging logging.getLogger().level = logging.INFO from tensorflow.contrib.framework import add_arg_scope ...
#! /usr/local/bin/python3 import argparse from openpyxl import load_workbook import boto3 import json import re parser = argparse.ArgumentParser(description="Example: python aws-ec2-pricing.py -f <file>.xlsx -w <worksheet> -r us-west-2 -i m5 -v gp2") parser.add_argument('-f', '--file', help='File name of the Excel wo...
#!/usr/bin/python import sys import os import re import enum # opcode refrence # key: mnemonic # value: 5-bit opcode opcodeRef = { "ADD" : 0b00001, "ADC" : 0b00001, "SUB" : 0b00001, "SBB" : 0b00001, "AND" : 0b00010, "OR" : 0b00010, "XOR" : 0b00010, "NOT" : 0b00010, "SHFL" : 0b00011,...
import docker from docker.models.images import Image from docker.models.containers import _create_container_args import yaml import shutil from multiprocessing import Process, Queue from distutils.dir_util import copy_tree import sys, os, time from pathlib import Path from jinja2 import Template def build_image(docker...
"""Downloads genome files from NCBI server Author: <NAME> """ import subprocess from sys import argv import os import ftplib import time import hashlib import sys sys.path.append('..') from config_files.sensitive import hmm_db_genome_downloads from config_files.config import * def parse_paths(fp: str, ext='.gbff.gz...
#!/usr/bin/env python """ https://www.kaggle.com/angps95/intro-to-reinforcement-learning-with-openai-gym REQUIRES: env.py in the same directory OUTPUTS: The optimal policies as calculated by the PI and VI algorithms on screen and as .csv files If run through launch file, .csv files go to tejas/resources directory, ...
import re import time import requests import mysql.connector from bs4 import BeautifulSoup header = { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 Safari/537.36", "Cache-Control" : "public, max-age=3600", "X-Requested-With": "XMLHttpRequest", ...
#!/usr/bin/env python # coding: utf-8 # # Additional NAICS Data Processing # **By: <NAME> and <NAME>** # This file is for adding additionally features to the generated NAICS data from the `NAICS Code Data Generation` notebook. Feel free to add on here if there are other features you'd like to analyze in junction wit...
""" File: day-18.py --------------- For Level 1, use the website. For Level 2, use the file puzzles/day-... """ from utils import * DAY = 18 YEAR = 2021 # --- Part 1 --- data = get_input(write=True, day=DAY, year=YEAR) class Node: def __init__(self, val): self.left = None self.right = None ...
#!/usr/bin/python2 # # Copyright 2013 Hewlett-Packard Development Company, L.P. # # 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 ...
""" Access SFEI ERDDAP copy of USGS SF Bay Water Quality data. Note that SFEI ERDDAP is not necessarily up to date! """ import os import six import numpy as np import matplotlib.pyplot as plt import xarray as xr import datetime import requests import pandas as pd import hashlib from bs4 import BeautifulSoup, Comment...
from nltk.corpus import wordnet as wn class Ideal: def __init__(self, word, expected): self.word = word self.expected = expected def group(*synset_names): synsets = map(lambda name: wn.synset(name), synset_names) return frozenset(synsets) ideals = [ Ideal('cannon', { group(...
# Sonar import random import sys def dibujarTablero(tablero): # Dibuja la estructura de datos del tablero. líneah = ' ' # espacio inicial para los números a lo largo del lado izquierdo del tablero for i in range(1, 6): líneah += (' ' * 9) + str(i) # imprimir los números a lo l...
import ast import os import re import sys import click import git import requests from termcolor import cprint if __name__ == '__main__': from parasite.pa.bin.download_source import pa_root, parasite_config_url from parasite.pa.bin.pycharm_project import create_temp_project else: from .download_source imp...
# coding: utf-8 from __future__ import unicode_literals, division import os import time import numpy as np from collections import Counter from custodian.utils import backup from custodian.custodian import ErrorHandler """ This module implements specific error handlers for VASP runs. These handlers tries to detec...
import pygame import os class Button: def __init__(self, screen, x, y, width, height, image_folder_path, command, name): self.screen = screen self.x = x self.y = y self.width = width self.height = height self.left = x self.right = x + width self.top ...
# # The MIT License (MIT) # # Copyright (c) 2017-2018 Zubax Robotics # # 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, c...
''' This module create map with: * your location * nearest points of film creation * location of creation selected film ''' import math import pandas as pd import folium from geopy.geocoders import Nominatim from geopy.extra.rate_limiter import RateLimiter from geopy.exc import GeocoderUnavailable geolocator = Nomina...
#!/usr/bin/python # # Copyright 2016 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 or ag...
import torch from torch import nn from ssltsc.architectures.ladder_utils import add_gaussian_noise, Combinator2d class ConvLayer(nn.Module): def __init__(self, in_channels, out_channels, padding=0, kernel_size=3): super(ConvLayer, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels,...
""" Load and render TMX maps, including camera logic. """ import inca.game import os import re import sdl import itertools import logging from .util import clamp import pytmx from pytmx.constants import TRANS_FLIPX, TRANS_FLIPY, TRANS_ROT log = logging.getLogger(__name__) class Map(object): def __init__(self,...
from discord import Embed import jikanpy as jk import modules.database as db import modules.entity as entity category = 'Animes' entity.Command.newcategory(category, ':japanese_goblin:Animes.') async def anime_channel(message, commandpar, bot): if commandpar == None: server = db.getserver(message.guild....
import re import requests import string from collections import deque import numpy as np from itertools import combinations import jax import jax.numpy as jnp from jax.config import config config.update("jax_enable_x64", True) from functools import partial, wraps from time import time two_pi=2*jnp.pi one_third = 1/3 ...
# Copyright 2020-present 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 wri...
import os import re import datetime import pybars import trafaret as t from aiohttp.web_reqrep import Response from aiohttp.web import HTTPFound from dateutil.parser import parse from eventsdisplay.eventsmonkey import EventsMonkey from eventsdisplay.settings import EVENTS_API_KEY, EVENTS_PER_PAGE, DEBUG, EVENTSMONKEY...
from Functions import * import DataAccessLayer as dal ## HexPlot: This is a 2D density plot with hexagonal bins instead of ## mindistance: Minimum Asteroid Distance from the sun you want in the plot (int) / au ## maxdistance: Maximum Asteroid Distance from the sun you want in the plot (int) / au ## date: the date you ...
import json import pytest import re import base58 from factom_did.client.constants import ( ENTRY_SCHEMA_V100, DID_METHOD_SPEC_V020, DID_METHOD_NAME, ) from factom_did.client.did import DID, DIDKeyPurpose, KeyType from factom_did.client.enums import EntryType, Network @pytest.fixture def did(): retu...
import six from six import iteritems import os import sys import time import cPickle import numpy as np import tensorflow as tf from collections import defaultdict _UIDS = defaultdict(int) _SESSION = None __all__ = ['get_uid', 'reset_uids', 'tf_set_session', 'tf_get_session', ...
from tqdm import tqdm import pandas as pd import numpy as np import gc import copy def AutoComple(action,caction): action['actionTime'] = action['actionTime'].apply(lambda x: pd.to_datetime(x)) aT4 = action[action['actionType'] > 3] temp1 = aT4.groupby(['userid'],as_index=True)['actionType'].diff() #pr...
"""Groups some info about the map so it can be used in an easy way""" from collections import deque from typing import List, Set from .pixel_map import PixelMap from .player import Player from .position import Point2, Rect, Size class Ramp: """Groups everything related to ramps and all the things to do near it"""...
from structs import Noun from helper import hprint, k100 import bisect import random import time class Lesson: @property def name(self): raise NotImplementedError @property def teacher(self): raise NotImplementedError def __init__(self, *args, **kwargs): self.classroom =...
"""PyLabware driver for IKA RV10 rotavap.""" from typing import Optional, Union import serial # Core imports from .. import parsers as parser from ..controllers import AbstractRotavap, in_simulation_device_returns from ..exceptions import PLConnectionError from ..models import LabDeviceCommands, ConnectionParameters ...
import ast from learning.convertDataFormat import ConvertToOneHot, ConvertToOneHotHelper def ConvertToInt(a): x = a.split(" ") return [float(i) for i in x] def GetDoor_OneHot(d): return { None: [0, 0, 0], "d1": [1, 0, 0], "d2": [0, 1, 0], "d3": [0, 0, 1], }[d] def GetLoadString_SD(s): d = ast.literal_ev...
# Copyright (c) 2013, FinByz Tech Pvt. Ltd. and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe import datetime from frappe import _ from frappe.utils import getdate, nowdate, date_diff, get_fullname from frappe.contacts.doctype.contact.contact impor...
import os from multiprocessing import Pool import requests import urllib.request import urllib.parse import csv from fuzzywuzzy import fuzz from fuzzywuzzy import process from fuzzywuzzy import utils from nltk.corpus import stopwords from nltk.tokenize import word_tokenize from nltk.stem.porter import PorterStemmer po...
import pytest import numpy as np from cycleindex import balance_ratio gama_pos = np.array([[0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0,...
#!/usr/bin/env python # coding: utf-8 # # MIDI to CSV Converter # In[657]: import mido import csv import os # In[178]: def cprint(s,b): if b: print(s) # In[273]: def get_active_notes(mid): active_notes = {} tracks = mid.tracks num_tracks = len(tracks) all_notes = num_tracks * [No...
import inspect import warnings from collections import namedtuple from functools import wraps from traceback import format_stack import numpy as np INTEGER_TYPES = (int, np.integer) __all__ = ('assign_only_single_slice', 'astro_data_descriptor', 'AstroDataDeprecationWarning', 'astro_data_tag', 'deprecated...
from app.worker.celery_init import celery from celery.utils.log import get_task_logger from app.settings import Config from app.utils.project_config import ProjectConfig from app.utils.predict_queue import PredictQueue from app.utils.priority_queue import TweetStore from app.utils.data_dump_ids import DataDumpIds from ...
from zetgo.zobrist import Zobrist class Board(object): def __init__(self, board_size): self.board_size = board_size self.dragons = {} self.positions = [[Position(x, y, self.board_size) for y in range(self.board_size)] for x in range(self.board_size)] self.zobrist = Zobrist(self.bo...
import hashlib import os import smtplib import time import zipfile from wsgiref.util import FileWrapper from django.http import StreamingHttpResponse from django.utils import timezone from django.utils.decorators import method_decorator from django.views.decorators.csrf import ensure_csrf_cookie, csrf_exempt from djan...
#! /usr/bin/env python # coding: ascii """\ Check include files in a ReST documentation project. This script verifies that all ReST source files reside within or below a given ``startdir``. Files that match the pattern "*.rst" are considered to be source files. The ReST sources are scanned for ``.. include::`` and ``...
import traceback import torch import torch.nn as nn import torch.jit as jit from typing import List, Tuple from torch import Tensor import math from torch.nn import functional as F import logging logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) error_handler = logging.FileHandler(filename='errors.l...
"""Quick draw dataset Example contributed by <NAME> (https://github.com/blrm) and adapted by <NAME> """ import pathlib import random import struct import urllib.request from itertools import islice import vpype as vp from shapely.geometry import MultiLineString import vsketch quick_draw_categories = ( "aircraf...
''' Dr. Dragonbot by MadScotty BEGIN LICENSE By existing on the same mortal coil as the author of this software you hereby allow the author, henceforth known as Dr. Awesomeweiner, to sleep on your couch, watch your television, and use your microwave. By reading this license you agree that Lord Satan isn't as bad a...
import logging import os import requests from cryptojwt.key_jar import KeyJar from cryptojwt.key_jar import init_key_jar from jinja2 import Environment from jinja2 import FileSystemLoader from oidcmsg.oidc import IdToken from oidcendpoint import authz from oidcendpoint import rndstr from oidcendpoint.client_authn imp...
from .imports import * # a shortcut getting the coordinates for an object, by its name get = coord.SkyCoord.from_name class Constellation(Talker): ''' A Constellation is collection of stars that can be accessed through a table of astropy coordinates, and/or plotted on a Finder chart Panel. '''...
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Python ToolTips for Tkinter V1.0.7 # # Copyright 2016, PedroHenriques # http://www.pedrojhenriques.com # https://github.com/PedroHenriques # # Free to use under the MIT license. # http://www.opensource.org/licenses/mit-license.php # # # # # # # # ...
import bpy import btools import random from contextlib import contextmanager @contextmanager def select_top_faces(): with btools.utils.bmesh_from_active_object(bpy.context) as bm: max_z = max([f.calc_center_median().z for f in bm.faces]) top_faces = [f for f in bm.faces if f.calc_center_median()....
import os import matplotlib.pyplot as plt import pandas as pd import seaborn as sns from arguments import get_args, make_full_string sns.set() # This file contains variance functions to plot results # Only a few of them are used and up-to-date # The others are left here as examples of how to design new plotting func...
#!/usr/bin/env python3 # name: test_inchi_sdf.py # author: <EMAIL> # license: MIT, 2022 # date: 2022-07-02 (YYYY-MM-DD) # edit: 2022-09-02 (YYYY-MM-DD) # """Identify systematic errors in inchi_sdf.py in a round trip. Script inchi_sdf.py aims to monitor the round trip of .sdf for which InChI trust's referen...
import ast from flask import Flask, jsonify, request, Response import json import requests from pymongo import MongoClient import logging from flask_cors import CORS import fastjsonschema from waitress import serve import os app = Flask(__name__) CORS(app) # Logging Parameters logger = logging.getLogger("-Distributor...
import json import logging import decimal from datetime import date, datetime, timedelta import tushare as ts from django.contrib.auth.decorators import login_required from django.db.models.functions import ExtractWeek from django.http import HttpResponse, JsonResponse from django.shortcuts import render from stockma...
from __future__ import print_function import os import argparse import torch import numpy as np from torch.optim import Adam, lr_scheduler from torch.nn import functional as F import data import bayesian_utils as utils import metrics import config_bayesian as cfg from Models.BayesianModels.Bayesian3Conv3FC import BB...
import argparse import os import pickle import matplotlib.pyplot as plt import numpy as np import multiprocessing as mp from sklearn.utils import shuffle from time import time from src.Parser import parseIn, parseOut from src.Utils import savePickle, loadPickle INPUTS = {'a': '../../inputs/a_example.txt', ...
import logging from abc import abstractmethod import torch from kornia.utils import one_hot as kornia_one_hot # Below are imported for access from other files to keep everything in the same place from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from torch.nn.functional import softmax from .metrics imp...
import os.path import random import cv2 import numpy as np from PIL import Image from torch.utils.data.dataset import Dataset from utils.dataset_utils import letterbox_image # 随机数生成,用于随机数据增强 def rand(a=0, b=1): return np.random.rand() * (b - a) + a # DataLoader中collate_fn参数 将一个batch中的np数组类型的图像和标签拼...
import os import numpy import rmgpy.util as util from rmgpy.tools.plot import * def retrieveSaturatedSpeciesFromList(species, speciesList): """ Given a radical `species`, this function retrieves the saturated species objects from a list of species objects. """ molecule = species.molecule[0] assert...
# Copyright (c) 2017, Fundacion Dr. <NAME> # 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 # list of conditions and...
import datetime import uuid import cryptography.hazmat.backends from collections import OrderedDict from cryptography import x509 from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import dsa, ec, rsa from cryptograp...
#!/usr/bin/env python3 import numpy as np import argparse from scipy.integrate import odeint as integrate from matplotlib import pyplot as plot from numpy.linalg import norm from mpl_toolkits.mplot3d import Axes3D parser = argparse.ArgumentParser() # Ball parameters constants = parser.add_argument_group("Constants"...
import os import api import secrets import requests import utils import routine from flask import Flask, render_template, session, request, redirect, Response from waitress import serve from paste.translogger import TransLogger from itertools import islice from replit import db routine.delete_logs() WEBHOOK = os.gete...
import math import os import cv2 import numpy import glyphs def optional_display(img, win_name, default_win_name): if win_name is not None: win_name = (win_name if isinstance(win_name, basestring) else default_win_name) cv2.imshow(win_name, img) cv2...
import datetime as dt from typing import Any, Optional, Union import discord import wavelink from discord.ext import commands from ...core import Bot from ...utils.bettercog import BetterCog from .utils import ( HZ_BANDS, LYRICS_URL, TIME_REGEX, URL_REGEX, EQGainOutOfBounds, InvalidEQPreset, ...
""" Tests for gpsdshm. These tests can be run against a real gpsd with shared memory or a mock-up. This is determined by whether the `shm.fix.latitude` attribute returns a "real" value or 0.0. The mock-up version is useful when running 'python setup.py test' or testing under tox and there is no gpsd process running. ...
import argparse import base64 import json import cv2 import numpy as np import matplotlib.pyplot as plt from keras.models import model_from_json from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array # Fix error with Keras and TensorFlow import tensorflow as tf tf.python.control_flow_ops...
import numpy as np import SimPEG as simpeg from SimPEG.Utils import meshTensor from SimPEG.EM.NSEM.RxNSEM import Point_impedance1D, Point_impedance3D, Point_tipper3D from SimPEG.EM.NSEM.SurveyNSEM import Survey from SimPEG.EM.NSEM.SrcNSEM import Planewave_xy_1Dprimary, Planewave_xy_1DhomotD from SimPEG.EM.NSEM.Problem...