text
stringlengths
3.07k
22.1k
from requests import get from requests.exceptions import MissingSchema from bs4 import BeautifulSoup as Soup from sys import argv, exit as sys_exit import os import re os.system('cls') #region functions def map_to_range(value, leftMin, leftMax, rightMin, rightMax): # Figure out how 'wide' each range is ...
#!/usr/bin/env python # SPDX-License-Identifier: BSD-3-Clause # Copyright(c) 2018 Nippon Telegraph and Telephone Corporation import common import os import sys work_dir = os.path.dirname(__file__) sys.path.append(work_dir + '/..') from conf import env def add_eal_args(parser, mem_size=1024, mem_channel=4): pars...
# Copyright 2015-2016 Stanford University # # 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 ...
from c2g.models import * from django.contrib.auth.models import User,Group from datetime import datetime, timedelta from courses.reports.generation.C2GReportWriter import * def gen_course_dashboard_report(ready_course, save_to_s3=False): dt = datetime.now() course_prefix = ready_course.handle.split('--')[0] ...
# -*- coding: utf-8 -*- import click import logging import os import sys import cv2 sys.path.append(os.path.abspath(".")) import numpy as np from keras.preprocessing import image from keras.preprocessing.image import ImageDataGenerator from concurrent.futures import ThreadPoolExecutor from src.utils_io import Consol...
import os from rpython.rlib.rsre import rsre_core from rpython.rlib.rstring import StringBuilder from topaz.objects.fileobject import FNM_NOESCAPE, FNM_DOTMATCH from topaz.utils import regexp from topaz.utils.ll_file import isdir from topaz.utils.ordereddict import OrderedDict def regexp_match(cache, re, string): ...
""" A component which allows you to update your custom cards and components. For more details about this component, please refer to the documentation at https://github.com/custom-components/custom_updater """ import logging import os import subprocess from datetime import timedelta import time import requests import ...
#!/usr/bin/env python # # Manage a single partition (info, read, write). # # Copyright (C) 2015 <NAME> <<EMAIL>> # Licensed under the MIT license <http://opensource.org/licenses/MIT>. from __future__ import print_function from collections import OrderedDict from contextlib import closing, contextmanager import argpars...
import argparse import asyncio import contextlib import fnmatch import functools import importlib.metadata import logging import os import pathlib import shutil import tempfile import mutagen import mutagen.mp3 from . import decoders, encoders LOGGER = logging.getLogger('harmonize') try: VERSION = importlib.met...
# -*- coding: UTF-8 -*- """ collector.xueqiu - 采集雪球数据 官网:https://xueqiu.com/ ==================================================================== """ import requests import time import json from collections import OrderedDict from bs4 import BeautifulSoup import webbrowser from zb.crawlers.utils import get_header im...
import torch import numpy as np import torch_geometric import torch_geometric.data from torch_geometric.datasets import TUDataset, Planetoid from collections import Counter from sklearn.model_selection import StratifiedKFold, StratifiedShuffleSplit POWERFUL_GNN_DATASET_NAMES = ["PTC_PGNN"] TU_DORTMUND_DATASET_NAMES =...
#%% import torch import torchvision import torchvision.transforms as transforms import matplotlib.pyplot as plt import numpy as np batch_size = 100 train_dataset = torchvision.datasets.MNIST( root = './data' ,train = True ,transform = transforms.ToTensor() ,download = True ) test_dat...
# -*- coding: utf-8 -*- """Example NumPy style docstrings. This module demonstrates documentation as specified by the `NumPy Documentation HOWTO`_. Docstrings may extend over multiple lines. Sections are created with a section header followed by an underline of equal length. Example ------- Examples can be given usi...
import numpy as np import pandas as pd import geopandas from geopandas import GeoDataFrame, read_file from geopandas import _compat as compat from pandas.testing import assert_frame_equal import pytest from geopandas.testing import assert_geodataframe_equal @pytest.fixture def nybb_polydf(): nybb_filename = ge...
from html import unescape from bs4 import BeautifulSoup import wikipedia import discord from discord.ext import commands from discord.ext.commands import Cog import random,json,datetime import asyncio def random_page(): random = wikipedia.random(1) try: result = wikipedia.page(random).summary except wi...
import requests import unicodedata import pandas as pd from collections import Counter import numpy as np import json import schema from os.path import join import os from c3cloud_semanticmapper_client.objects import * from c3cloud_semanticmapper_client.lib import * from c3cloud_semanticmapper_client.helpers import sc...
"""Class based cli builder with sub commands.""" import shlex import sys import argparse import asyncio import itertools import typing import functools import inspect import stringcase from ._tools import is_windows from ._services import Service from ._immutable import ImmutableDict from .events import PreceptEvent ...
# Copyright 2018 DeepMind Technologies Limited. 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 ...
# # License: Yujin # ############################################################################## # Description ############################################################################## """ .. module:: dot_to_qt :platform: Unix :synopsis: Repackaging of the limiting ROS qt_dotgraph.dot_to_qt module. Oh m...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import json import os import random from tqdm import tqdm, trange import numpy as np from torch.nn import functional as F import torch.nn as nn import torch import logging # import pdb from sk...
import pickle import os import numpy as np import argparse from matplotlib import pyplot as plt import matplotlib import glob import pandas as pd from tqdm import tqdm parser = argparse.ArgumentParser(description='save annotations') parser.add_argument('--vis', action='store_true', default=False, h...
import bot_input_struct as bi import bot_manager import configparser import ctypes import game_data_struct as gd import mmap import multiprocessing as mp import queue import msvcrt import rlbot_exception import time import os import sys import subprocess # These packages enhance RLBot but they are not critical to its ...
from typing import Tuple from rectgle import Rectgle from terrain import Terrain from math import tan, sqrt from queue import PriorityQueue import numpy as np RACINEDEDEUX = sqrt(2) class Calculateur(): def __init__(self, depart, arrivee, rectangle: Rectgle, terrain: Terrain): """calcule la...
import functools from bokeh.application import Application from bokeh.application.handlers import FunctionHandler from bokeh.io import output_file, show, curdoc import os from bokeh.layouts import column from bokeh.models import Div, Panel from tornado import web from .reporting_bokeh_graph import process_data_graph f...
import scipy.linalg as la import numpy as np from typing import Union import parla.comps.determiter.saddle as dsad import parla.comps.preconditioning as rpc import parla.comps.sketchers.oblivious as sko from parla.drivers.least_squares import dim_checks, OverLstsqSolver from parla.comps.determiter.logging import Sketch...
# Utils used with tensorflow implemetation import tensorflow as tf import scipy.misc as misc import os, sys from six.moves import urllib import tarfile import zipfile import scipy.io import numpy as np RESIZED_IMAGE_HEIGHT = 1944 RESIZED_IMAGE_WIDTH = 2592 def argmax_threshold(input, threshold): threshold = tf.co...
import numpy as np import tensorflow as tf from tensorflow.contrib import rnn import data_loader import matplotlib.pyplot as plt import gzip import json import datetime class SeriesPredictor: def __init__(self, input_dim, seq_size, hidden_dim): # Hyperparameters self.input_dim = input...
import os import csv import sys import time import json import h5py import logging import pickle as pkl import argparse import random from collections import OrderedDict import torch import numpy as np from tqdm import tqdm from nglib.common import utils from nglib.narrative.dataset import sample_mcnc from nglib.narr...
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns def plot_corr_matrix(in_corr_matrix): """ Plots the correlation matrix as a heatmap using seaborn """ sns.set(style = 'white') f, ax = plt.subplots(figsize = (12, 9)) # Generate a mask for the...
"""Run the scaling environment using blocks of different scales. Copyright 2020 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. """ import os, sys; sys.path.insert(0, os.path.abspath(".")) import environments.scaling_repeater_del...
from flask import Blueprint, Response, request, send_file from datetime import datetime, timedelta from dateutil.relativedelta import relativedelta import pandas as pd from io import BytesIO from .db import engine from .auth import checkAuth # Create Blueprint bp = Blueprint('expenses', __name__, url_prefix='/api/expe...
import tornado.ioloop import tornado.web import os import os.path import tornado.tcpserver import ssl import logging import flickr_api import pprint import uuid import json flickr_auth_info = { "api_key" : "<KEY>", "secret" : "69003acec0548150" } flickr_api.set_keys( api_key = flickr_auth_info['...
''' * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT-0 * * 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, includin...
""" Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying t...
import re from datetime import date from django import forms from forum.models import * from django.utils.translation import ugettext as _ from django.utils.encoding import smart_unicode from general import NextUrlField, UserNameField from forum import settings, REQUEST_HOLDER from forum.modules import call_all_hand...
#!/usr/bin/env python from __future__ import division from ase.atoms import Atoms from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt import numpy as np import numpy.linalg from ase.geometry import cell_to_cellpar, crystal_structure_from_cell, cellpar_to_cell from ase.dft.kpoints import (get_special...
# -*- coding: utf-8 -*- from functools import partial import numpy as np import torch import torch.nn as nn import warnings from memcnn.models.additive import AdditiveCoupling from memcnn.models.affine import AffineCoupling from memcnn.models.utils import pytorch_version_one_and_above warnings.filterwarnings(action='...
"""Defines the templaters.""" import os.path import ast from jinja2.sandbox import SandboxedEnvironment from jinja2 import meta import jinja2.nodes from .errors import SQLTemplaterError from .parser import FilePositionMarker _templater_lookup = {} def templater_selector(s=None, **kwargs): """I...
# -*- coding: utf-8 -*- from imutils.video import VideoStream from picamera import PiCamera, Color from imutils import paths import imutils import time import os import cv2 import pickle import numpy as np import pandas as pd import face_recognition import RPi.GPIO as GPIO from shutil import rmtree def test(): un...
# mmpdb - matched molecular pair database generation and analysis # # Copyright (c) 2015-2017, <NAME> Ltd. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (c) 2017-present, Facebook, Inc. # 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. An additional grant # of patent rights can be found in the PATENTS file ...
import xml.etree.ElementTree as ET import sqlite3 import os import re import io def create_connection(db_file): """ Create a database connection to the SQLite database specified by db_file :param db_file: database file :return: Connection object or None """ try: conn = sql...
from __future__ import absolute_import from __future__ import unicode_literals from __future__ import print_function from __future__ import division import torch import torch.nn as nn from torch.autograd import Variable from functools import reduce import operator count_ops = 0 count_params = 0 ignored_modules = []...
import unittest from unittest.mock import patch, call, Mock import numpy as np from pygwyfile._libgwyfile import ffi from pygwyfile.gwyfile import GwyfileErrorCMsg from pygwyfile.gwydatafield import GwyDataField class GwyDataField_init(unittest.TestCase): """Test constructor of GwyDataField class """ de...
#!/usr/bin/env python3 from typing import NamedTuple import urllib.request as request import shutil import os URL = "https://github.com/Legacy-Fabric/Legacy-Intermediaries/raw/master/mappings/{}.tiny" class Intermediaries(NamedTuple): classes: dict # { offical name, class } fields: dict # { field, signatur...
""" Python package for convex optimization CVXOPT is a free software package for convex optimization based on the Python programming language. It can be used with the interactive Python interpreter, on the command line by executing Python scripts, or integrated in other software via Python extension modules. Its m...
import hashlib import io import json import os from hmac import compare_digest from ..helpers import IntegrityError from ..logger import create_logger from ..checksums import StreamingXXH64 logger = create_logger() class FileLikeWrapper: def __enter__(self): self.fd.__enter__() return self ...
#!/usr/bin/python # encoding: utf-8 import torch import params import numpy as np import torch.nn as nn from torch.autograd import Variable import collections from torch.utils.data.sampler import SubsetRandomSampler class strLabelConverter(object): """Convert between str and label. NOTE: Insert `bla...
from functools import partial, cached_property from types import MappingProxyType as mappingproxy from .core_functions import arity, declaration, to_callable, make_xor, signature from .fn_placeholders import compile_ast, call_node from .signature import Signature from .utils import mixed_accessor, lazy_string from .._...
"""Procedural-Generated Dungeon RPG mygame.py this is a prototype for a procedural-generated dungeon RPG has bare-minimum graphics created by rtgher 26/11/2014-> """ __version__=0.2 __status__="Prototype" __author__="<EMAIL>" #License """ The software itself is a free product. Anyone can download and inst...
from typing import Dict, List import aiohttp from aiohttp import client_exceptions import asyncio import time import datetime """ Usage: Use this program from another file using the following: - import async_web_requests - results = async_web_requests.main_loop(urls_list, output=bool) ...
"""SMAL Renderer object responsible for visualising a SMAL sequence""" from data.data_loader import extract_npz, DataSources from vis.mesh_viewer import BBox import torch from smal_fitter.smbld_model.smbld_mesh import SMBLDMesh from scipy import signal import numpy as np from matplotlib import pyplot as plt from matpl...
# -*- coding: utf-8 -*- """ Created on Sat Dec 1 12:46:07 2018 @author: mhturner """ import numpy as np import matplotlib.colors as mcolors import h5py import os import datetime import inspect import yaml from matplotlib.patches import Rectangle, Circle, Arrow import matplotlib.pyplot as plt def addStimulusDrawing(...
import matplotlib.pyplot as plt import math """ A_star 公式:f(n) = g(n)+h(n) g(n)表示当前点到起点的距离,h(n)表示当前点到目标点的距离 维护两个列表,open列表表示待计算的点,close的表示已经搜索的点 算法过程: 1.将起始点放入open列表 2.重复以下步骤: i.在open_list 查找F最小的点,并把查找点作为当前点 ii.把当前点从open_list 删除,添加到close_list iii. 对当前点相邻的点执行以下步骤: 1. 如果该相邻点不可通行或已经在close_list,则跳过,继续下一节点 2. 如果该相...
from owlready2 import * onto = get_ontology("file://D:/INZ/Guns4.owl").load() ########################### value_from_onclick = 'Sex' ########################### # potrzebne do wyboru ktorej funkcji uzyc dla slowa (zaleznie czy jest klasa czy indywiduum + zmienne globalne: classes = list(onto.classes()) def cut_the_c...
import re import os import time import argparse import tweepy import datasets import logging import stanza import random from word_generator import WordGenerator logger = logging.getLogger(__name__) MAX_TWEET_LENGTH = 250 def _inverse_definition_str(word_with_definition): return f"{word_with_definition.word}: {...
# Source: https://github.com/alejandrods/Style-Transfer-PyTorch-Keras/blob/master/Style_Transfer_Pytorch.ipynb from PIL import Image import matplotlib.pyplot as plt import numpy as np import os import argparse import torch import torch.optim as optim from torchvision import transforms, models from torchvision.utils i...
#!/usr/bin/python3 import sys try: from PySide6.QtCore import * from PySide6.QtGui import * except Exception: try: from PySide2.QtCore import * from PySide2.QtGui import * except Exception: from PySide.QtCore import * from PySide.QtGui import * from Ui_ImageWindow import * import os import shutil import fi...
###################################################################### # Software License Agreement (BSD License) # # Copyright (c) 2013, Rice University # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions...
# Copyright 2020 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import functools import logging import pprint import pytest import pytest_bdd import random import uuid from chromeperf.engine import evaluator as evaluator...
from datetime import datetime from lxml import etree import numpy as np import cv2 import torch class AverageMeter(object): def __init__(self): self.initialized = False self.val = None self.avg = None self.sum = None self.count = None def initialize(self, val, weight): ...
""" @author: <NAME> @contact: yuhao.cheng[at]outlook.com """ import os import pickle import cv2 import torch import mmcv import numpy as np from collections import OrderedDict from torch.utils.data import DataLoader from pyanomaly.datatools.evaluate.utils import psnr_error, oc_score from pyanomaly.core.ut...
"""Converts TREC-CAR queries and corpus into TFRecord that will be consumed by BERT. The main necessary inputs are: - Paragraph Corpus (CBOR file) - Pairs of Query-Relevant Paragraph (called qrels in TREC's nomenclature) - Pairs of Query-Candidate Paragraph (called run in TREC's nomenclature) The outputs are 3 TFRec...
# -*- coding:utf-8 -*- ''' technically a bloom filter can be used to deterministically evaluate iterations of eh statistical probabilities available to subsets of pairs within a O(log n) - O(n) ''' # import matplotlib.pyplot as plt import btcelib #import numpy as np #import json import math import operator from functo...
import asyncio import shlex import datetime from asgiref.sync import sync_to_async from . import models import logging logger = logging.getLogger(__name__) class LocalAgent: """ A simple implementation of the agent, that runs on the local server DO NO USE IN PRODUCTION is only for backend api definiti...
# Copyright (c) 2020, NVIDIA CORPORATION. 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 appli...
import ujson import caesar_external as ce import sqlite3 class Classification(object): def __init__(self, id, subject_id, annotation): self.id = int(id) self.subject_id = int(subject_id) self.label = self.parse(annotation) def parse(self, annotation): ...
"""Metrics to assess performance on cost-sensitive classification tasks given class prediction and cost-matrix Functions named as ``*_score`` return a scalar value to maximize: the higher the better Function named as ``*_error`` or ``*_loss`` return a scalar value to minimize: the lower the better """ # Authors: <NA...
from functools import partial from keras.layers import Input, LeakyReLU, Add, UpSampling3D, Activation, SpatialDropout3D, Conv3D, Dense, Subtract, \ GlobalAveragePooling3D from keras.layers.core import Lambda from keras.engine import Model from keras.optimizers import Adam, SGD from keras.losses import binary_cros...
# import pygame module in this program import pygame import time from kartingpros import screen, track, mainmenu, settings, car, loadimage from kartingpros.loadimage import _load_image,_load_sound,_load_font from kartingpros.car import Car from pygame.locals import * from pygame import mixer import numpy as np import s...
# -*- coding: utf-8 -*- __author__ = "<NAME>, <NAME>, <NAME>" __copyright__ = "Copyright 2019, The Information Security and Privacy Lab at the University of Lausanne (https://www.unil.ch/isplab/)" __credits__ = ["<NAME>", "<NAME>", "<NAME>", "<NAME>"] __version__ = "1" __license__ = "MIT" __maintainer__...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow.compat.v1 as tf tf.disable_v2_behavior() import tf_slim as slim def gan_arg_scope(is_training = True, weight_decay=0.0005): """Defines the VAE arg scope. Returns: An arg_scope. "...
""" Script to compute features used for posture and activity recognition in multilocation paper. features: "MEAN" 'STD' 'MAX' 'DOM_FREQ' 'DOM_FREQ_POWER_RATIO' 'HIGHEND_FREQ_POWER_RATIO' 'RANGE' 'ACTIVE_SAMPLE_PERC' 'NUMBER_OF_ACTIVATIONS' 'ACTIVATION_INTERVAL_VAR' Usage: ...
# The storm identifier that labels individual storms with unique label at each time step of precipitation data. # The almost-connected labeling algorithm in the code, which is the method "identify" is from # Storm Tracking and Evaluation Protocol (https://github.com/DUTLiuKevin/STEP, author: <NAME>) and paper: # <NAME>...
import sre_constants import sre_parse from typing import Any, Callable, List, Optional, Tuple from data.graph import bloom_mask, bloom_node _LOWER_ALPHA = 'abcdefghijklmnopqrstuvwxyz' _UPPER_ALPHA = _LOWER_ALPHA.upper() _TRANSFORMER_CACHE = {} def transform(expression: str) -> sre_parse.SubPattern: parsed = sre_p...
#주가 import discord from discord.ext import commands from discord.ext.commands import Context from discord_slash import SlashContext, cog_ext from discord_slash.model import SlashCommandOptionType as OptionType from discord_slash.utils.manage_commands import create_option from discord.ext.commands.errors import Missing...
# -*- coding: utf-8 -*- """Utility functions for mirdata Attributes: NoteData (namedtuple): `intervals`, `notes`, `confidence` F0Data (namedtuple): `times`, `frequencies`, `confidence` LyricData (namedtuple): `start_times`, `end_times`, `lyrics`, `pronounciations` SectionData (namedtuple): `start_t...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import with_statement, absolute_import, print_function import sys VER = sys.version_info.major if VER < 3: range = xrange import struct from ctypes import Structure, byref, sizeof, POINTER, windll, c_char from ctypes.wintypes import DWORD, LONG, ULONG, ...
import time import os import numpy as np import pytest import asynckeepa import datetime import asyncio is_matplotlib = True try: import matplotlib except ModuleNotFoundError: is_matplotlib = False # slow down number of offers for testing asynckeepa.interface.REQLIM = 2 try: path = os.path.dirname(os....
from __future__ import division import sys if sys.version_info > (3, 0): from functools import reduce from functools import lru_cache from collections import Sequence from magma import * from .LUT import LUT, LUT1, LUT2, LUT3, LUT4, A0, A1, A2, A3, ZERO, ONE from .ROM import ROMN from .cascade import FlatHalfC...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright [2010] [Anso Labs, 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...
# -*- coding: utf-8 -*- import functions.add_path import numpy as np import pandas as pd #import matplotlib.pyplot as plt #from plotnine import * #from plotnine.data import * #import functions.et_make_df as make_df #import functions.et_helper as helper #import functions.et_plotting as etplot #import functions.det...
# -*- coding: utf-8 -*- from django.test import TestCase, RequestFactory from django.contrib.auth.models import Group, Permission from django.contrib.sites.models import Site from django.core.files.uploadedfile import SimpleUploadedFile # weird stuff for the models test from django.conf import settings from django.cor...
import ptypes, pecoff from . import umtypes from .datatypes import * class LDR_DATA_TABLE_ENTRY(pstruct.type, versioned): class SectionPointerUnion(dynamic.union): class SectionPointer(pstruct.type): _fields_ = [(PVOID, 'SectionPointer'), (ULONG, 'CheckSum')] _fields_ = [ (...
#!/usr/bin/env python3 import logging import random import sys import pygame from gamelib import logging as gamelog from gamelib import util as gameutil from gamelib import Display, colors, fonts from gamelib.constants import (DOWN, KEY_DOWN, KEY_LEFT, KEY_RIGHT, KEY_UP, LEFT, RIGHT, UP...
import os import sys import gzip import json import datetime from io import TextIOWrapper from typing import Tuple from backports.datetime_fromisoformat import MonkeyPatch from collections import OrderedDict # Polyfiller for retrocompatibiliy with Python3.5 MonkeyPatch.patch_fromisoformat() class Parameters: """ ...
from argparse import ArgumentParser import os import json import numpy as np from google.protobuf import json_format from calamari_ocr.utils import glob_all, split_all_ext from calamari_ocr.ocr import Evaluator from calamari_ocr.ocr.datasets import create_dataset, DataSetType, DataSetMode from calamari_ocr.proto impo...
import argparse import os import pickle from pathlib import Path import numpy as np import torch import torch.backends.cudnn as cudnn import torch.nn as nn import torch.optim as optim from torch.utils import data from torch.utils.data import dataloader from tqdm import trange from diagan.datasets.generated import ( ...
####################################################################################### # unet_conv_cifar10rgb_mc.py # Convlutional Layer UNET with RGB Cifar10 dataset and Class with Keras Model approach ####################################################################################### #import matplotlib #matplotl...
#!/usr/bin/env python3 # The MIT License (MIT) # Copyright (c) 2021 <NAME> & <NAME>. # # 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 r...
import torch.nn as nn import torchvision.transforms as transforms import math from .binarized_modules import BinarizeLinear,BinarizeConv2d __all__ = ['resnet_binary'] def Binaryconv3x3(in_planes, out_planes, stride=1): "3x3 convolution with padding" return BinarizeConv2d(in_planes, out_planes, kernel_size=3,...
# -*- coding: utf-8 -*- # import re from .version import __version__ from functools import wraps from collections import namedtuple def line_info_at(stream, index): if index > len(stream): raise ValueError("invalid index") line = stream.count("\n", 0, index) last_nl = stream.rfind("\n", 0, index) ...
################################################################ # Implemented by <NAME> (<EMAIL>) # # # # PyTorch-compatible implmentation of Integrated Gradients # # proposed in "Axiomatic attribution for deep neuron networks" # # (https://arxiv.org/a...
import frappe from frappe import _ def set_supplier_details(si, method): for si_item in si.items: item = frappe.get_doc("Item", si_item.item_code) for item_default in item.item_defaults: if item_default.company == si.company and item_default.default_supplier: supplier_name = frappe.get_value("Supplier", i...
import numpy as np import theano import theano.tensor as T from scipy.optimize import fmin_l_bfgs_b from scipy import misc import skimage from skimage.transform import resize from skimage.io import imread from theano_model import vgg19_model, preliminary_model VGG19 = vgg19_model.VGG19 class NeuralStyleTransfer(objec...
# -*- coding: utf-8 -*- """ Created on Jan 5 09:20:37 2022 Compiles NDFD data into SQLite DB @author: buriona,tclarkin """ import sys from pathlib import Path import pandas as pd import sqlalchemy as sql import sqlite3 import zipfile from zipfile import ZipFile # Load directories and defaults this_dir = Path(__fil...
#!/usr/bin/python # A simple database class to handle tagging files. #TODO: return values? #TODO: a fix for os.path.commonprefix import sqlite3 import os import datetime import tarfile import csv import logging logger = logging.getLogger(__name__) SEARCH_EXCLUSIVE = 'e' SEARCH_INCLUSIVE = 'i' # CSV dialect used for...
import os import logging import time from .dataloader import EvalDataset, TrainDataset, NewBidirectionalOneShotIterator from .dataloader import get_dataset from .utils import get_compatible_batch_size, save_model, CommonArgParser backend = os.environ.get('DGLBACKEND', 'pytorch') assert backend.lower() == 'pytorch' i...
import asyncio import signal import sys from datetime import datetime, timedelta import shelve import os import random from aiogram import Bot, Dispatcher, types BOT_TOKEN = os.getenv('TOKEN') db = shelve.open(os.path.join('db', 'db'), writeback=True) tasks_set = set(db['tasks'].keys()) bot: Bot solving...
import torch import torch.nn as nn import torch.nn.functional as F from torchsummary import summary from torchvision import models import math import argparse import os import matplotlib.image as mpimg import numpy as np class BaseCNN(nn.Module): def __init__(self): super(BaseCNN, self).__init__() ...