text stringlengths 6.04k 39.5k |
|---|
import pickle
import jax
import jax.numpy as jnp
import jax.random
import numpy as np
import sklearn.metrics as metrics
from jax import lax
from sklearn.metrics import log_loss
def inf_generator(iterable):
"""Allows training with DataLoaders in a single infinite loop:
for i, (x, y) in enumerate(inf_generator... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Title :图片处理工具类
@File : image_util.py
@Time : 2019/11/7 5:25 下午
@Version : 1.0
'''
import cv2
import os, math
import numpy as np
import random
from PIL import Image, ImageDraw, ImageFile
from app.main.app.utils import text_util
ImageFile.LOAD_TRUNCATED_IMA... |
#!/bin/python
'''
redshift success rate calculations necessary for SV preparation
'''
import os
import h5py
import pickle
import numpy as np
import scipy as sp
import corner as DFM
from itertools import product
# --- desi ---
import specsim.config
from desisurvey import etc as ETC
# --- astropy ---
import a... |
# %%
'''----------------------------------------------------------------
This script deals with Neutrophils and B cells interaction
----------------------------------------------------------------'''
import os
import pickle
import cv2
import pandas as pd
import numpy as np
from tqdm import tqdm
import sys
sy... |
#!/usr/bin/env python
# Copyright 2018 <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 agree... |
#cryptobot
# requires python 3.8.7
#------------
import csv
import config
import time
from datetime import date
from enum import Enum
import os
import sys
from decimal import *
import math
#Binance
from binance.client import Client
from binance import exceptions
#Discord
import requests
from discord... |
# inference with fine_tuned Bert
from transformers import pipeline
from transformers import AutoModelForTokenClassification
from transformers import AutoTokenizer
import torch
import re
import pickle
import argparse
from collections import Counter
parser = argparse.ArgumentParser()
parser.add_argument('--predict'... |
import numpy as np
import tensorflow as tf
import config
def generate_obstacle_circle(center, radius, num=12):
theta = np.linspace(0, np.pi*2, num=num, endpoint=False).reshape(-1, 1)
unit_circle = np.concatenate([np.cos(theta), np.sin(theta)], axis=1)
circle = np.array(center) + unit_circle * radius
... |
# Copyright 2021 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... |
"""
ID Software Quake 2 Model File.
Some parts of this file is based on the original work from:
https://github.com/adamlwgriffiths/PyMesh/tree/master/pymesh/md2
"""
import logging
import os
import struct
import time
from copy import deepcopy
from typing import Any, BinaryIO, Dict, Generator, List, NamedTuple, Optional... |
import numpy as np
import networkx as nx
import operator
def get_unassigned_nodes(node_id_list, attribute_dict):
unassigned = []
for n in node_id_list:
if attribute_dict[n] == -1:
unassigned.append(n)
return unassigned
def sample_cell_type(dist):
x_i = np.random.multinomial(1, dist... |
import datetime as dt
import os
from datetime import timedelta
from pathlib import Path
import holidays
import pandas as pd
from sqlalchemy import create_engine
DB_HOST = 'localhost'
DB_PORT = 5432
DB = 'group_16'
def main():
user = input('Enter pgadmin username: ')
password = input('Enter p... |
import functools
import PySimpleGUI as sg
import re
from easydbo.exception import EASYDBO_GOTO_LOOP, EASYDBO_USER_ERROR
from .alias import AliasWindow
from .base import BaseWindow
from .common.layout.attribution import Attribution as attr
from .common.popup import popup_error
from .common.sql import create_query_result... |
# -*- coding: utf-8 -*--
from sqlalchemy.sql.elements import and_
from sqlalchemy.sql.sqltypes import Float
from pyramid.view import view_config
import pyramid.httpexceptions as exc
from infolica.exceptions.custom_error import CustomError
from infolica.models.constant import Constant
from infolica.models.models import... |
from __future__ import annotations
import random
import struct
from typing import Union, Iterator, TYPE_CHECKING
import elma.models
from elma.constants import VERSION_ELMA
from elma.constants import VERSION_ACROSS
from elma.constants import END_OF_DATA_MARKER
from elma.constants import END_OF_FILE_MARKER
from elma.co... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 21 10:42:13 2021
@author: <NAME>
"""
import numpy as np
from scipy.sparse import coo_matrix
def vertexNeighborFromEdge(vertex, edge):
if vertex == edge[0]:
return edge[1]
elif vertex == edge[1]:
return edge[0]
return No... |
import socket
import time
import sys
import os.path
import dbus
import dbus.exceptions
import dbus.mainloop.glib
import dbus.service
from gi.repository import GLib
try:
from gi.repository import GObject
except ImportError:
import gobject as GObject
mainloop = None
BLUEZ_SERVICE_NAME = 'org.bluez'
GATT_MANAG... |
# -*- coding: utf-8 -*-
"""
A Step by Step Back propagation Example.
This code is based on the implementation by <NAME>.
Tutorial: https://mattmazur.com/2015/03/17/a-step-by-step-backpropagation-example/
Github: https://github.com/mattm/simple-neural-network
"""
import numpy as np
def neuron_create(nu... |
import pandas as pd
import datetime
import urllib
import urllib.request
import json
import requests
import io
class Reportes:
def __init__(self):
self.__cargar()
self.lista_emisoras = self.diccionario.keys()
self.estado = 'Reportes trimestrales'
self.__mxn_usd()
self.__repo... |
import torch
from torch.nn.modules import Module
import cutlassconv_cuda
import int8pool_cuda
import int8mm_cuda
import int8conv_cuda
import torch.nn.functional as F
import time
from options import args
class UpdateWeight(Module):
"""
The parameter update part of both TiConv2d and TiLinear are the same
Use... |
# -*- coding: utf-8 -*-
"""Test Markdown parser and reader."""
# ------------------------------------------------------------------------------
# Imports
# ------------------------------------------------------------------------------
from ipymd.core.format_manager import convert, format_manager
from ._utils import ... |
import uuid
from concurrent.futures.thread import ThreadPoolExecutor
from threading import Thread
from eggroll.core.aspects import _method_profile_logger
from eggroll.core.command.command_model import ErCommandRequest
from eggroll.core.constants import StoreTypes
from eggroll.core.io.kv_adapter import RocksdbSortedKvA... |
import os
from collections import OrderedDict
import itertools
import functools
import numpy as np
import pickle
import json
class Model:
def __init__(self, range_dict_list_filepath=os.path.join(os.getcwd(), 'range_dicts', 'range_dict_list.json')):
self.range_dict_list_filepath = range_dict_list_filepat... |
import random
import numpy
import pysam
from Crypto.Cipher import AES
count_reads = 0
count_candidates = 0
count_extensions_case_default = 0
count_extensions_case_reverse = 0
count_extensions_not_done = 0
count_contraction_case_default = 0
count_contraction_case_reverse = 0
count_contraction_not_done = 0
count_contra... |
#std packages
from collections import OrderedDict
#third-party packages
import scipy.constants as sc
from PyQt5.QtGui import QIcon, QFont, QDoubleValidator
from PyQt5.QtWidgets import (QMainWindow, QWidget, QApplication, QPushButton, QLabel, QAction, QComboBox, QStackedWidget,
QDoubleSpin... |
import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder
import json
import logging
from os.path import exists, basename, abspath, join
from time import sleep
import multiprocessing
log = multiprocessing.get_logger()
logging.getLogger('urllib3').setLevel(logging.WARN)
GOOGLE_DRIVE_SCOPE = 'h... |
import os
from math import sqrt
# ----------------------------------
# make txt files
# ----------------------------------
def space():
return ' '
def make_txt_edges(f_name='School_Gazebo_EGraph', E=None):
if E is None:
edges = manual_ss_edges()[0]
else:
edges = E
line1 = ['SS-2', ... |
import ctypes as ct
import errno
import signal
import socket
import sys
import typing as ta
Self = ta.TypeVar('Self')
LINUX_PLATFORMS = ('linux', 'linux2')
DARWIN_PLATFORMS = ('darwin',)
LINUX = False
DARWIN = False
if sys.platform in LINUX_PLATFORMS:
libc = ct.CDLL('libc.so.6')
LINUX = True
elif sys.pla... |
"""Spectral Projection gurgle tools"""
from functools import wraps, cached_property
import numpy as np
from scipy.spatial.distance import cdist
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import IncrementalPCA, PCA
from sklearn.utils.validation import check_is_fitted, check_array
from ... |
import random
from ..utils import process_graphs, ModelInput
from .samplers import single_view_contrast
from .samplers.augmentations import *
class SamplerFactory:
def __init__(self, name, graph, features, batch_size, negative_ratio=5, **kwargs):
# super(BaseSampler, self).__init__()
self.graph = ... |
"""
Cryptanalib3 - A series of useful functions for cryptanalysis
by Daniel "unicornFurnace" Crowley
dependencies - PyCryptodome
"""
# Get helper functions
from . import helpers
from . import frequency
import operator
from math import sqrt
# -------------------------
# Classical cryptography functions
#
# This secti... |
import os
import numpy as np
from array import array
from sklearn.metrics import mean_absolute_error
from skmultiflow.data import RegressionGenerator
from skmultiflow.trees import HoeffdingTreeRegressor
from skmultiflow.utils import calculate_object_size
from difflib import SequenceMatcher
def test_hoeffding_tree_reg... |
# ### Walking controller
# Written by <NAME> <EMAIL>
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing ... |
# get_movie_data.py
"""Use imdbpy (pip install imdbpy) to get data for the Kevin Bacon lab."""
import os
import re
import pickle
from time import time
from statistics import mean
from collections import defaultdict
import imdb
try:
from tqdm import tqdm
except ImportError:
print("Recommended: pip install tqdm... |
#!/usr/bin/env python
"""
Simulates high frequency seismograms for stations.
"""
from argparse import ArgumentParser
import os
import random
from subprocess import Popen, PIPE
from tempfile import mkstemp
import numpy as np
import logging
from qcore import binary_version, constants, utils
from shared_workflow.platfor... |
import asyncio
import unittest
from time import time
from functools import wraps
# Sorry "web." notation is a legacy from zorro
import aioroutes as web
from aioroutes.http import BaseHTTPRequest
from aioroutes.exceptions import OutOfScopeError, NotFound, MethodNotAllowed
def instantiate(klass):
"""Class decorato... |
"""Structs and definitions used serialize/deserialize ATOP statistics directly from log files.
Structs are declared in a way that will help provide as close to a 1 to 1 match as possible for debuggability
and maintenance. The _fields_ of every struct match their original name, however the struct names have been update... |
import re
from collections import abc
from pudzu.utils import *
# Pronouncing dictionary class, largely targeted at English
IPA_VOWELS = "ɔɑiuɛɪʊʌəæeaoyʏøɝɚɒɜʁ"
IPA_VOWELENDINGS = IPA_VOWELS + "ː̯̩̃"
IPA_CONSONANTS = "pbtdkɡfvθðszʃʒhmnŋlrɾɹjwʔʍχ"
IPA_STRESS = "ˈˌ"
class Nouncer(abc.MutableMapping):
PHONEME_PA... |
from __future__ import division
import torch
import math
import argparse
import time
from torch.autograd import Variable
from PIL import ImageDraw
def detect_arg_parse():
"""
Parse arguments to the detect module.
:return: parser.parse_args()
"""
parser = argparse.ArgumentParser(description='YOLO... |
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, Iterable, List, Optional, Set, Tuple
import numpy as np
from darwin.dataset.utils import extract_classes, get_release_path
from darwin.datatypes import PathLike
@dataclass
class Split:
"""
A Split object holds the state of a ... |
"""
The inference algorithm
introduce a new format of fit
trial isolation
unequal trial ready
"""
import logging
import click
import numpy as np
from numpy import identity, einsum, trace
from scipy.linalg import solve, norm, svd, LinAlgError
from . import gp
from .evaluation import timer
from .math import trunc_exp
f... |
# gemato: Manifest file support tests
# vim:fileencoding=utf-8
# (c) 2017-2020 <NAME>
# Licensed under the terms of 2-clause BSD license
import datetime
import io
import pytest
from gemato.exceptions import (
ManifestSyntaxError,
)
from gemato.manifest import (
ManifestFile,
ManifestEntryTIMESTAMP,
... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# *****************************************************************************/
# * Authors: <NAME>
# *****************************************************************************/
from __future__ import absolute_import, division, print_function, unicode_literals # , ne... |
import tkinter as tk
import tkinter.messagebox
from time import sleep
from random import choice
from PIL import ImageTk, Image
from settings import *
from board import *
class Coin:
def __init__(self, master, x, y, color, path_list, flag):
self.canvas = master
self.curr_x = x
self.curr_y... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# parsereport.py
#
# Codecheck assumptions:
# - All *.signed.zip files in download_directory are read
# - The last @author e-mail address in student files (alphabetically) will...
# - (a) be valid (including > & <) and (b) not contain 'address'
#
"""
parsereport.... |
import os
import six
from copy import copy
from jinja2 import Template
from operator import itemgetter
from collections import Mapping
from .meta import Attr, Attrs, Meta, create_hook, preserve_attr_data, \
pre_create_hook
from syn.base_utils import AttrDict, ReflexiveDict, message, get_mod, \
get_typename, Seq... |
import os
import sys
import sqlite3
import pandas as pd
from matplotlib import pyplot as plt
from multiprocessing import Process, Queue
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
from utility.static import now, strf_time
from utility.setting import db_day, db_backtest, db_stg, graph_pa... |
import logging
import math
import random
import re
import nltk
from nltk.tokenize import word_tokenize
import logger
from noise.noise_phoneme import NoiseFromP2G
from utils import choice
class SamplingGraph:
def __init__(self, noise_generator, error_prob, max_M, sampling_M, sampling_N, sampling_error_samples):
... |
#!/usr/bin/env python3
# Pest Control - Battle for the Lawn
# Requires Python 3 and Pygame library
import pygame as pg
import os, sys
from random import randint
class Window:
def __init__(self):
'''Create screen surface object'''
self.screen = pg.display.set_mode((650,625))
self.rect =... |
r"""
Python wrapper around the ``librlscope.so`` ``LD_PRELOAD`` library.
We offload most profiling work to the C++ library.
In particular:
#. Every :py:meth:`rlscope.profiler.profilers.Profiler.operation` calls into
:py:func:`push_operation` upon entering the ``with`` block and
:py:func:`pop_operation` upon exit... |
#!/usr/bin/env python
# Core python library
import os
import sys
import copy
import base64
import logging
import tempfile
import argparse
import pkg_resources
# Other stuff
import ete3
from ete3 import NodeStyle, TreeStyle, TextFace
def get_version():
"""
Uses :mod:`pkg_resources` to figure out what versio... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 25 20:36:41 2016
@author: <NAME>
"""
import numpy as np
import matplotlib
import matplotlib.pyplot as pl
import scipy.special as sps
from mpl_toolkits.mplot3d import Axes3D
from scipy import ndimage
from skimage import measure
import time
start_time = time.time()
#######... |
#! /usr/bin/python3
#from __future__ import absolute_import
##############################################################################################
#################### example for network-file ################################################
#################### contains definition of whole graph ##########... |
"""
Coupling
********
Functions to estimate coupling from twiss dataframes and different methods to calculate the closest tune
approach from the calculated coupling RDTs.
"""
import logging
from contextlib import suppress
from typing import Sequence, Tuple
import numpy as np
from pandas import DataFrame, Series
from ... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from mflow.models.basic import GraphLinear, GraphConv, ActNorm, ActNorm2D
# class AffineCoupling(nn.Module):
# def __init__(self, in_channel, hidden_channels, affine=True): # filter_size=512, --> hidden_channels =(512, 512)
# super(Affin... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import date, datetime, timedelta
from unittest.mock import patch
from odoo.addons.event.tests.common import TestEventCommon
from odoo import exceptions
from odoo.fields import Datetime as FieldsDatetime, D... |
import pandas as pd
import torch
import random
import numpy as np
from scipy.sparse import coo_matrix, csr_matrix
from torch.utils.data import Dataset
import time
import pickle as pkl
import h5py
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import sys
def load_array_data(dataname):... |
# -*- coding: utf-8 -*-
"""parser object module."""
from __future__ import unicode_literals
import os
import argparse
import pydoc
import pickle
import re
from pyloco.util import (pyloco_formatter, parse_param_option, type_check,
Option)
from pyloco.error import UsageError, NormalExit, TypeC... |
import codecs
import copy
import pickle
import numpy as np
import console
import constants
import regression
np.random.seed(11)
# This is to pickle all foods in sorted order
def pickle_top_foods_for_each_nutrient(pickle_all_foods=True):
with open(constants.NUTRIENT_DETAILS_FILE, 'r', encoding='ISO-8859-1') \
... |
# coding=utf-8
#
# The MIT License (MIT)
#
# Copyright (c) 2016-2017 yutiansut/QUANTAXIS
#
# 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 th... |
'''
Wrappers for Bert submodules adapted from
https://github.com/huggingface/transformers/blob/master/src/transformers/models/bert/modeling_bert.py.
This implementation is far from optimal and will likely be rewritten in a more concise way in the future (using Flax maybe?)
'''
import torch
import math
from... |
import time
import zlib
import json
import sys
import text_game_maker
from text_game_maker.audio import audio
from text_game_maker.game_objects.living import LivingGameEntity
from text_game_maker.game_objects import __object_model_version__
from text_game_maker.game_objects.items import SmallBag, Lighter, Coins
from ... |
# Copyright 2020 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, so... |
import autograd.numpy as np
import math
import scipy.optimize
from scipy.odr import ODR, Model, RealData
from scipy.linalg import cholesky
from scipy.stats import norm
import pyerrors as pe
import pytest
np.random.seed(0)
def test_fit_lin():
x = [0, 2]
y = [pe.pseudo_Obs(0, 0.1, 'ensemble'),
pe.pseu... |
import collections
import random
import heapq
from typing import Iterator, List, Union, Tuple, Any, TypeVar, Optional, \
TYPE_CHECKING
import numpy as np
try:
import pyarrow
except ImportError:
pyarrow = None
from ray.data.block import Block, BlockAccessor, BlockMetadata
from ray.data.impl.block_builder ... |
# Copyright (c) 2020 PaddlePaddle 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 app... |
import os
import time
import sys
import datetime
import joblib
import numpy as np
import os.path as osp
import tensorflow as tf
sys.path.append('../')
from baselines import logger
from collections import deque
from baselines.common import explained_variance
import multiprocessing
import sys
from gym import spaces
impo... |
#!/usr/bin/env python
#
# -----------------------------------------------------------------------------
# Copyright (c) 2017 The Regents of the University of California
#
# This file is part of kevlar (http://github.com/dib-lab/kevlar) and is
# licensed under the MIT license: see LICENSE.
# ----------------------------... |
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 15 18:58:22 2021
@author: <NAME>
Code to build model of neurons by analyzing their image and score trajectory.
Depending on the `Visual_Neuron_Modelling` repository.
"""
# %load_ext autoreload
# %autoreload 2
#%%
# backup_dir = r"C:\Users\Ponce lab\Documents\ml2a-monk\ge... |
from __future__ import print_function
import numpy as NP
"""
A module which implements the continuous wavelet transform
---------------------------------------------------------
Code released under the BSD 3-clause licence.
Copyright (c) 2012, <NAME>, University of Cape Town
All rights reserved.
Redistribution and ... |
import argparse
import pickle
import re
import string
import sys
import warnings
import matplotlib.pyplot as plt
import nltk
nltk.download('stopwords')
nltk.download('wordnet')
nltk.download('omw-1.4')
nltk.download('punkt')
import pandas as pd
from matplotlib import pyplot as plt
from nltk.corpus import stopwords
f... |
import copy
import logging
import multiprocessing
import time
import signal
from typing import Dict
from lume_model.variables import Variable, InputVariable, OutputVariable
import numpy as np
import os
from queue import Full, Empty, Queue
from epics.ca import CAThread
import epics
from epics.multiproc import CAProces... |
# -*- coding: UTF-8 -*-
import time
from .imp_device import Device, DeviceError
from .imp_datatypes import DataTypes
from .imp_packages import Package
from .imp_commands import Command
from .imp_responces import Responce
from .imp_tables import Tables
from .imp_helper import _imprange
class BusError(Exception):
... |
# Copyright 2017-2020 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" fil... |
import collections
import inspect
import io
import types
import typing
import warnings
import torch
from . import (_dev_utils, activations, convolution, normalization, pooling,
preprocessing, regularization, upsample)
from ._version import __version__
from .module import InferDimension
__all__ = ["sum... |
from keras.models import Model
from keras.layers.recurrent import LSTM
from keras.layers import Dense, Input, Embedding, Bidirectional, Concatenate
from keras.preprocessing.sequence import pad_sequences
from keras.callbacks import ModelCheckpoint, EarlyStopping
from keras.layers.core import Flatten
from collectio... |
import numpy, pandas
from scipy.spatial import distance
from sklearn.utils import check_array
from scipy.stats import mode as most_common_value
import matplotlib.pyplot as plt
from libpysal import weights
try:
from tqdm import tqdm as _tqdm
HAS_TQDM = True
except ImportError:
HAS_TQDM = False
def _passt... |
#!/usr/bin/env python3
# predmet: PDS 2018/2019
# projekt: Hybridní chatovací P2P síť
# autor: <NAME> (xsuhaj02)
import socket
import sys
import threading
import os
import json
import time
import errno
import signal
import arg_parser
from my_bencode import *
BUFFSIZE = 65536
node_socket = None
# pre ulozeni... |
r"""
Ordered Set Partitions
AUTHORS:
- <NAME>
- MuPAD-Combinat developers (for algorithms and design inspiration)
- <NAME> (2013-02-28): Removed ``CombinatorialClass`` and added
entry point through :class:`OrderedSetPartition`.
"""
#*****************************************************************************
# ... |
import rlkit.torch.pytorch_util as ptu
from rlkit.data_management.load_buffer import load_data_from_npy, load_data_from_npy_mult
from rlkit.samplers.data_collector import MdpPathCollector, \
CustomMDPPathCollector, CustomMDPPathCollector_EVAL
from rlkit.torch.sac.policies import TanhGaussianPolicy, MakeDeterminist... |
# Copyright 2020 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
# -*- coding: utf-8 -*-
import sys
import re
import unicodedata
import dns.resolver, dns.exception
import idna # implements IDNA 2008; Python's codec is only IDNA 2003
# Based on RFC 2822 section 3.2.4 / RFC 5322 section 3.2.3, these
# characters are permitted in email addresses (not taking into
# account internatio... |
"""
TextAttack Command Helpers for Attack
------------------------------------------
"""
import argparse
import copy
import importlib
import json
import os
import time
import textattack
from .attack_args import (
ATTACK_RECIPE_NAMES,
BLACK_BOX_TRANSFORMATION_CLASS_NAMES,
CONSTRAINT_CLASS_NAMES,
GOA... |
# -*- coding: utf-8 -*-
#!/usr/bin/env python
"""
Aplica filtro paso Butterworth. Se puede pasar array 1D o en pandas DataFrame 2D.
Función de paso bajo o alto y función de bandpass.
"""
from __future__ import division, print_function
import numpy as np
import pandas as pd
import xarray as xr
import scipy... |
# Copyright 2016 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) 2014-2020 Cloudify Platform Ltd. 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... |
# Copyright (C) 2018-2019 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#
import datetime
import logging as log
import os
import sys
import numpy as np
try:
from openvino import inference_engine as ie
from openvino.inference_engine import IENetwork, IEPlugin
except Exception as e:
exception_typ... |
from __future__ import absolute_import
import time
from eth_abi import (
decode_single
)
from eth_abi.exceptions import (
DecodingError
)
from eth_utils import (
encode_hex,
int_to_big_endian,
to_dict,
to_tuple,
to_wei,
is_integer,
)
from eth_utils.decorators import replace_exception... |
#@+leo-ver=5-thin
#@+node:ekr.20211021200745.1: * @file ../plugins/picture_viewer.py
#@+<< docstring (picture_viewer.py) >>
#@+node:ekr.20211021202710.1: ** << docstring (picture_viewer.py) >>
"""
Display image files in a directory tree as a slide show.
This plugin will display all files in a directory tree that have ... |
import collections
import itertools
import pickle
import numpy as np
import pandas as pd
def find_closest(a, v):
""" Find closest value in a to values in v
Args:
a (numpy.array): array in which to search, size N
v (numpy.array): targets to search for, size M
Returns:
numpy.array:... |
# SPDX-FileCopyrightText: 2016-2021 Espressif Systems (Shanghai) CO LTD
# SPDX-License-Identifier: Apache-2.0
import logging
import os
import re
from threading import Thread
import ttfw_idf
from tiny_test_fw import DUT
LOG_LEVEL = logging.DEBUG
LOGGER_NAME = 'modbus_test'
# Allowed options for the test
TEST_READ_MA... |
"""
Custom manager for Objects.
"""
import re
from itertools import chain
from django.db.models import Q
from django.conf import settings
from django.db.models.fields import exceptions
from evennia.typeclasses.managers import TypedObjectManager, TypeclassManager
from evennia.utils.utils import is_iter, make_iter, strin... |
'''
This module contains all fo the routines needed to set up a master server, this
involves preparing the three listeners and the workers needed by the master.
'''
# Import python modules
import cPickle as pickle
import datetime
import hashlib
import logging
import multiprocessing
import os
import re
import shutil
im... |
# coding=utf-8
import json
import threading
from autobahn.twisted.websocket import WebSocketClientFactory, \
WebSocketClientProtocol, \
connectWS
from twisted.internet import reactor, ssl
from twisted.internet.protocol import ReconnectingClientFactory
from twisted.internet.error import ReactorAlreadyRunning
... |
"""
Define a base command class that:
1) provides a consistent interface with `git`,
2) implements common git operations in one place, and
3) tracks file- and repo- specific data the is necessary
for Git operations.
"""
from collections import deque, ChainMap
import io
from itertools import chain, repeat
fr... |
#!/usr/bin/python
from __future__ import (absolute_import, division, print_function)
# Copyright 2019 Fortinet, Inc.
#
# 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 Lic... |
#!/usr/bin/env python3
import itertools
import json
import os
import yaml
__all__ = [
'GENERATION_NAMES',
'MemberList',
'SNH48',
'TEAM_IDS',
'TIERS',
'TIER_NAMES',
'TIER_MEMBERS',
'TeamS2',
'TeamN2',
'TeamH2',
'TeamX',
'TeamX2',
]
HERE = os.path.dirname(os.path.realp... |
"""
Notice : 神兽保佑 ,测试一次通过
//
// ┏┛ ┻━━━━━┛ ┻┓
// ┃ ┃
// ┃ ━ ┃
// ┃ ┳┛ ┗┳ ┃
// ┃ ┃
// ┃ ┻ ┃
// ┃ ┃
// ┗━┓ ┏━━━┛
// ┃ ┃ Author: somewheve
// ┃ ┃ Datetime: 2019/7/3 下午8:46 ---> 无知即是罪恶
// ┃ ┗━━━━━━━━━┓
// ┃ ... |
# encoding=utf-8
import os
import unittest
import tempfile
from pyparsing import ParseException
from jsgf import *
from jsgf.parser import parse_expansion_string, parse_rule_string
class ValidGrammarTests(unittest.TestCase):
"""
Tests for valid_grammar function.
"""
def assert_valid(self, s):
... |
import math
import random
import warnings
import cv2
import torch
import numpy as np
from torchvision import transforms
def gray_scale(image: np.ndarray) -> np.ndarray:
# language=rst
"""
Converts RGB image into grayscale.
:param image: RGB image.
:return: Gray-scaled image.
"""
return c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.