text
stringlengths
3.07k
22.1k
import json import os import re import sys import time import unittest import click import vmraid import requests from .test_runner import (SLOW_TEST_THRESHOLD, make_test_records, set_test_email_config) click_ctx = click.get_current_context(True) if click_ctx: click_ctx.color = True class ParallelTestRunner(): def...
import imaplib import re import email import base64 import quopri import sys import time from datetime import datetime from email.header import decode_header from core.imbox.utils import str_encode, str_decode import operator as op import configparser import os from email import header # 获取配置 base_dir = os.path.dirnam...
import numpy as np from scipy.sparse import csr_matrix from .ldpcalgebra import* __all__ = ['BinaryProduct', 'InCode', 'BinaryRank','RegularH','CodingMatrix','CodingMatrix_systematic','HtG'] def RegularH(n,d_v,d_c): """ ------------------------------------------------------------------------------ Builds a...
import torch from torch import nn from .parts import * __all__ = ["VGGUNet", "NestedUNet"] class VGGUNet(nn.Module): def __init__(self, num_classes, input_channels=3, leak_p=0.1, factor=1, **kwargs): super().__init__() nb_filter = [ 32 // factor, 64 // factor, ...
import functools import logging import traceback import hashlib import orjson from cached_property import cached_property from nlabel.io.json.group import split_data from nlabel.nlp.nlp import NLP as CoreNLP, Text as CoreText from nlabel.io.carenero.schema import Tagger, Tag, TagInstances, Text, Vector, Vectors, Resu...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' cli.arguments: default arguments with the ability to override them ''' import re from datetime import timedelta from cli.utils.dictionary import merge from cli.config import CFG CALLS_STYLE = [ 'simple', 'detail', ] DETAIL = [ 'summary', 'detailed' ...
# This file is part of h5py, a Python interface to the HDF5 library. # # http://www.h5py.org # # Copyright 2008-2013 <NAME> and contributors # # License: Standard 3-clause BSD; see "license.txt" for full license terms # and contributor agreement. """ Tests the h5py.File object. """ from __future__ impo...
# -*- coding: utf-8 -*- # # Copyright 2018 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requir...
import os.path import tensorflow as tf import helper import warnings from distutils.version import LooseVersion import project_tests as tests import scipy.misc import re from glob import glob import numpy as np from sklearn.utils import shuffle # Check TensorFlow Version assert LooseVersion(tf.__version__) >= LooseV...
# %% import os import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from IPython.core.interactiveshell import InteractiveShell from sklearn.base import BaseEstimator from sklearn.metrics import make_scorer from sklearn.model_selection import KFold, cross_val_score from sklearn....
from pathlib import Path import pandas as pd from fuzzywuzzy import fuzz from fuzzywuzzy import process import time import re import numpy as np pd.set_option('display.max_columns', None) pd.set_option('display.max_rows', None) def main(): # start time of function start_time = time.time() # project direc...
import datetime, pytz import math from ..utils.format import to_sex from .altaz import get_nutation, get_obliquity #### DATETIME METHODS def get_utdt(utdt=None): """ Take a non-TZ aware datetime and return an aware one. """ if not utdt: utdt = datetime.datetime.utcnow() return utdt.replace(...
import torch import torch.nn as nn class conv_block(nn.Module): def __init__(self, inplanes, outplanes, kernel_size=3, stride=1, upsample=False): super(conv_block, self).__init__() self.upsample = upsample if (upsample): self.conv = nn.Conv2d(inplanes, outplanes, kernel...
import tkinter as tk import tkinter.ttk as ttk import tkinter.messagebox as msb from tkinter import * import sqlite3 # --------- Frame ------------- root = Tk() root.title(" Estacio boletim da area python ") width = 900 height = 600 sc_width = root.winfo_screenwidth() sc_height = root.winfo_screenheight() ...
#!/usr/bin/python from __future__ import print_function import itertools import numpy as np from scipy.stats import f_oneway, gamma from scipy.optimize import curve_fit from . import parsers from . import convolution_dp from . import hyperparameters def getPosteriors(quantRowsOrig, params): quantRows, quantMatri...
import dataclasses from abc import abstractmethod, ABCMeta from typing import cast, Iterator, Tuple, Optional, Dict from mypy.nodes import ClassDef, AssignmentStmt, CallExpr, MemberExpr, StrExpr, NameExpr, MDEF, TypeInfo, Var, SymbolTableNode, \ Lvalue, Expression, MypyFile, Context from mypy.plugin import ClassDe...
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Copyright 2014 California Institute of Technology. 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 th...
''' Analysis script II: I: make initial non-discretionary exclusions to data (done) II: prepare samples for train and test (done) III: structure files directory of images () IV: make vector data inputs (done) ''' # -- # dependancies from data_io_function_library import * # -- ...
""" Code to visualize samples and latent walks for VAE. Note: this code is for research i.e. quick experimentation; it has minimal comments for now, but if we see further interest from the community -- we will add further comments, unify the style, improve efficiency and add unittests. @contactrika """ import nump...
"""Test errors.py.""" import collections import csv import io import os import textwrap from unittest import mock from pytype import errors from pytype import file_utils from pytype import state as frame_state from pytype.tests import test_utils import unittest _TEST_ERROR = "test-error" _MESSAGE = "an error messag...
# Author: <NAME> import os import time import requests import pandas as pd import geopandas as gpd import numpy as np import subprocess import sqlalchemy import datetime import multiprocessing as mp from datetime import datetime from io import StringIO pd.set_option('display.max_columns', None) # DEBUG # Get DB conn...
# <NAME> # 12-16-2020 import logging import discord import discord.ext.commands as commands import bot.extensions as ext from bot.messaging.events import Events from bot.bot_secrets import BotSecrets from bot.consts import Colors import aiohttp import asyncio import re import datetime as dt log = logging.getLogger...
# -*- coding: utf-8 -*- # # Copyright (c) 2010 by xt <<EMAIL>> # # This program 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; either version 3 of the License, or # (at your option) any later version. # # Thi...
import os from datetime import datetime import pandas as pd import numpy as np from scipy import stats from tqdm import tqdm from sklearn.preprocessing import StandardScaler, RobustScaler from sklearn.impute import SimpleImputer def epoch_timestamp(year, month=1, day=1,hour=1): return datetime(year=year, month=...
""" 规范sql存储的数据,转换适用于from_blaze格式,生成DataSet对象 如果数据量大,以bcolz格式(文件)存储;否则直接转换为DataFramde(内存中) 转换后的数据格式为: asof_date timestamp sid int_value str_value date_value float_value 2014-01-06 2014-01-07 1 0 A 2001-01-01 2000.30 2014-01-07 2014-01-08 333 1 B 2010-...
import bpy import colorsys import csv import io import logging import math import mathutils import operator import random import svgwrite logger = logging.getLogger("wrapping_paper_tools") class SvgExporter(bpy.types.Operator): bl_idname = "wpt.exporter" bl_label = "Export Wrapping Paper" location_matrix ...
import numpy as np import matplotlib.pyplot as plt # model parameters class ModelParams: def __init__(self): self.D = 0.5 # base fee decay factor self.T = 1 # weighting for token price in trove issuance self.F = 0.3 # weighting for momentum in trove issuance self.lookback = 5 # Lo...
from time import sleep_ms from mcs.ili9341 import color565 class EditText: def __init__(self, text, x, y, display, width=100, focus=False, padding=4, color=0xffff, background=color565(0x52, 0x52, 0x52), enabled=True, action=None): self.text = text self.x = x self.y = y self.display ...
from generallibrary.object import * from generallibrary.objinfo.objinfo import ObjInfo, hook, call_base_hooks from generallibrary.functions import initBases, AutoInitBases import unittest # hook couldn't get foo's parent if defined inside method class hook_A: def foo(self): return 1 class hook_B(hook_A)...
# Copyright 2019,2020,2021 Sony Corporation. # Copyright 2021 Sony Group Corporation. # # 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 # # Un...
import os import sys from itertools import product import numpy as np import matplotlib.pyplot as plt from tqdm import tqdm here = os.path.abspath(os.path.dirname(__file__)) sys.path.insert(0, here + '/../') from experiments import util as exp_util # public def get_results(args, exp_dir, logger=None, progress_bar=T...
import abc from .item import Item from .observation import ( ProbitWinObservation, ProbitTieObservation, LogitWinObservation, LogitTieObservation, GaussianObservation, PoissonObservation, SkellamObservation) class Model(metaclass=abc.ABCMeta): def __init__(self): ...
from dataclasses import dataclass from IPython.display import display import datetime import io import ipywidgets as widgets import matplotlib.pyplot as plt import pandas as pd import numpy as np import warnings from marketpsych import sftp ASSET_CLASSES = "CMPNY CMPNY_AMER CMPNY_APAC CMPNY_EMEA CMPNY_ESG CMPNY_GRP C...
import numpy as np import tensorflow as tf from t3f import ops from t3f import shapes from t3f import decompositions from t3f import initializers class _DecompositionsTest(): def testTTTensor(self): shape = (2, 1, 4, 3) np.random.seed(1) tens = np.random.rand(*shape).astype(self.dtype.as_numpy_dtype) ...
r""" .. _plugins_hybrid: Plugins and Hybrid computation ============================== .. meta:: :property="og:description": This tutorial introduces the notion of hybrid computation by combining several PennyLane device backends to train an algorithm containing both photonic and qubit devices. ...
import pickle as pickle import re import wx import wx.lib.mixins.listctrl as listmix from pathlib import Path from pyfuzzyrenamer import masks, utils from pyfuzzyrenamer.config import get_config class MaskListCtrlDropTarget(wx.DropTarget): def __init__(self, source): wx.DropTarget.__init__(self) ...
import threading import time import logging logger = logging.getLogger('KingPhisher.Plugins.SFTPClient.tasks') class TaskQueue(object): """ Task queue used for transfer tasks that handles thread and task management in a way to prevent errors. """ def __init__(self): self.mutex = threading.RLock() self.not_em...
import os from pytest import raises from matplotlib import pyplot as plt from matplotlib.testing.compare import compare_images from discopy import rigid, messages from discopy.rigid import Id, Cup, Cap, Ty, Box from discopy.grammar import * def test_Word(): with raises(TypeError): Word(0, Ty('n')) wi...
import numpy as np import argparse import pprint import os import copy """ T.J.Blätte 2018 """ """ To extract molecular barcodes sequenced as part of the main reads into separate FASTQ files. Args: fastq1: FASTQ file of forward reads (REQUIRED) fastq2: FASTQ file of reverse reads (REQUIRED) sampleID: sam...
import numpy as np import pandas as pd import os throwThreshold=0.5 gradient=0 delThrow=False delThrowOrOneCatch =False delOneLength = False delTwoLength = False filePath ="../dataset/resultsTEST" list=[] def ReadFile(filePath): files = os.listdir(filePath) for file in files: list1 = [] file=o...
''' This file provides helper functions used to normalize the arguments that go into search queries. Mainly converting the strings given by the user into proper data types. ''' from . import constants from . import exceptions from . import helpers from . import objects from voussoirkit import expressionmatch from vous...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Mar 26 14:11:12 2022 @author: rantanem """ import numpy as np import pandas as pd import xarray as xr import matplotlib.pyplot as plt from scipy import stats import ghcn_routines as ghcn import math def rounddown(x): return int(math.floor(x / 100...
import pytest import numpy as np import pandas as pd from unittest import mock from sklearn.datasets import fetch_20newsgroups, make_blobs from bertopic import BERTopic newsgroup_docs = fetch_20newsgroups(subset='all')['data'][:1000] def create_embeddings(docs): """ For mocking the _extract_embeddings function ...
#!/usr/bin/env vpython3 # Copyright 2020 The Goma Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Simple test scripts for sanity check. The script is intended to be used with the production Goma RBE server. """ import argparse impo...
# %% # To add a new cell, type '# %%' # To add a new markdown cell, type '# %% [markdown]' # %% from IPython import get_ipython # %% # Python ≥3.5 is required import sys assert sys.version_info >= (3, 5) # Scikit-Learn ≥0.20 is required import sklearn assert sklearn.__version__ >= "0.20" # Common imports import num...
import sys import os import subprocess from pathlib import Path import configparser from hashlib import sha1 import json import warnings from datetime import datetime import pytz import time def read_cache_json(cache_key): home_path = str(Path.home()) cache_json_path = os.path.join(home_path, '.aws', 'cli', '...
import numpy as np import random import bisect import environment import pickle from collections import deque from keras.models import Sequential from keras.layers import Dense, Dropout from keras.optimizers import Adam from keras.regularizers import l2 from keras import backend as K from keras.models import load_mode...
import numpy as np from collections import Counter import torch import torch.nn.functional as F from tnt.utils.logging import logger, beautify_info from torch.utils.data import Sampler from torch.utils.data import Dataset, DataLoader from munch import munchify from tnt.data.transform_image import TransformImage from tn...
#!/opt/datadog-agent/embedded/bin/python # Unless explicitly stated otherwise all files in this repository are licensed # under the Apache License Version 2.0. # This product includes software developed at Datadog (https://www.datadoghq.com/). # Copyright 2018 Datadog, Inc. import os import signal import sys import t...
import json import subprocess from dataclasses import dataclass, asdict, field from pathlib import Path, WindowsPath, PosixPath from typing import Optional, Any, Callable, Tuple, Dict import docker import numpy as np import requests from docker.errors import DockerException from docker.models.containers import Contain...
''' ------------------------------------------------------------------------ Last updated 9/24/2014 Functions for created the matrix of ability levels, e. This py-file calls the following other file(s): data/e_vec_data/jan2014.asc data/e_vec_data/feb2014.asc data/e_vec_data/march20...
#!/usr/bin/python2 import re import os import numpy as np import pcbnew import matplotlib.pyplot as plt import matplotlib.patches; from matplotlib.patches import Rectangle, Circle, Ellipse, FancyBboxPatch, Polygon def create_board_figure(pcb, bom_row, layer=pcbnew.F_Cu): qty, value, footpr, highlight_refs = bom_...
import matplotlib.pyplot as plt import numpy as np color1 = "dodgerblue" color2 = "orange" lw = 2.5 #linewidth ftsz = 16 #label fontsize def plot_util(timesteps, x_sol, u_sol,n_x): fig, axes = plt.subplots(nrows=3, ncols=4, figsize=(15,15)) fig.subplots_adjust(hspace=10) fig.suptitle('Nominal State and Input Tr...
""" Patch cqlengine, add async functions. """ from datetime import datetime, timedelta from warnings import warn import time import six from cassandra.cqlengine.query import ( DMLQuery, ModelQuerySet, check_applied, SimpleStatement, conn, ValidationError, EqualsOperator, BatchQuery, ) f...
import numpy as np import pandas as pd import plotly.graph_objects as go from igraph import Graph from textblob import TextBlob from datetime import datetime from .data import gather_data def make_df(url): # gather data for dataframe stuff = gather_data(url) # adjust columns and prepare for plot stuf...
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use ...
import BLS import numpy as np import matplotlib.pyplot as plt def test_fake_data(): test1 = BLS.fake_data(10,.1,0,20) test2 = BLS.fake_data() assert(len(test1[0])==len(test1[1])==len(test1[2])) assert(len(test2[0])==len(test2[1])==len(test2[2])) def test_open_mylcs(): tic1= 140801898; sector1=1 ...
# -*- coding: utf-8 -*- """ Created on Thu Sep 6 16:04:13 2018 @author: N.Chlis """ #if used on a non-GUI server ###### import matplotlib matplotlib.use('Agg') ################################### import numpy as np #import pandas as pd import matplotlib.pyplot as plt #import h5py from keras.models import Model from...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Sep 23 18:29:33 2018 FYI: This project was done using Python 3.6.* The Solution we are trying to solve can be found on the .pdf file @author: <NAME> """ # You first must download the modules/lybraries used below otherwise you will have compiler errors....
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
""" Copyright (C) 2019 NVIDIA Corporation. All rights reserved. Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode). """ import os import numpy as np import torch from PIL import Image from torch.utils import data from collections import defaultdict import math imp...
############################################################################## # # Copyright (c) 2005 Zope Foundation and Contributors. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS I...
from .mipow import MipowDevice from typing import Final import logging import random import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_RGBW_COLOR, A...
import os import os.path as op import shutil import re import tempfile import polib from . import pygettext from .util import modified_after, dedupe, ensure_folder, ensure_file from .build import print_and_do, ensure_empty_folder, copy LC_MESSAGES = 'LC_MESSAGES' # There isn't a 1-on-1 exact fit between .po languag...
from typing import List # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: # 61 Rotate list, Medium def rotateRight(self, head: ListNode, k: int) -> ListNode: if head is None: retu...
# -*- coding: utf-8 -*- # # SPDX-License-Identifier: Apache-2.0 # Copyright 2020 - 2022 Pionix GmbH and Contributors to EVerest # """ author: <EMAIL> FIXME (aw): Module documentation. """ from pathlib import Path import shutil import subprocess import re import json import jstyleson import jsonschema from uuid impor...
import omegaml as om import json # No need to specify in the setup file (NNtS) import dash # (NNtS) import dash_bootstrap_components as dbc # Specify in the setup file ? import dash_core_components as dcc # (NNtS) import dash_html_components as html # (NNtS) import numpy as np # (NNtS) import omegaml as om # (NNt...
from __future__ import print_function import numpy as np import torch import torch.nn.functional as F import time import os import pathlib import sys import SimpleITK as sitk import nibabel as nib import scipy.io import argparse cuda_idx = 0 from utils.tools import countParam, dice_coeff from utils.datasets import M...
#!/usr/bin/env python # coding:utf-8 from __future__ import print_function import math import numpy as np #import scipy.linalg import scipy.sparse import scipy.sparse.linalg import argparse import time def parse_args(): parser = argparse.ArgumentParser(description='Calculate the ground state of S=1/2 Heisenberg c...
#!/usr/bin/env python """ Binance quick market buy+limit sell script Author: Dawnflash Ensure .env is created (use .env.example as a template) Follow the prompts and good luck. """ import asyncio from threading import Thread, Lock, Condition import aiohttp from server import HTTPCoinAcceptor from util import Invalid...
import copy from headers import * from paddle import * from input import * from board import * from ball import * from powerUp import * from laser import * import globalVar from globalVar import TOP, BOTTOM, LEFT, LIVES, SCORE, WIDTH, HT, SHOOT_COOLDOWN, obj_bricks, paddle, power_ups, balls, level, lasers, last_shoot i...
import numpy as np from arc.actions import Actions, chebyshev_vector from arc.object import Object def test_translations(): """Test each action that translates an Object.""" pt1 = Object(1, 1, 1) pt2 = Actions.Horizontal().act(pt1, 1) assert pt2 == Object(1, 2, 1) assert pt2 != pt1 # 'Konami'...
# coding: UTF-8 import numpy as np import torch import time from utils import build_iterator, get_time_dif from importlib import import_module from tqdm import tqdm from generate_data import cut_para_many_times PAD, CLS = '[PAD]', '[CLS]' # padding符号, bert中综合信息符号 min_length = 64 label2class = { "财经" : "高风险", ...
# encoding: utf-8 import math import torch from torch import nn import torch.nn.functional as F def conv3x3(in_planes, out_planes, stride=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False) class BasicBlo...
import argparse import itertools from pathlib import Path import torch from torch import optim from torch.utils.data.dataloader import DataLoader from typing import Tuple from models.tacotron import Tacotron from trainer.taco_trainer import TacoTrainer from utils import hparams as hp from utils.checkpoints import res...
import numpy as np import kabuki import pymc as pm import os.path from copy import deepcopy import matplotlib.pyplot as plt def sort_dict(d): from operator import itemgetter return sorted(iter(d.items()), key=itemgetter(1)) def _model_type_to_class(model_type): """Takes either a (inherited) class of Hie...
# ©EsterHlav # July 27, 2017 import numpy as np import gzip, numpy import math import _pickle as Pickle import matplotlib import PIL from PIL import Image, ImageOps, ImageFilter import scipy from scipy import ndimage def load_MNIST_vector(): # Load the dataset, url: http://yann.lecun.com/exdb/mnist/ f = gzip....
import datetime import time import re import random import os from copy import deepcopy import json from flask import Flask, render_template, url_for, request, redirect from flask.json import jsonify import pytz import dateutil.parser app = Flask(__name__) def utcnow(): return datetime.datetime.utcnow().replace(...
# Copyright 2017 Natural Language Processing Group, Nanjing University, <EMAIL>. # # 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...
""" Copyright (c) <NAME> All rights reserved. MIT License 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, merge,...
""" Copyright 2019 Samsung SDS 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 ...
import copy import logging import os from typing import List import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from yarr.agents.agent import Agent, Summary, ActResult, \ ScalarSummary, HistogramSummary from arm import utils from arm.utils import stack_on_channel NAME = 'TD3Age...
#!/usr/bin/env python3 """ Created on 2021-11-27 09:52 @author: johannes """ import os from pathlib import Path import yaml import sqlite3 import pandas as pd DAYS_MAPPER = { 'day': 1, 'days3': 3, 'week': 7, 'month': 30, 'quartile': 90, 'halfyear': 180, 'fullyear': 365, } def get_db_co...
#!/usr/bin/env python3 import logging import json import pprint as pp import time from urllib.parse import urlparse import click import redis from cathpy.core import tasks, ssap, version #import click_log # click_log.basic_config(LOG) logging.basicConfig( level='INFO', format='%(asctime)s %(levelname)7s | %(me...
# Copyright (c) <NAME> import datetime import getpass from log import log import cmdline import pssubs import syms import format import voice import parse_0 import common import constants args = cmdline.options() cfmt = format.Format() info = voice.Field() class Index: def __init__(self): self.make_ind...
import argparse import asyncio from collections import deque import sys import math import base64 import os import traceback import hashlib import aiohttp import aioprocessing import logging import locale try: locale.setlocale(locale.LC_ALL, 'en_US') except: pass from OpenSSL import crypto import certlib D...
import numpy as np import random import torch class DataSet(object): def __len__(self): raise NotImplementedError def __getitem__(self, index): raise NotImplementedError class MyDataSet(DataSet): def __init__(self, insts, transform=None): self.insts = insts self.transfor...
import os import uuid import copy import getpass import logging import collections from Qt import QtCore, QtGui from avalon.vendor import qtawesome from avalon import api, lib as avalon_lib from . import lib from .constants import ( ACTION_ROLE, GROUP_ROLE, ACTION_ID_ROLE ) from .actions import Applicati...
# <code># -- coding:UTF-8 --<code> # # 把srt字幕处理成无时间的txt # path = "./assets/files/jojo.txt" # newFile = open("./assets/files/newFile.txt", 'w') # with open(path,'r',encoding='utf-8') as fc: # for line in fc.readlines()[2::4]: # newFile.write(line) # newFile.close() # # 读取文件名中的信息并重名命 # import o...
from collections import namedtuple import datetime import itertools import logging import math import os import re import shutil import typing from bankline_parser.data_services import parse from bankline_parser.data_services.enums import TransactionCode from mtp_common.bank_accounts import ( is_correspondence_acc...
# -*- coding: utf-8 -*- from __future__ import absolute_import import re import ast import sys from copy import deepcopy from functools import partial PY3 = sys.version_info[0] == 3 if PY3: fmt_types = str, bytes else: fmt_types = basestring, unicode # noqa: F821 class Fmt(object): def __init__(self...
import json from typing import List class PatchingError(Exception): pass class MetadataException(Exception): pass class TimePeriod: start: int stop: int def __init__(self, start: int, stop: int): self.start = start self.stop = stop def to_dict(self) -> dict: if se...
import os # os.environ["CUDA_VISIBLE_DEVICES"] = "0" import cv2 import numpy as np import torch from torch.autograd import Variable import glob import json from PIL import Image as PILImage import importlib from torchvision.transforms import functional as F import pickle from argparse import ArgumentParser from et...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Runs MultiNet on a whole bunch of input images. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import json import logging import os import sys # configure logging if 'TV_IS_DEV' in os.environ and os....
# 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. """Recipe for engine shards. web_engine.py will call these shards. It will build the Flutter Web Engine, and will archive it to the isolate server. ...
import urllib import functools import pprint import typing as T import requests from pyrsistent import pmap from pymaybe import Nothing from .toolz import ( pipe, curry, partial, concatv, compose, map, filter, merge, maybe_pipe, vmap, maybe_first, noop, is_dict, vcall, ) from . import logging log = logging.n...
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program 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; either version 2 # of the License, or (at your option) any later version. # # This program is distrib...
# HTTP protocol import re, mimetools, cgi, select, cStringIO, tempfile, logging as L from httplib import responses as StatusCodeMap import striga.core.exception, striga.core.context from striga.core.variables import MultiDict from ._stpro_httpcookie import CookieJar ### #TODO: Based on security settings send only par...
#! /usr/bin/env morseexec """ Basic MORSE simulation scene for <sim> environment Feel free to edit this template as you like! """ from morse.builder import * import pytoml as toml import os # control if a file exists def findFileInPath(filename, extension, paths): for path in paths: if os.path.exists(os...
import torch import torch.nn as nn import torch.nn.functional as F from collections import OrderedDict from models.base_model import BaseModel from sklearn.metrics import accuracy_score from utils.radam import RAdam def conv3x3(in_channels, out_channels, stride=1, groups=1, dilation=1): return nn.Conv2d( i...