id
stringlengths
3
8
content
stringlengths
100
981k
3397644
import aiocache from discord.guild import Guild import tortoise.exceptions from alttprbot import models CACHE = aiocache.Cache(aiocache.SimpleMemoryCache) async def config_set(self, parameter, value): await models.Config.update_or_create(guild_id=self.id, parameter=parameter, defaults={'value': value}) await...
3397726
from .base_collection import BaseCollection from ..library import ( whitespace_char_text_normalizer, float_with_space_text_normalizer, int_with_space_text_normalizer, float_with_digit_n_space_text_normalizer, int_with_digit_n_space_text_normalizer, full_punctuation_mapping_text_normalizer, s...
3397794
from tir import Webapp import unittest class OGC040(unittest.TestCase): @classmethod def setUpClass(inst): from datetime import datetime DateSystem = datetime.today().strftime('%d/%m/%Y') inst.oHelper = Webapp() inst.oHelper.Setup('SIGAADV',DateSystem,'T1','D MG 0...
3397816
from PIL import Image import torchvision.transforms.functional as TF from torch.utils.data import Dataset, DataLoader from torch.utils.data.dataloader import default_collate import utils.io as io class DetInputDataset(Dataset): def __init__(self,det_input_json): super().__init__() self.det_input ...
3397824
from .efficientnet import (EfficientNet, efficientnet_b0, efficientnet_b1, efficientnet_b2, efficientnet_b3, efficientnet_b4, efficientnet_b5, efficientnet_b6, efficientnet_b7) from .efficientnet_lsoftmax import (efficientnetl_b0,EfficientNetL) from .efficientnetsl ...
3397846
def toJadenCase(string): """ to_jaden_case == PEP8 (forced mixedCase by CodeWars) """ return ' '.join(a.capitalize() for a in string.split())
3397866
from os import getenv from json import loads, JSONEncoder from requests import post class _Singleton(type): """ A metaclass that creates a Singleton base class when called. """ _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(_Singleton, cls)...
3397889
import torchvision as tv import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import time class Model(nn.Module): def __init__(self): super(Model, self).__init__() self.conv1 = nn.Conv2d(3, 20, 5) self.conv2 = nn.Conv2d(20, 50, 5) self.fc...
3397908
import json import time import urllib.request import urllib.error import certifi from collections import deque from . import utils CFDOCS_BASE_URL = "https://raw.githubusercontent.com/foundeo/cfdocs/master/data/en/" CFDOCS_HTTP_ERROR_MESSAGE = """ <p>HTTP requests to GitHub seem to be failing at the moment. This means...
3397920
from twilio.base.exceptions import TwilioRestException from twilio.http import HttpClient from twilio.http.request import Request import platform from twilio import __version__ class Hologram(object): def __init__(self, request, response): self.request = request self.response = response class H...
3397931
from builtins import object from collections import deque """Keys in mockDB correspond to (method, route) calls""" mockDB = dict() class MockResponse(object): """Mocks requests.Response""" def __init__(self, status_code=None, json=None, text=None): self._status_code = status_code self._text...
3397950
import itertools def chunk(iterable, n): """Splits an iterable into a list of length ``n``. If the iterable is finite, The last element may be shorter than the other chunks, depending on the length of the iterable. """ i = iter(iterable) return iter(lambda: list(itertools.islice(i, n)), [])
3397956
from __future__ import print_function # import matplotlib # matplotlib.use('Agg') import unittest import numpy as np from SimPEG.electromagnetics import resistivity as dc from SimPEG.electromagnetics.static import utils from SimPEG import maps, mkvc, data from SimPEG.utils.io_utils import io_utils_electromagnetics as...
3397959
import math import re import asyncio from functools import lru_cache, partial import time from datetime import datetime from dateutil import tz import datetime from multiprocessing import Pool import spacy from spacy import displacy import pandas as pd import redis import numpy as np import dill import nltk nltk.down...
3398005
from pwn import * r = process("./asterisk_alloc", env={"LD_PRELOAD": "./libc.so.6"}) libc = ELF("libc.so.6") def malloc(n, s): r.sendlineafter('choice: ', '1') r.sendlineafter('Size: ', str(n)) r.sendafter('Data: ', s) def calloc(n, s): r.sendlineafter('choice: ', '2') r.sendlineafter('Size: ',...
3398016
import ctypes import pkg_resources import platform if platform.system() == "Windows": library_name = "openxr_loader.dll" elif platform.system() == "Linux": library_name = "libopenxr_loader.so" else: raise NotImplementedError library_path = pkg_resources.resource_filename("xr.library", library_name) openxr...
3398043
import os import boto3 table_name = f'aws-scheduler-events-v2-{os.environ.get("STAGE")}' table = boto3.resource('dynamodb').Table(table_name) client = boto3.client('dynamodb')
3398065
import webapp2 from templates import get_template class CalendarHandler(webapp2.RequestHandler): def get(self): data = { "page" : "write"} self.response.write(get_template('calendar.html').render(data))
3398075
import logging import os import torch import torch.nn as nn import numpy as np logger = logging.getLogger(__name__) def recall(sentence, srl_string): matches = 0 for word in sentence.split(): if word in srl_string: matches += 1 if len(sentence.split()) > 0: return float(matc...
3398100
from polog.core.engine.real_engines.multithreaded.engine import MultiThreadedRealEngine from polog.core.engine.real_engines.singlethreaded.engine import SingleThreadedRealEngine def real_engine_fabric(settings): """ Здесь "порождаются" движки Polog. Т. к. их несколько, выбор движка осуществляется исходя ...
3398110
import argparse import os import os.path as osp from shutil import copyfile import mmcv from tqdm import tqdm def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("--annotation_path", default="/data/coco_train.json") parser.add_argument("--image_root", default="/data/train") parse...
3398125
import textwrap from typing import Union from antlr4.Token import CommonToken from antlr4.tree.Tree import TerminalNodeImpl def is_pow2(x: int) -> bool: return (x > 0) and ((x & (x - 1)) == 0) def roundup_pow2(x: int) -> int: return 1<<(x-1).bit_length() def roundup_to(x: int, n: int) -> int: if x % n:...
3398155
from bxcommon import constants from bxcommon.messages.bloxroute import short_ids_serializer from bxcommon.messages.bloxroute.abstract_bloxroute_message import AbstractBloxrouteMessage from bxcommon.messages.bloxroute.bloxroute_message_type import BloxrouteMessageType from bxutils.logging.log_level import LogLevel cla...
3398178
from torch import nn import torch class CTCLoss(nn.Module): def __init__(self, blank_idx, reduction='mean'): super().__init__() self.loss_func = torch.nn.CTCLoss(blank=blank_idx, reduction=reduction, zero_infinity=True) def forward(self, pred, args): batch_size = pred.size(0) ...
3398216
import re def run(): dev = __proxy__['junos.conn']() op1 = dev.rpc.request_shell_execute(command="sysctl net.inet.tcp.system_attack_count") obj = re.search('\d+', op1.text) obj1 = int(obj.group()) return ({'fields': {"tcp-ddos-attack": obj1}})
3398286
from key import * import pprint as pp import boto3 s3 = boto3.client('s3', region_name = 'us-east-1', aws_access_key_id = AWS_KEY_ID, aws_secret_access_key = AWS_SECRET) response = s3.upload_file(Filename='upload/0000.jpeg', Key='texting.jpeg', Bucket='shokr-1862020') pp.pprint(r...
3398362
import os import torch import numpy as np import matplotlib import matplotlib.pyplot as plt from qutip import * from plot_helpers import * from model import load import os import matplotlib.ticker as mticker train_end = 2 expo_start = 1.9732 expo_good_end = 6 np.random.seed(0) torch.manual_seed(0) matplotlib.rcParams...
3398407
from lstm_mobility_model.config import Constants class AbstractMixtureDensityBuilder(object): """It transforms the output from neural network into a set of parameters for probability mixtures functions. """ DEFAULT_NUMBER_OF_MIXTURES = 10 def __init__(self, number_of_mixtures=None): "...
3398437
import numpy as np import time def multi_list(a,b): c=[] for i in a: c.append(i*b[i]) return c def multi_array(a,b): c=a*b return c a=range(1000) b=range(1000) time_start=time.time() for i in range(10000): c=multi_list(a,b) time_end=time.time() print('multi list totally cost',time_end...
3398442
class RTMServiceError(RuntimeError): def __init__(self, message, err_data): super(RTMServiceError, self).__init__(message) self.err_data = err_data class RTMService(object): """service of Real Time Message""" def __init__(self, rtm_client): self._rtm_client = rtm_client class R...
3398476
from __future__ import absolute_import import logging from flask import Blueprint, request, abort from huskar_api import settings from huskar_api.extras.rate_limiter import ( check_new_request, RateExceededError) from huskar_api.switch import switch, SWITCH_ENABLE_RATE_LIMITER bp = Blueprint('middlewares.rate_...
3398534
import unittest from sacrerouge.common.testing.util import sacrerouge_command_exists class TestMultiLing2013Subcommand(unittest.TestCase): def test_command_exists(self): assert sacrerouge_command_exists(['setup-dataset', 'multiling2013'])
3398559
from typing import List import matplotlib.pyplot as plt import numbers import numpy as np import pandas as pd from scipy import stats from sklearn.metrics import auc, plot_roc_curve, roc_curve, RocCurveDisplay from sklearn.model_selection import KFold, LeaveOneOut, GroupKFold, LeaveOneGroupOut from sklearn.preprocessin...
3398624
import numpy as np from typing import Optional, NamedTuple, Tuple, Iterable class Point(NamedTuple): x: float y: float class Line(object): def __init__(self, slope: float, intercept: float): self.slope = slope self.intercept = intercept def solve_point(self, x: float = None, y: flo...
3398641
import pytest from authlib.integrations.httpx_client import ( OAuthError, OAuth1Client, SIGNATURE_TYPE_BODY, SIGNATURE_TYPE_QUERY, ) from ..utils import MockDispatch oauth_url = 'https://example.com/oauth' @pytest.mark.asyncio def test_fetch_request_token_via_header(): request_token = {'oauth_tok...
3398660
from datetime import datetime from sqlalchemy import text, literal_column from sqlalchemy.orm import Session from app import schemas from app.models import User, Reaction def get_user(db: Session, item_user: str): return db.query(User).filter(User.slack_id == item_user).first() def get_users(db: Session, year...
3398672
import torch import torch.nn as nn def pad_tensor(input, divide): height_org, width_org = input.shape[2], input.shape[3] if width_org % divide != 0 or height_org % divide != 0: width_res = width_org % divide height_res = height_org % divide if width_res != 0: width_div = d...
3398677
import requests import datetime import pandas as pd from matplotlib import pyplot as plt from matplotlib import dates as mpl_dates import matplotlib.pyplot import seaborn as sns plt.style.use('seaborn') sns.set(font='Franklin Gothic Book', rc={ 'axes.axisbelow':False, 'axes.edgecolor':'lightgrey', 'axes.fac...
3398681
import omegaconf import torch.nn as nn def load_encoder(encoder_cfg, in_channels): if encoder_cfg.type == "cnn3d": from .encoder.cnn3d import CNN3D return CNN3D(in_channels=in_channels, **encoder_cfg.params) elif encoder_cfg.type == "cnn2d": from .encoder.cnn2d import CNN2D r...
3398695
import stk import pymongo from typing import Iterable import itertools class ConstructedMoleculeCreator: def __init__(self): self._num_molecules = 1 def get_molecules(self) -> Iterable[stk.ConstructedMolecule]: while True: self._num_molecules += 1 bb1 = stk.BuildingBl...
3398753
from __future__ import absolute_import from rouge.rouge import FilesRouge, Rouge __version__ = "0.3.0" __all__ = ["FilesRouge", "Rouge"]
3398763
from tabulate import tabulate # from l_03_create_devices import create_devices from util.create_utils import create_devices # --- Main program -------------------------------------------- if __name__ == '__main__': devices = create_devices(num_subnets=5, num_devices=3, random_ip=True) print("\n", tabulate(dev...
3398770
from eth_utils import denoms GAS_EXTCODEHASH_EIP1052 = 400 GAS_SSTORE_EIP1283_NOOP = 200 GAS_SSTORE_EIP1283_INIT = 20000 GAS_SSTORE_EIP1283_CLEAN = 5000 GAS_SSTORE_EIP1283_CLEAR_REFUND = 15000 GAS_SSTORE_EIP1283_RESET_CLEAR_REFUND = 19800 GAS_SSTORE_EIP1283_RESET_REFUND = 4800 EIP1234_BLOCK_REWARD = 2 * denoms.ether...
3398786
from bitmovin.resources import AudioMedia from .generic_media_service import GenericMediaService class Audio(GenericMediaService): def __init__(self, http_client): super().__init__(http_client=http_client, media_type_url='audio', resource_class=AudioMedia...
3398793
from .clean_data import preproc_data all_datasets_ls = [ # # 'adult', # #'airlines', # # 'Amazon_employee_access', # # 'bank-marketing', # # 'Click_prediction_small', # # 'credit-g', # # 'eeg-eye-state', 'electricity', # 'kc1', ...
3398819
from enum import Enum from ._ingenialink import ffi, lib from ingenialink.utils._utils import * from abc import ABC # CANOPEN DTYPES IL_REG_DTYPE_DOMAIN = 15 class REG_DTYPE(Enum): """Data Type.""" U8 = lib.IL_REG_DTYPE_U8 """Unsigned 8-bit integer.""" S8 = lib.IL_REG_DTYPE_S8 """Signed 8-bit i...
3398899
import torch from src.data.utils import TextEncoder import src.data.data as data import src.models.models as models from src.evaluate.sampler import BeamSampler, GreedySampler, TopKSampler from config import settings import utils.utils as utils def load_model_file(model_file): model_stuff = data.load_checkpoin...
3398903
from collections import namedtuple import falcon from builtins import str from builtins import object import structlog from monitorrent.plugin_managers import NotifierManager log = structlog.get_logger() # noinspection PyUnusedLocal class NotifierCollection(object): def __init__(self, notifier_manager): ...
3398937
from songs import Songs, Playlists from wordpool import WordPool from settings import Settings import functions as func import os st = Settings def search_and_save(): pls = Playlists(keyword=st.search_keyword, limit=st.result_limit) # 获得前50项歌单 pls.get_playlists() # 递归下载歌单 pls...
3398959
import logging from typing import List, Optional from hummingbot.connector.exchange.bitfinex.bitfinex_api_user_stream_data_source import BitfinexAPIUserStreamDataSource from hummingbot.connector.exchange.bitfinex.bitfinex_auth import BitfinexAuth from hummingbot.core.data_type.user_stream_tracker import UserStreamTrac...
3398999
import torch import torch.nn as nn class PCCN(nn.Module): """PCCN convolution layer. Implementation from the paper Deep Parametric Convtinuous Convolutional Neural Network (http://openaccess.thecvf.com/content_cvpr_2018/papers/Wang_Deep_Parametric_Continuous_CVPR_2018_paper.pdf) To be used with a `li...
3399079
import clr clr.AddReference('RevitAPI') from Autodesk.Revit.DB import * clr.AddReference("RevitServices") import RevitServices from RevitServices.Persistence import DocumentManager doc = DocumentManager.Instance.CurrentDBDocument items = UnwrapElement(IN[0]) paintedmats = IN[1] elementmats = list() elementareas = lis...
3399088
BASE_URL = 'http://www.alphavantage.co/query' # time period flags INTRADAY = 'I' DAILY = 'D' WEEKLY = 'W' MONTHLY = 'M' # field names OPEN = 'open' HIGH = 'high' LOW = 'low' CLOSE = 'close' VOLUME = 'volume' ADJUSTED_CLOSE = 'adjusted_close' DIVIDEND = 'dividend_amount' SPLIT_COEFFICIENT = 'split_coefficient'
3399089
from generativepy.drawing import make_image from generativepy.color import Color ''' In this example, similar to color.py, we set colours using CSS names. See the color module for a list of colours, or look up "CSS named colours" on the web. ''' def draw(ctx, width, height, frame_no, frame_count): # Set the back...
3399091
from flask import render_template from flask import request from app.settings import config from .blueprint import blueprint from .models import MainCategoryProduct, Product, CategoryProduct from .logger import logger # TODO: Возможно имеет смысл вынести хелперы в отдельный файл def get_categorys(): main_categor...
3399110
import functools from urllib import parse from waterbutler.core import path class BitbucketPathPart(path.WaterButlerPathPart): bitbucket_safe_chars = '~`!@$^&*()_-+={}|[];:,<.>"\' ' DECODE = parse.unquote # TODO: mypy lacks a syntax to define kwargs for callables ENCODE = functools.partial(parse.qu...
3399121
import importlib import subprocess import sys import os import pkg_resources from sqlalchemy import select, and_ def open_database(engine): conn = engine.connect() print("Database Opened") return conn def install(package): # Function to install the given packaged subprocess.run(["pip", "install", ...
3399128
from django.db import models class Category(models.Model): name = models.CharField(max_length=30) parent = models.ForeignKey('Category', on_delete=models.CASCADE, null=True) def __str__(self): return self.name class Expense(models.Model): amount = models.DecimalField(max_digits=10, decimal_...
3399150
import pytest from pycfmodel.model.resources.security_group_ingress import SecurityGroupIngress @pytest.fixture() def security_group_ingress_ipv4_1(): return SecurityGroupIngress( **{ "Type": "AWS::EC2::SecurityGroupIngress", "Properties": { "GroupId": "sg-12341234...
3399191
import numpy as np class cov: def __init__( self, params = None ): self.params = params if self.params is None: self.params = np.log(1) self.nparams = 1 self.sigma2, self.prec = self._trans_params( params ) def get_cov( self, N, params = None ): ''' compute ...
3399209
from LanguagePrinter import LanguagePrinter type_mappings = { 'BinNums.Z': 'int', 'Datatypes.bool': 'bool' } def convert_type(t): global type_mappings res = type_mappings.get(t) if res: return res else: return t InstructionListCode = ''' typedef struct { Instruction ins...
3399229
from __future__ import absolute_import from __future__ import division from __future__ import print_function from builtins import range from builtins import object from .clustcompare import * def _non_sequential_raise(basis): """Ensure that the linear function index of the cluster functions is sane. That is, ...
3399239
from django.conf import settings from django.conf.urls.static import static from django.urls import include, path from django.contrib import admin from django.contrib.sitemaps.views import sitemap from spectator.core.apps import spectator_apps from spectator.core.sitemaps import CreatorSitemap if spectator_apps.is_en...
3399252
from pydantic import BaseSettings class OLBaseSettings(BaseSettings): class Config: # noqa: WPS431 case_sensitive = False
3399254
from shutil import rmtree from os.path import join from contextlib import nested from datetime import datetime, timedelta from mock import patch from jig.tests.testcase import ( RunnerTestCase, PluginTestCase, result_with_hint) from jig.conf import PLUGIN_CHECK_FOR_UPDATES from jig.commands.hints import GIT_REPO_...
3399255
import os # Environment variables SECRET_KEY = os.environ.get('SECRET_KEY', '') IS_HEROKU = os.environ.get('IS_HEROKU', False) FLASK_DEBUG = not IS_HEROKU DATABASE_URL = os.environ.get('DATABASE_URL', '/tmp/profbit.db') SENTRY_PRIVATE_DSN = os.environ.get('SENTRY_PRIVATE_DSN', '') GOOGLE_ANALYTICS_ID = os.environ.get(...
3399262
import unittest import disco.fileutils as fileutils from disco.error import DataError # value far bigger than today's hdds fileutils.MIN_DISK_SPACE = 2**64 class FileutilsTest(unittest.TestCase): def test_ensure_free_space(self): self.assertRaises(DataError, fileutils.ensure_free_space, "/tmp")
3399315
from relogic.components.component import Component from relogic.structures.structure import Structure from typing import List class SRLComponent(Component): """ """ def execute(self, inputs: List[Structure]): counter = 0 expanded_inputs = [] mapping = [] for idx, structure in enumerate(inputs)...
3399324
from distutils.core import setup name = 'pyPaSWAS' setup( #Information about the package name=name, version='0.1.0', description='Python implementation of Smith-Waterman on CUDA', author='<NAME>', author_email='<EMAIL>', url='http://trac.nbic.nl/' + name.lower(), license='', #TODO Prov...
3399344
import os from PIL import Image from easydict import EasyDict as edict from torch.backends import cudnn from config import config, default, dataset_config from solvers import * from data_loaders import * default.network = 'MULTICYCLEGAN' #default.network = 'STARGAN' default.dataset_choice = ['MAKEUP'] #default.datas...
3399362
from scaner.utils import add_metadata import json from flask import current_app @add_metadata('tasks') def search(*args, **kwargs): return {'tasks': current_app.tasks.get_task_list()}, 200 @add_metadata('status') def get(taskId, *args, **kwargs): return {'status': current_app.tasks.get_task_status(taskId)}...
3399407
config = { "version": 1, "controllers": { "con1": { "type": "opx1", "analog_outputs": { 1: {"offset": +0.0}, }, "digital_outputs": {1: {}, 2: {}}, } }, "elements": { "qe1": { "singleInput": {...
3399440
r""" Integration models """ import os from .base import Model from .scglue import AUTO, configure_dataset, SCGLUEModel def load_model(fname: os.PathLike) -> Model: r""" Load model from file Parameters ---------- fname Specifies path to the file """ return Model.load(fname)
3399458
COURSES = { "count": 10000, "next": "https://www.udemy.com/api-2.0/courses/?page=2&page_size=12", "previous": None, "results": [ { "_class": "course", "id": 4314396, "title": "CAREER COACHING FOR YOUR SUCCESS. HOW TO BE A BOSS!", "url": "/course/ca...
3399464
import sys import os from os.path import join as pjoin import subprocess from nose.tools import eq_, ok_ from ...core.test import utils from ...core.test.utils import which, temp_working_dir_fixture, dump from ...core.test.test_build_store import fixture def setup(): global hdist_script, projdir projdir = o...
3399476
from setuptools import setup, find_packages setup(name='multi_script_editor', version='2.1', description='Python editor for multiple platforms', long_description='Python editor for multiple platforms and CG software applications', classifiers=[ 'Development Status :: Release 2.1', ...
3399502
import numpy as np from descarteslabs.common.workflows.utils import masked_stack # Fixtures: foo = np.ma.masked_array( np.array([[1, 2], [3, 4]]), np.array([[True, False], [False, True]]) ) bar = np.ma.masked_array( np.array([[5, 6], [7, 8]]), np.array([[False, False], [True, False]]) ) baz = np.ma.masked_ar...
3399519
import functools import inspect import logging import typing from typing import Any, Optional, Type from dbnd._core.configuration.environ_config import get_dbnd_project_config from dbnd._core.current import current_task_run, get_databand_run, try_get_current_task from dbnd._core.errors import show_exc_info from dbnd....
3399553
from guniflask.annotation import Annotation, AnnotationUtils class MethodDefFilter(Annotation): def add_filter(self, name, args=None): if 'values' not in self: self['values'] = [] self['values'].append({'name': name, 'args': args}) def get_filters(self): if 'values' not in...
3399574
import logging import os import tantivy from tqdm import tqdm class SparseRetrieverFast: def __init__(self, path='sparse_index', load=True): if not os.path.exists(path): os.mkdir(path) schema_builder = tantivy.SchemaBuilder() schema_builder.add_text_field("body", stored=False)...
3399581
import pyecharts.options as opts from pyecharts.charts import Line from pyecharts.faker import Faker c = ( Line() .add_xaxis(Faker.choose()) .add_yaxis("商家A", Faker.values(), is_smooth=True) .add_yaxis("商家B", Faker.values(), is_smooth=True) .set_series_opts( areastyle_opts=opts.AreaStyleOp...
3399589
f = [0, 1, 2, -1, -1, 5, 9, -1, 8, 6] def flip(n): x = 0 while n > 0: a = n % 10 if f[a] == -1: return -1 x += 10 ** (len(str(n)) - 1) * a n /= 10 #print(a, n, x) return x n, s = [int(x) for x in raw_input().split()] nums = [int(x) for x in raw_input().split()] m = ...
3399602
from collections import OrderedDict from django.contrib.auth import get_user_model from django.db import models from django.urls import reverse from rest_framework import serializers from rest_framework.fields import SerializerMethodField from common.utils import full_url from data_import.models import DataFile from...
3399661
from paddlepalm.lr_sched.base_schedualer import Schedualer from paddle import fluid class TriangularSchedualer(Schedualer): """ Implementation of Slanted Triangular learning rate schedual method, more details refer to https://arxiv.org/pdf/1801.06146.pdf . Apply linear warmup of learning rate from 0 to learning_r...
3399662
expected_output = { 'session_count': 1, 'session_id': { 24: { 'global_lock': 'None', 'in_bad_rpcs': '0', 'in_rpcs': '1', 'login_time': '2020-09-29T15:19:54+00:00', 'out_notifications': '0', 'out_rpc_errors': '0', 'source_host': '10.69.35.35', 'tr...
3399670
from pathlib import Path from django.conf import settings from django.core.files.uploadedfile import SimpleUploadedFile from django.test import TestCase from django.urls import reverse from .forms import CommentForm from .models import User, Webpage, Template, Comment USERNAME = 'haha69420' PASSWORD = '<PASSWORD> < ...
3399671
from colorama import Fore, Back, Style from utility import Utility from abstract_analyzer import Analyzer class NVDMatchingAnalyzer(Analyzer): def __init__(self, project): super().__init__(project) def analyze(self, nvd_projects=[]): self.match_dir_to_nvd_project(nvd_projects) def mat...
3399676
import os import json import copy import numpy as np; np.random.seed(0) import matplotlib.pyplot as plt import seaborn as sns; sns.set_theme() cmap = sns.diverging_palette(220, 10, as_cmap=True) order_name_list = ["alphabetical", "alphabetical_reverse", "length", "length_reverse", "no_sort", "no_sort_reverse", "verbat...
3399686
import gzip import sys from collections import defaultdict def readFasta(infile): sequence = '' if '.gz' in infile: with gzip.open(infile) as data: for line in data: if '>' in line: seqname = line.strip().replace('>','') else: sequence += line.strip().replace(' ','') else: with open(infil...
3399689
import torch import torch.nn as nn import torch.nn.functional as F import torchvision import torchvision.transforms as T class VGG(nn.Module): """VGG/Perceptual Loss Parameters ---------- conv_index : str Convolutional layer in VGG model to use as perceptual output """ def __init__(...
3399711
from typing import List from MotionGRU import MotionGRU from SpatiotemporalLSTM import SpatiotemporalLSTM import torch from torch import nn, Tensor # 由于 M 的存在之字形贯穿所有 cell,要保证 M 的 channel 不变,只能所有 layer 隐藏层通道数相同 class MotionRNN(nn.Module): def __init__(self, in_channels: int, hidden_channels_list: List[int], kerne...
3399750
class Node: def __init__(self, val): self.val = val self.left = self.right = None class Solution: def pathSum(self, nums: List[int]) -> int: self.totalSum = 0 root = Node(nums[0] % 10) for num in nums[1:]: depth, position, val = num // 100, (num // 1...
3399757
from cisco_sdwan_policy.BaseObject import BaseObject from cisco_sdwan_policy.Helper.Sequence import Sequence class DataPolicy(BaseObject): def __init__(self,name,description,sequences,default_action=None,id=None,references=None,**kwargs): self.id = id self.description= description self.na...
3399764
from setuptools import setup # read the contents of your README file from os import path this_directory = path.abspath(path.dirname(__file__)) with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='mapextrackt', version='0.4.8.5', packages=[...
3399790
import sys import io import os from itertools import islice from ate_rule_learn import handle_special_cases, write_sentences # Reads the input sentences from the specified file. def get_sentences(file_path): sentences = [] with io.open(file_path, 'r', encoding='utf8') as f: # skipping first line ...
3399803
import pytest from datetime import datetime from jtv2xmltv.parser import parse_titles, parse_schedule def test_correct_jtv_header(): data = b'JTV 3.x TV Program Data\x0A\x0A\x0A' assert parse_titles(data) == [] def test_alternative_jtv_header(): data = b'JTV 3.x TV Program Data\xA0\xA0\xA0' assert p...
3399807
import torch import torch.nn as nn import torch.nn.functional as F __all__ = [ 'CELoss', 'KDLoss', ] class CELoss(nn.Module): '''Cross Entropy Loss''' def __init__(self): super().__init__() def forward(self, stu_pred, label): loss = F.cross_entropy(stu_pred, label) return...
3399836
import glob import json import os import tempfile from aplatam import __version__ from aplatam.build_trainset import CnnTrainsetBuilder def test_cnn_trainset_builder(): builder = CnnTrainsetBuilder( ['tests/fixtures/sen2_20161215_clipped.tif'], 'tests/fixtures/settlements.geojson', size=1...
3399849
from .crb import crb_det_farfield_1d, crb_sto_farfield_1d, crb_stouc_farfield_1d from .mse import ecov_music_1d, ecov_coarray_music_1d
3399852
from typing import Union import numpy as np class Softmax: def __call__(self, x: Union[list, np.ndarray]) -> np.ndarray: e_x = np.exp(x - np.max(x)) return e_x / e_x.sum(axis=0) def gradient(self, x: Union[list, np.ndarray]) -> np.ndarray: p = self.__call__(x) return p * (1 - ...