text
stringlengths
3.07k
22.1k
from __future__ import annotations from typing import List from typing import NamedTuple from typing import Optional from typing import Tuple from pathlib import Path import json import uuid from random import randint class Entity: @staticmethod def eid() -> str: return uuid.uuid4().hex class See...
from briefmetrics import api from briefmetrics import test from briefmetrics import model from briefmetrics.lib.service import registry as service_registry from briefmetrics.lib.payment import registry as payment_registry from dateutil.relativedelta import relativedelta import mock import json import logging import da...
# SPDX-License-Identifier: Apache-2.0 import warnings from uuid import uuid4 from .proto import get_latest_tested_opset_version from .common._topology import convert_topology from .common.utils_sklearn import _process_options from ._parse import parse_sklearn_model # Invoke the registration of all our converters and ...
import asyncio import io import os import subprocess from datetime import datetime from PIL import Image from .. import command, module, util PNG_MAGIC = b"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a" class LengthMismatchError(Exception): pass class StickerModule(module.Module): name = "Sticker" async def on_l...
import torch import torch.nn as nn import os import numpy as np import random import json import jsonlines import csv import re import time import argparse import sys import sklearn import traceback from torch.utils import data from tqdm import tqdm from apex import amp from scipy.special import softmax sys.path.inse...
#!/usr/bin/env python """ Copyright 2019 <NAME> (Johns Hopkins University) Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """ import sys import os from jsonargparse import ( ArgumentParser, ActionConfigFile, ActionParser, namespace_to_dict, ) import time import logging import numpy as np ...
#!/usr/bin/env python import platform import glob import argparse import re import json import os import sys import tempfile import socket import subprocess if sys.version_info[0] >= 3: from urllib.request import urlopen from html.parser import HTMLParser from urllib.request import urlretrieve from http.clien...
import re, json, os, csv, time, codecs, HTMLParser from logger import * def identify_tech(data, file): matches = [] with open(file) as f: keywords = f.readlines() for sentence in data.lower().split("."): keyword_found = [] for keyword in keywords: if re.findall('\\b{}\\b'.format(re.escape(keyword.rstrip()...
import logging import argparse import ast import os import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import Dataset, DataLoader import cv2 import numpy as np import random import architectures_grayscale.grayscale as arch import sys import synthetic_heatmap.generators.char_string as g...
# -*- coding: utf-8 -*- """ Created on Wed Sep 21 12:48:20 2016 based on mne.io.read_raw_eeglab @author: behinger """ import os.path as op import numpy as np #from ..utils import (_read_segments_file, _find_channels,_synthesize_stim_channel) from mne.io.utils import (_read_segments_file, _find_channels,_synthesize_...
# Copyright 2019 <NAME>. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, softw...
import addnn import addnn.node import addnn.node.neural_network import click import csv import pickle import random import torch from addnn.cli import cli from addnn.profile.layer_profile import LayerProfile, get_layer_profiles from addnn.util.torchscript import read_model_from_preprocessed_script from timeit import ti...
#!/usr/bin/env python import sys import os import argparse import re import vcfpy import tempfile import csv import binascii def define_parser(): parser = argparse.ArgumentParser( 'vep-annotation-reporter', description = "A tool to create a tab-delimited (TSV) file of variants in a VCF and their "...
# Creates config file for webserver based on create_conf.yaml and data downloaded based on that file. from __future__ import print_function import os import sys import re import requests import yaml from collections import OrderedDict # Hack to make yaml print out somewhat in order class UnsortableList(list): d...
import os from utils.utils import quote from utils.miditool import convert_to_abs_notes, transpose_tone, restrict_instrument from utils.spectral import spectrum import numpy as np import math import matplotlib.pyplot as plt import torch import re from pydub import AudioSegment import traceback import imageio import mu...
import argparse, sys, os, psutil, subprocess, re, signal from PyQt5.QtWidgets import QApplication from PyQt5.QtCore import Qt, QTimer import pkg_resources import oskb from oskb import im linux = sys.platform.startswith("linux") if linux: import getpass from ewmh import EWMH, ewmh wm = EWMH() moved_w...
import typing from collections import OrderedDict from copy import deepcopy from itertools import chain, repeat import numpy as np import onnx from onnx import numpy_helper import dace from dace.frontend.python.parser import infer_symbols_from_shapes from dace.sdfg import SDFG, SDFGState from dace.dtypes import Acce...
# -*- coding: utf-8 -*- import numpy as np __author__ = "<NAME>" def euclidean_distance(x, y): return ed(x, y) def euclidean(x, y): return ed(x, y) def e_distance(x, y): return ed(x, y) def ed(x, y): # convert to numpy array x = np.array(x, copy=False) y = np.array(y, copy=False) # ...
import open3d as o3d from sys import argv, exit from PIL import Image import math import numpy as np import copy import cv2 import matplotlib.pyplot as plt from shapely.geometry import Point, Polygon def display(pcd, T=np.identity(4)): axis = o3d.geometry.TriangleMesh.create_coordinate_frame(size=1, origin=[0, 0, 0]...
import argparse import json import lyricsgenius import math import pandas as pd import re import requests from lyricsgenius.types import Song from local import * ALBUMS = [ '1989', '1989 (Deluxe)', "1989 (Taylor’s Version)", '2004-2005 Demo CD', 'Beautiful Eyes - EP', 'Cats: Highlights From the Motion Pict...
from logging import exception import os import jnius_config SSHELL_PATH = os.environ.get('SSHELL_PATH', '') jnius_config.add_classpath(os.path.join(SSHELL_PATH, 'lib', '*')) import jnius import io from .plotting_module import SibillaDataPlotter from .profiler_module import Profiler SimulationMonitor = jnius.autocl...
# This template is for cli configuration of the equipment with "candidate config" feature import re # import cidr_to_netmask '''The list of templates for pan ''' ######## vlan ########### ######## svi ########### ######## addresses ########### def create_address (eq_parameter, name, ipv4_prefix, parameters): # ...
import os import re import sys import glob import urllib2 import collections import colorama ######################## # # # Functional Tools # # # ######################## def partition(pred, iterable): """ split the results of an iterable based on a predicate """ ...
import importlib import itertools import os.path import pathlib import shutil from typing import Dict, Iterator, List, Optional, Sequence, Union import urllib.request import urllib.error from .env import gpg_key_id from .patch import Patch from .source import Source, GitSource, URLSource from .util import ( _PathT...
import torch from nff.utils.scatter import compute_grad import numpy as np import math from ase import units from torchmd.sovlers import odeint_adjoint, odeint from ase.geometry import wrap_positions ''' Here contains object for simulation and computing the equation of state ''' class Simulations(): """Si...
# Copyright (c) 2019-2020, NVIDIA 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 # # Unless required by applicable law or agreed...
"""Simple biomolecular structures. This module contains the simpler structure objects used in PDB2PQR and their associated methods. .. codeauthor:: <NAME> .. codeauthor:: <NAME> """ # from . import pdb from .config import BACKBONE class Chain: """Chain class The chain class contains information about each ...
import tensorflow as tf from model import KEYPOINTSUBNET, DETECTERSUBNET from reader import Reader from datetime import datetime import os import logging import json_convert import numpy as np import labels_generator import hyper_parameters import anchors_generator # from tensorflow.contrib.slim import nets train_mode...
import six from urllib.parse import urlparse from selenium.webdriver.common.by import By from selenium.common.exceptions import WebDriverException import selenium.webdriver.common.keys from selenium.webdriver.support.ui import Select, WebDriverWait from selenium.webdriver.support import expected_conditions as EC on_...
import torch from torch import nn, einsum import torch.nn.functional as F from einops import rearrange, repeat from einops.layers.torch import Rearrange from vit_pytorch.face_losses import CosFace, ArcFace, SFaceLoss, Softmax # helpers def exists(val): return val is not None def default(val, d): return va...
import datetime as dt import os import sys import time import tkinter as tk import webbrowser as browser from tkinter.filedialog import askopenfile, asksaveasfile, askopenfilename, asksaveasfilename from tkinter.messagebox import showerror as error import pyautogui as pag from PIL import ImageTk from pyscreeze import ...
# -*- coding: utf-8 -*- """ Created on Fri Jul 5 16:13:25 2019 @Title: FrontierLab exchange program - Metropolis-Hastings source code (for Neural Networks) @Author: <NAME> The structre all almost the same as the code for Bayesian Logistic Regression Just simply change the input, and apply tensorflow package for GPU ...
""" ===================================================== Prediction Intervals for Gradient Boosting Regression ===================================================== This example shows how quantile regression can be used to create prediction intervals. """ # %% # Generate some data for a synthetic regression problem...
from abc import abstractmethod from typing import Iterable, Tuple from atmfjstc.lib.text_utils import iter_wrap_items from atmfjstc.lib.abstract_codegen.CodegenContext import CodegenContext from atmfjstc.lib.abstract_codegen.ast.base import AbstractCodegenASTNode, PromptableNode class Sequence(AbstractCodegenASTNod...
#!/usr/bin/env python ########### # Imports # ########### import csv import os import torch import torch.nn as nn from PIL import Image from torch.utils import data from torchvision import datasets from generator import base64ToPIL ############# # Functions # ############# def DoubleConvolution(in_channels, out...
from subprocess import check_call import os import os.path as op import shutil as sh import yaml from nbclean import NotebookCleaner import nbformat as nbf from tqdm import tqdm import numpy as np from glob import glob import argparse DESCRIPTION = ("Convert a collection of Jupyter Notebooks into Jekyll " ...
# -*- coding: utf-8 -*- """ Super-fast Attitude from Accelerometer and Magnetometer ======================================================= This novel estimator proposed by [Wu]_, offers an extremely simplified computation of `Davenport's <../davenport.html>`_ solution to `Wahba's problem <https://en.wikipedia.org/wik...
# -*- coding: utf-8 -*- import pytest from marshmallow import fields from marshmallow.marshalling import Marshaller, Unmarshaller, missing from marshmallow.exceptions import ValidationError from tests.base import User def test_missing_is_falsy(): assert bool(missing) is False class TestMarshaller: @pytest...
"""Turtle asteroids""" import turtle import time import random screen = turtle.Screen() width, height = screen.screensize() turtle.tracer(0,0) turtle.listen() t = turtle.Turtle() t.speed(0) t.hideturtle() class Scene(object): def __init__(self, game): self.game = game d...
import os import io from glob import glob from collections import OrderedDict, defaultdict import numpy as np import torch import torch.distributed as dist import torchvision.utils as vutils import torchvision.transforms.functional as TF import PIL.Image from mpi4py import MPI # Note! This is l2 square, not l2 def l...
from collections import defaultdict import logging import networkx as nx from networkx.classes.function import add_path from python_cypher import python_cypher from xpark import settings from xpark.plan.base import BaseOptimizedPlan from xpark.utils.iter import take_pairs _LOG = logging.getLogger(__name__) PARSER = p...
import warnings warnings.filterwarnings("ignore") import keras from keras.models import Sequential, Model from keras.preprocessing.image import ImageDataGenerator from keras.datasets import cifar10 from keras.regularizers import l2 from keras.layers import Dense, Dropout, Activation, BatchNormalization, Conv2D, MaxPoo...
from tempfile import NamedTemporaryFile from statiskit import linalg from statiskit import pgm import unittest from nose.plugins.attrib import attr @attr(linux=True, osx=True, win=True, level=1) class TestUndirectedGraph(unittest.TestCase): @classmethod def setUpClass(cls): """Test...
import time import sys import openvr import math import json from functools import lru_cache # Function to print out text but instead of starting a new line it will overwrite the existing line def update_text(txt): sys.stdout.write('\r' + txt) sys.stdout.flush() # Convert the standard 3x4 position/rotation...
# 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...
import datetime import multiprocessing import signal import sys import threading import time import warnings from concurrent.futures import ThreadPoolExecutor from concurrent.futures import TimeoutError as FutureTimeout from functools import wraps from logging import Logger from typing import TYPE_CHECKING, Any, Calla...
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Demonstration manager for the Amazon S3 file transfer example. The demonstration collects information from the user and runs various upload and download scenarios to show how to use Boto 3 managed transfers. ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab # flake8: noqa from __future__ import unicode_literals, division, absolute_import, print_function from .compatibility_utils import PY2, text_type, bchr, bord import binascii if PY2: range = xrange from itertools impo...
""" @copyright (c) 2012 ON Semiconductor. All rights reserved. ON Semiconductor is supplying this software for use with ON Semiconductor processor based microcontrollers only. THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF M...
# generated by datamodel-codegen: # filename: iiif_3_0.json # timestamp: 2022-04-01T08:25:37+00:00 from __future__ import annotations from datetime import datetime from typing import Any, Dict, List, Optional, Union from pydantic import AnyUrl, Field, confloat, constr from .base import Base class Behavior(Ba...
from math import sin, cos import ast import math import numpy as np from scipy.integrate import solve_ivp from simulated_dynamics import NumpySimulatedDynamics from friction import Friction def xaxis(): x = np.zeros((2,1)) x[0] = 1 return x def yaxis(): y = np.zeros((2,1)) y[1] = 1 return y ...
import argparse import os import sys import numpy as np from ase.io import read, write from asaplib.io import str2bool from qml.representations import generate_fchl_acsf def repr_wrapper(frame, elements, is_periodic = False, nRs2=24, nRs3=20, ...
#!/usr/bin/env python3 # # Copyright 2021 Red Hat, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 ...
# # Copyright (c) 2019 -2021 MINRES Technolgies GmbH # # SPDX-License-Identifier: Apache-2.0 # import cppyy import os.path import site from sysconfig import get_paths import sys import re import logging from contextlib import (redirect_stdout, redirect_stderr) import io lang_symbols = { 3: '199711L', 11:'2011...
import os import re import subprocess from pathlib import Path from typing import List, Tuple import click import pytest from tango.common import Params from tango.common.testing import TangoTestCase from tango.settings import TangoGlobalSettings from tango.version import VERSION from tango.workspace import StepExecu...
""" This module contain :class:`Simulation` and :class:`_poolMemory` classes. """ import sys import platform import multiprocessing from .base import _recurseIfList from .baseClasses import timeBase, qBaseSim from .QSweep import Sweep from .extensions.modularSweep import runSimulation from .extensions.modularSweep...
# -*- coding: utf-8 -*- import asyncio from crontab import CronTab from collections import OrderedDict from hagworm.extend.interface import TaskInterface from .base import Utils, FutureWithTask class _BaseTask(TaskInterface): """异步任务基类 """ def __init__(self, _callable): self._running = False...
import os import gzip import json import pickle import argparse import numpy as np import matplotlib.pyplot as plt from RsNet.setup_mnist import MNIST from RsNet.dataset_nn import model_mnist_meta, model_cifar10_meta import tensorflow as tf from RsNet.tf_config import setup_visibile_gpus, gpu_config def norm_l0(x1, x...
""" eval A set of functions for evaluating an AST. By design we separate the evaluator from the AST. Rather than have the eval functions as methods on the different node types. """ from eta.types import Symbol, Expression, Definition, EmptyExpr, IfExpression, \ Lambda, EtaError, AndDefinition, OrDefinition, QuoteT...
from __future__ import print_function import os import random import cv2 import numpy as np import tensorflow as tf from sklearn.model_selection import train_test_split from tensorflow import keras from tensorflow.keras import backend as K from tensorflow.keras.callbacks import ModelCheckpoint from tensorflow.keras.l...
from __future__ import annotations from typing import Any, Callable, List, Union from util import valid_comp, valid_min from variables import AllVariable, IndexVariable, RandomVariable, RangeVariable, SampleVariable, SizeVariable, \ Variable, VariableDict, VariableSet, merge # Default syntax specifiers _default_...
# The 2D position is based on OpenCV computer vision and the Essential matrix that can be calculated with matched Features # Compare all the test images against all the reference images # Find which session has the highest match rate # Find which Image has the highest match rate # Calculate the transformati...
from __future__ import annotations import mimetypes import os import pathlib import re import typing import typing as t import uuid from babel.core import Locale from imia import UserLike, UserToken from starlette import datastructures as ds, requests from starlette.datastructures import State from starlette.requests ...
import ctypes import numpy as np import os import subprocess import tempfile import tvm from tvm import relay, get_global_func, target, register_func from tvm.relay.function import Function from tvm.relay.expr import Expr, Let, GlobalVar from tvm.relay.adt import Constructor from tvm.relay.expr_functor import ExprFunct...
import sys import time import threading import random import telepot from telepot.loop import MessageLoop from telepot.namedtuple import ReplyKeyboardMarkup, KeyboardButton, ReplyKeyboardRemove, ForceReply from telepot.namedtuple import InlineKeyboardMarkup, InlineKeyboardButton from telepot.namedtuple import InlineQue...
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (c) 2017 F5 Networks Inc. # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { 'status': ['preview'], 'supp...
''' Generate Master TSNR ensemble DFLUX files. See doc. 4723. Note: in this instance, ensemble avg. of flux is written, in order to efficiently generate tile depths. ''' import os import sys import argparse import numpy as np from pkg_resources import resource_filename import astropy.io.fits as fits from astropy.tab...
import sys,re,argparse,socket try : from scapy.all import * except Exception as e : print('[!]Is scapy installed ?') print('[>]Installation possible via pip : python3.x : pip3 install scapy-python3'+'\n'\ 'sudo must be used if not root') sys.exit('Exception details:'+str(e)) file1 = open('Open_Ports_results.tx...
from collections import Counter from dataclasses import dataclass from aocd import get_data @dataclass class InputLine: line: str = "" def signals(self) -> list: return ["".join(sorted(result)) for result in str.strip(self.line.split('|').pop(0)).split(' ')] def output(self) -> list: ret...
""" Python module for controlling Yeelight Sunflower bulbs. This module exports the Hub and Bulb classes. All bulbs belong to one hub. """ import datetime import logging import socket import threading TIMEOUT_SECONDS = 2 GET_LIGHTS_COMMAND = "GL,,,,0,\r\n" BUFFER_SIZE = 8192 UPDATE_INTERVAL_SECONDS = 1 _LOGGER = lo...
# -*- coding: utf-8 -*- # # Copyright 2015 Ternaris, Munich, Germany # # 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...
""" Control Compulab fit-statUSB devices from python https://fit-iot.com/web/product/fit-statusb/ """ from enum import Enum from io import BytesIO import re from serial import Serial import serial.tools.list_ports as list_ports import time # Vendor and product ID for Compulab fit-statUSB with Texas Instruments chip V...
import torch import torch.nn as nn from torch.utils.checkpoint import checkpoint from torch.nn.modules.utils import _pair as to_2tuple from mmseg.ops import resize from mmcv.runner.base_module import BaseModule from mmcv.cnn import ConvModule, build_norm_layer from mmcv.cnn.bricks.transformer import FFN from ..backbone...
from functools import partial import pickle import multiprocessing as mp from multiprocessing.pool import ThreadPool import traceback import numpy as np import pandas as pd from sklearn.externals import joblib from sklearn.linear_model import Lasso from mercari.config import \ DUMP_DATASET, USE_CACHED_DATASET, DE...
"""JOSE utilities.""" import abc from types import ModuleType from typing import Union, Any, Callable, Iterator, Tuple, List, TypeVar, cast from collections.abc import Hashable, Mapping import sys import warnings from OpenSSL import crypto from cryptography.hazmat.primitives.asymmetric import ec, rsa # Deprecated. P...
# Copyright (c) 2011, <NAME> <<EMAIL>>, # <NAME> <<EMAIL>> # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH # REGARD TO THIS SOFTWARE INCLUD...
# ##### 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...
import torch import torch.nn as nn import numpy as np from torch.utils.tensorboard import SummaryWriter def tensorboard(): # writer = SummaryWriter(comment='test_tensorboard') writer = SummaryWriter(log_dir="./train_log/test_log_dir", comment='test_tensorboard') for x in range(100): # add_scalar(t...
# Made by DrLecter import sys from com.l2jfrozen.gameserver.datatables.sql import ItemTable from com.l2jfrozen.gameserver.model.quest import State from com.l2jfrozen.gameserver.model.quest import QuestState from com.l2jfrozen.gameserver.model.quest.jython import QuestJython as JQuest qn = "7000_HeroItems" MONUMENTS =...
import numpy as np import pandas as pd import contractions from gensim.models import Word2Vec from gensim.models import KeyedVectors from imblearn.over_sampling import RandomOverSampler from sklearn.model_selection import train_test_split import itertools, re from sklearn.naive_bayes import CategoricalNB, Compleme...
#!/usr/bin/env python3 #-------------------------------------------------------------------------- # BHLReco - BlockHashLoc Recover # # Created: 06/05/2017 # # Copyright (C) 2017 <NAME> - http://mark0.net/ # # Licence: # This program is free software: you can redistribute it and/or modify # it under the terms of the G...
# Copyright 2018 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
""" Proposal for further splitting of the current structure: - the liap module should take bigger part in the nesting. - the TableElement class shall assist more in the unfolding of the pseudotables. """ from functools import lru_cache from typing import Union from collections import Counter from lexref.model ...
import re from dataclasses import dataclass from typing import Dict, List, Sequence, Text, Tuple from smart_open import open GROUPING_ENTITIES = frozenset(["And-Group", "Or-Group"]) GROUPING_RELATIONS = frozenset(["And", "Or"]) def remove_empty(iterable: Sequence[Text]) -> Sequence[Text]: """ Returns only n...
import os, sys import pandas as pd import numpy as np from random import shuffle import argparse from math import log, floor def load_data(train_data_path, train_label_path, test_data_path): X_train = pd.read_csv(train_data_path, sep=',', header=0) X_train = np.array(X_train.values) Y_train = pd.read_csv(...
# Copyright 2017 <NAME>. All Rights Reserved. # MIT License """Orchestrates training and evaluation of a neural network""" import argparse import glob import json import os from keras.callbacks import Callback, ModelCheckpoint, TensorBoard, EarlyStopping from keras.models import load_model from tensorflow.python.lib...
import numpy as np import os import pandas as pd from snorkel.labeling import PandasLFApplier from synthesizer.parser import nlp from config import DATASETS_PATH from config import DEFAULT_MAX_TRAINING_SIZE from config import MIN_LABELLED_SIZE from config import PROCESSED_FILE_NAME ALLOWED_EXTENSIONS = {'csv'} def ...
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import unittest import erpnext import frappe from dateutil.relativedelta import relativedelta from erpnext.accounts.utils import get_fiscal_year, getdate...
# coding=utf-8 from function.main import * from function.variables import * from secrets.secrets import * from PIL import Image from PIL import ImageFont from PIL import ImageDraw from io import BytesIO import requests import shutil import time import datetime import asyncio start = getTime() @client.event async def ...
# Copyright (c) 2013 OpenStack Foundation # 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 r...
""" Tests for the estimation module """ import pytest from mock import Mock import numpy as np from scipy.stats import bernoulli from pyquil.paulis import sX, sY, sZ, sI, PauliSum, is_zero from pyquil.quil import Program from pyquil.gates import RY, RX from pyquil.api import QVMConnection from grove.measurements.estima...
# -- coding: utf-8 -- """Methods to for regions, i.e. connected areas with same unique ID. Building on scipy.ndimage measurement methods, see https://docs.scipy.org/doc/scipy/reference/ndimage.html#measurements """ from scipy import ndimage import numpy as np from numba import njit from . import gis_utils __all__ = ...
#/usr/bin/env python # -*- coding:utf-8 -*- from urllib import request,parse from bs4 import BeautifulSoup import http.cookiejar import time import re import pyqrcode import io import math import os import random import json import subprocess import sys ''' 构建公共请求头 ''' global globalData QRImagePath = os.path.join(...
""" Adapated from Vertex frequency codebase. Credit to <NAME>. Algorithms based on https://arxiv.org/pdf/1905.09758.pdf Goal is to estimate the density of eigenvalues over a known range. """ import numpy as np import scipy.sparse as ss import scipy.io as sio import numpy.random as nr import matplotlib.pyplot as plt im...
import numpy as np import scipy.sparse as sp import sklearn import sklearn.metrics import torch import pandas as pd import random def boolean_string(s): if s not in {'False', 'True'}: raise ValueError('Not a valid boolean string') return s == 'True' def encode_onehot(labels): classes = set(labels)...
import collections from collections.abc import Iterable class Move: def __init__(self, parent_action): self.parent_action = parent_action def perform(self, game_state, player): pass def __str__(self): return self.__class__.__name__ def __eq__(self, other): retur...
""" 'storage-list' subcommand for kubectl-kadalu CLI tool """ from __future__ import print_function import json import sys import utils # noqa # pylint: disable=too-many-instance-attributes # noqa # pylint: disable=useless-object-inheritance # noqa # pylint: disable=too-few-public-methods # noqa # pylint: disable=bad...
""" .. codeauthor:: <NAME> <<EMAIL>> """ import numpy as np import pytest from pde import ScalarField, UnitGrid from pde.tools.misc import skipUnlessModule from droplets import DiffuseDroplet, Emulsion, SphericalDroplet, droplets, emulsions def test_empty_emulsion(): """test an emulsions without any droplets""...
# coding: utf-8 # In[7]: import cv2 import numpy as np import scipy.io from scipy import signal import scipy import matplotlib.pyplot as plt from visualize import visualize # (A) Compute the projection matrix from a set of 2D-3D point correspondences by using the leastsquares (eigenvector) method for each image. ...
#!/usr/bin/env python3 # coding: utf-8 ### QUESTION 2 # [0,1,2,3] -> 3X^3 + 2X^2 + X # [1,2,3] -> 3X^2 + 2X + 1 # [3,2,1] -> X^2 + 2X + 3 # [3,2,1,0] -> X^2 + 2X + 3 # X^2 + 2 -> [2,0,1] # 2 + 2X + 2X^2 + 2X^3 -> [2,2,2,2] # X^10 + X^20 -> [0]*10 + [1] + [0]*9 + [1] def clear_poly(poly): """Enlève les puissance i...