id
stringlengths
3
8
content
stringlengths
100
981k
1708060
class Solution: def maxSubArray(self, nums: List[int]) -> int: dp[0] = nums[0] for i in range(1, len(nums)): dp[i] = max(nums[i], dp[i-1] + nums[i]) res = -1 for i in range(len(dp)) res = max(res, dp[i]) return res
1708065
from datetime import datetime from django.core.management import BaseCommand from django.db import connection from club.settings import POST_HOTNESS_PERIOD from posts.models.post import Post class Command(BaseCommand): help = "Updates hotness rank" def handle(self, *args, **options): Post.objects.e...
1708070
import requests # Vuln Base Info def info(): return { "author": "cckuailong", "name": '''CMSimple 3.1 - Local File Inclusion''', "description": '''Directory traversal vulnerability in cmsimple/cms.php in CMSimple 3.1, when register_globals is enabled, allows remote attackers to include and...
1708090
def precise(lexer, precise_token, parent_token): # Due to a pygments bug*, custom tokens will look bad # on outside styles. Until it is fixed on upstream, we'll # convey whether the client is using pie style or not # through precise option and return more precise tokens # depending on it's value. ...
1708121
from app import create_app, db from app.models import User application = create_app() @application.shell_context_processor def make_shell_context(): return {"db": db, "User": User} if __name__ == "__main__": application.run(port=5003, debug=True)
1708123
import mobula import mobula.layers as L import numpy as np def go_eltwise(op): a = np.array([1,0,6]).astype(np.float) b = np.array([4,5,3]).astype(np.float) print ("a: ", a) print ("b: ", b) data1 = L.Data(a) data2 = L.Data(b) coeffs = np.array([-1.0,1.2]) l = L.Eltwise([data1,data2], o...
1708125
from typing import List, Optional, Union, cast import requests from eip712_structs import make_domain from eth_account import Account from eth_account.messages import encode_defunct from eth_typing import AnyAddress, ChecksumAddress, HexStr from hexbytes import HexBytes from web3 import Web3 from gnosis.eth import Et...
1708138
import abc import numpy as np import six import os import tensorflow as tf @six.add_metaclass(abc.ABCMeta) class NeuralNetwork(object): """Abstract base class for Neural Network used in policy-value net. Details can be found in https://www.nature.com/articles/nature24270 'Mastering the game of Go wi...
1708142
import socket import json def main(): serversocket = socket.socket() host = "localhost" port = 23456 serversocket.bind((host, port)) serversocket.listen(1) while True: s, addr = serversocket.accept() msg = s.recv(1024).decode("utf-8")#[1:] print(msg) msgJson = ...
1708158
import unittest import os import fv3gfs.wrapper from util import get_default_config, main test_dir = os.path.dirname(os.path.abspath(__file__)) rundir = os.path.join(test_dir, "rundir") class TracerMetadataTests(unittest.TestCase): def test_tracer_index_is_one_based(self): data = fv3gfs.wrapper.get_trace...
1708226
from dataclasses import asdict from functools import wraps import json from protobuf_to_dict import protobuf_to_dict from dacite import from_dict from schemes.graph import GraphNode, GraphRelation from configs.config import logger def raise_customized_error(capture, target): def _raise_customized_error(func): ...
1708249
import copy from membase.helper.cluster_helper import ClusterOperationHelper from couchbase_helper.documentgenerator import BlobGenerator from .xdcrnewbasetests import XDCRNewBaseTest from .xdcrnewbasetests import NodeHelper from .xdcrnewbasetests import Utility, BUCKET_NAME, OPS from remote.remote_util import RemoteM...
1708269
from django.conf import settings from rest_framework import serializers class SearchHashtagsSerializer(serializers.Serializer): query = serializers.CharField(max_length=settings.SEARCH_QUERIES_MAX_LENGTH, required=True) count = serializers.IntegerField( required=False, max_value=10 )
1708322
import numpy as np import pytest from sklearn_extra.robust import ( RobustWeightedClassifier, RobustWeightedRegressor, RobustWeightedKMeans, ) from sklearn.datasets import make_blobs from sklearn.linear_model import SGDClassifier, SGDRegressor, HuberRegressor from sklearn.cluster import KMeans from sklearn...
1708330
from io import StringIO from snowfakery.data_generator import generate class TestFriends: def test_multiple_friends(self, generated_rows): yaml = """ - object: Account - object: Account friends: - object: Contact fields: AccountId: ...
1708368
from __future__ import absolute_import, division, print_function, unicode_literals import os import pathlib import typing from typing import TYPE_CHECKING import numpy as np if TYPE_CHECKING: # pragma: no cover import tensorflow as _tf try: import tensorflow as tf assert tf.__version__[:2] == "2." exc...
1708378
import numpy as np from mcfly.models.base_hyperparameter_generator import generate_base_hyperparameter_set, \ get_regularization def test_regularization_is_float(): """ Regularization should be a float. """ reg = get_regularization(0, 5) assert isinstance(reg, np.float), "Expected different type." def...
1708456
import os import sys import re import operator import json from commands import getoutput from collections import defaultdict import py from dotmap import DotMap import pygal try: # see GroupedBarChart.get_point for why it's needed import scipy except ImportError: scipy = None class SecondsFormatter(pyga...
1708488
import logging from src.commons.big_query.big_query_table_metadata import BigQueryTableMetadata class SLIBackupTableNotSeenByCensusPredicate(object): def __init__(self, big_query, query_specification): self.big_query = big_query self.query_specification = query_specification def is_not_seen...
1708503
import sys class MuninGraph(object): def run(self): cmd_name = None if len(sys.argv) > 1: cmd_name = sys.argv[1] if cmd_name == 'config': self.print_config() else: metrics = self.calculate_metrics() self.print_metrics(metrics) ...
1708504
from .folder import ImageFolder, DatasetFolder from .vision import VisionDataset __all__ = ('ImageFolder', 'DatasetFolder', 'VisionDataset')
1708527
import rest_framework_filters as filters from metaci.build.models import Build from metaci.build.models import BuildFlow from metaci.build.models import Rebuild from metaci.cumulusci.filters import OrgRelatedFilter from metaci.cumulusci.filters import ScratchOrgInstanceRelatedFilter from metaci.cumulusci.models import ...
1708533
import quiver import torch world_size = torch.cuda.device_count() device_list = list(range(world_size)) numa_topo = quiver.NumaTopo(device_list) numa_topo.info()
1708545
import argparse import os import librosa from utils.utils import calc_snr, calc_lsd from generating import AudioGenerator if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--input_folder', help='Folder of trained model', type=str, required=True) parser.add_argument('--lr_si...
1708557
from os import mkdir from shutil import copy2, rmtree from os.path import basename, join from json import load, dumps from file_handler import read_data from generator import get_dim def start(event_name, template, csv): try: mkdir("UI/temp") except: pass for x in [(template, basename(temp...
1708563
import jinja2 from localstack.utils.common import short_uid from localstack.utils.generic.wait_utils import wait_until from tests.integration.cloudformation.test_cloudformation_changesets import load_template_raw def test_delete_role_detaches_role_policy( cfn_client, iam_client, cleanup_stacks, clean...
1708599
from malwareconfig.common import Decoder from malwareconfig.common import string_printable class LuxNet(Decoder): decoder_name = "LuxNet" decoder__version = 1 decoder_author = "@kevthehermit" decoder_description = "Luxnet RAT Decoder" def __init__(self): self.config = {} def get_con...
1708617
import numpy as np class NetworkInput(object): def __init__(self, path, input_shape, num_labels): self.path = path self.num_labels = num_labels self.batch_start = 0 self.epochs_completed = 0 self.input_shape = input_shape self.cache = np.array([]) self.cache_...
1708670
from torchvision.transforms.functional import InterpolationMode import os from PIL import Image import numpy as np from collections import OrderedDict from tqdm.auto import tqdm import torchvision import torch def to_numpy(x): x_ = np.array(x) x_ = x_.astype(np.float32) return x_ def get_image_transfo...
1708677
import FWCore.ParameterSet.Config as cms from RecoEcal.EgammaClusterProducers.hybridSuperClusters_cfi import * from RecoEcal.EgammaClusterProducers.multi5x5BasicClusters_cfi import * EleIsoEcalFromHitsExtractorBlock = cms.PSet( ComponentName = cms.string('EgammaRecHitExtractor'), DepositLabel = cms.untracked....
1708692
import os import sys import numpy as np from .config import config class Model: def __init__(self, n_feature, n_tag): self.n_tag = n_tag self.n_feature = n_feature self.n_transition_feature = n_tag * (n_feature + n_tag) if config.random: self.w = np.random.random(size...
1708700
import unittest import subprocess class TestJupyterNbconvert(unittest.TestCase): def test_nbconvert(self): result = subprocess.run([ 'jupyter', 'nbconvert', '--to', 'notebook', '--template', '/opt/kaggle/nbconvert-extensions.tpl', ...
1708709
def my_function(a, b): return a + b functions = [my_function] print(functions[0]) print(functions[0](1, 2))
1708722
import unittest from media_management_scripts.convert import convert_config_from_ns, convert_with_config, combine from media_management_scripts.support.combine_all import combine_all, get_combinable_files from tests import create_test_video, VideoDefinition, AudioDefition, AudioCodec, AudioChannelName from tempfile im...
1708728
import os.path from fabric.state import env def run_capture(out = []): """Helper for retriving env.run issued commands""" return lambda command, *args, **kwargs: out.append(command.strip()) class CdPlaceholder(object): def __enter__(self, *args, **kwargs): return True def __exit__(self, typ...
1708740
import json import logging from abc import abstractmethod from json import dumps as json_dumps from typing import List, Callable, Any, Optional from inoft_vocal_framework.dummy_object import DummyObject from inoft_vocal_framework.exceptions import raise_if_value_not_in_list, raise_if_variable_not_expected_type from i...
1708753
from abc import ABCMeta, abstractmethod class Goal: __metaclass__ = ABCMeta INACTIVE = 0 ACTIVE = 1 COMPLETED = 2 FAILED = 3 def __init__(self, owner): self.owner = owner self.status = self.INACTIVE @abstractmethod def activate(self): pass ...
1708769
from __future__ import absolute_import from .._hook import import_hook @import_hook(__name__) def value_processor(name, raw_name, raw_value): import json try: value = json.loads(raw_value) except ValueError: error_msg = ( '{0}={1!r} found but {1!r} is not a valid json value.\n...
1708823
from configparser import ConfigParser import os, sys from ant.core import log from BtAtsPowerCalculator import BtAtsPowerCalculator from CycleOpsFluid2PowerCalculator import CycleOpsFluid2PowerCalculator from EliteNovoForceS3PowerCalculator import EliteNovoForceS3PowerCalculator from GenericFluidPowerCalculator import...
1708830
class IDisposable: """ Defines a method to release allocated resources. """ def Dispose(self): """ Dispose(self: IDisposable) Performs application-defined tasks associated with freeing,releasing,or resetting unmanaged resources. """ pass def __enter__(self,*args): """ __enter__(sel...
1708831
from indy_node.test.did.conftest import nym_get from indy_node.test.helper import sdk_rotate_verkey def testAddDidWithoutAVerkey(nym_empty_vk): pass def testRetrieveEmptyVerkey(looper, tconf, nodeSet, sdk_pool_handle, sdk_wallet_trustee, nym_empty_vk): nwh, ndid = nym_empty_vk resp_data = nym_get(looper...
1708858
import unittest import super_gradients from super_gradients.training import MultiGPUMode from super_gradients.training import SgModel from super_gradients.training.datasets.dataset_interfaces.dataset_interface import ClassificationTestDatasetInterface from super_gradients.training.metrics import Accuracy import os impo...
1708864
from flask import Blueprint, current_app, request, abort, json import pusher as _pusher from pusher.signature import sign, verify try: import flask_jsonpify except ImportError: # pragma: no cover from flask import jsonify else: jsonify = flask_jsonpify.jsonify flask_jsonpify__dumps = flask_jsonpify.__...
1708866
from django.db import models from django.contrib.auth.models import User class Project(models.Model): name = models.CharField(max_length=128) description = models.TextField(default="", blank=True) members = models.ManyToManyField(User, through="Membership") created_by = models.ForeignKey(User, on_dele...
1708869
from django.contrib.auth.models import User from django_tables2 import tables, TemplateColumn class UserByObjectTable(tables.Table): actions = TemplateColumn(template_name='custom_columns/user_by_group_actions.html', orderable=False) role = TemplateColumn(template_name='custom_columns/role_object.html', order...
1708877
from django.contrib import messages from django.contrib.auth.mixins import LoginRequiredMixin from django.shortcuts import redirect, render from django.urls import reverse from django.views.generic import DetailView, ListView from django.views.generic.edit import CreateView, UpdateView from dfirtrack_main.forms import...
1708906
import sys import math import numpy as np try: from scipy.spatial import cKDTree as kd_tree except ImportError: from scipy.spatial import cKDTree as kd_tree import maya.OpenMaya as om import logging_util # import progress_bar class GeoCache(object): """ container for cached triangulated geometry ...
1708929
from django.conf.urls import patterns, include, url urlpatterns = patterns('exam.views', url(r'^$', 'index'), url(r'^login/$', 'user_login'), url(r'^quizzes/$','quizlist_user'), url(r'^results/$','results_user'), url(r'^start/$', 'start'), url(r'^start/(?P<questionpaper_id>\d+)/$','start'), ...
1708984
from wrapper import * from goto import * @with_goto def all_code(): clear_all_execution() exec_sql('CREATE DATABASE IF NOT EXISTS test;') exec_sql('USE test;') exec_sql( 'create table tbcalifica' '( iditem integer not null primary key,' 'item varchar(150) not null,' ...
1708987
from django.test import TestCase from . import country class TestCountry(TestCase): def test_activate_deactivate_country(self): self.assertIsNone(country.get_country()) country.activate('us') self.assertEqual(country.get_country(), 'us') country.activate('ca') self.assert...
1708995
import os from azure.cognitiveservices.search.autosuggest import AutoSuggestClient from msrest.authentication import CognitiveServicesCredentials ''' Microsoft Azure Cognitive Services - Bing Autosuggest - Get Search Suggestions Uses the general Cognitive Services key/endpoint. It's used when you want to combine ma...
1709003
from cospar.tool._clone import * from cospar.tool._gene import * from cospar.tool._map import * from cospar.tool._utils import *
1709055
import datetime from decimal import Decimal import pytest from pymssql import _pymssql from pydapper import connect from pydapper import using from pydapper.mssql.pymssql import PymssqlCommands from tests.suites.commands import ExecuteScalarTestSuite from tests.suites.commands import ExecuteTestSuite from tests.suite...
1709058
import itertools import dask.dataframe as dd import dask.dataframe.groupby as ddgb import numpy as np import pandas import toolz from pandas import isnull import ibis import ibis.expr.operations as ops from ibis.backends.pandas.core import integer_types, scalar_types from ibis.backends.pandas.execution.strings import...
1709064
import os import random listdir = os.listdir('/media/dsg3/datasets/SIXray/Annotation') test = random.sample(listdir, 200) train = [x for x in listdir if x not in test] with open('dataset-train.txt', 'w') as f: for item in train: f.writelines('{0}\n'.format(os.path.splitext(item)[0])) w...
1709072
import re import sublime from ..logging import logger from ..view import MdeTextCommand class MdeChangeHeadingsLevelCommand(MdeTextCommand): """ The `mde_change_headings_level` command modifies headings levels to an absolute or by a relative value. 1. Carets are moved to the beginning of each header...
1709080
import os from setuptools import setup, find_packages def read(fname): try: with open(os.path.join(os.path.dirname(__file__), fname)) as fh: return fh.read() except IOError: return '' requirements = read('REQUIREMENTS').splitlines() tests_requirements = read('REQUIREMENTS-TESTS')....
1709101
from functools import wraps from primehub.utils import reject_action from primehub.utils.decorators import __requires_permission__, logger, __command_groups__ def has_permission_flag(cmd_args: dict): k = "{}.{}".format(cmd_args['module'], cmd_args['func']) if k in __requires_permission__: return True...
1709103
import torch import numpy as np from tqdm import tqdm import time from PIL import Image import os from im2mesh.common import ( arange_pixels, transform_to_camera_space) class Renderer(object): ''' Render class for DVR. It provides functions to render the representation. Args: model (nn.Modu...
1709147
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import numpy as np from tqdm import tqdm from abc import ABCMeta, abstractmethod import paddle import paddle.nn as nn from paddle.io import DataLoader from paddlemm.models import CMML, ...
1709150
class AppearanceAssetElement(Element,IDisposable): """ An element that represents an appearance asset for use in composing material definitions. """ @staticmethod def Create(document,name,asset): """ Create(document: Document,name: str,asset: Asset) -> AppearanceAssetElement Creates a new Appear...
1709186
import math import easing_functions as ef from fontTools.misc.bezierTools import splitCubic, splitLine from typing import List eases = dict( cei=ef.CubicEaseIn, ceo=ef.CubicEaseOut, ceio=ef.CubicEaseInOut, qei=ef.QuadEaseIn, qeo=ef.QuadEaseOut, qeio=ef.QuadEaseInOut, eei=ef.ExponentialEase...
1709192
class TestFunctional: def test_create_domain(self, client): headers = {"X-Api-Key": "123"} # create user data = {"email": "<EMAIL>"} post_res = client.post("/api/user/add", data=data, headers=headers) json_data = post_res.get_json() user_id = json_data["data"]["id"] ...
1709211
import numpy as np #this is not an efficient implementation. just for testing! def dual_contouring_47_test(int_grid, float_grid): all_vertices = [] all_triangles = [] int_grid = np.squeeze(int_grid) dimx,dimy,dimz = int_grid.shape vertices_grid = np.full([dimx,dimy,dimz], -1, np.int32) #all ...
1709253
import os import os.path import torch from utils.data_aug import Lighting from torchvision import datasets, transforms class Dataloder(): def __init__(self, config): normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) tra...
1709261
def c_star(x, β, γ): return (1 - β ** (1/γ)) * x def v_star(x, β, γ): return (1 - β**(1 / γ))**(-γ) * (x**(1-γ) / (1-γ))
1709388
import time import sys from sdk.actions import * if __name__ == "__main__": print_all_domains("0lt017548f8774f9602b4e25743050d3a8ab37f1341") sys.exit(-1) print get_domain_on_sale()
1709414
from __future__ import print_function import digdag def echo_params(): print('digdag params') for k, v in digdag.env.params.items(): print(k, v)
1709422
import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'openwisp2.settings') app = Celery('openwisp2') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() {% if openwisp2_django_celery_logging %} from celery.signal...
1709423
from util.observe import Observable from util.primitives.funcs import do class SlotsSavable(object): ''' Prereqs: 1) use slots 2) only store persistent information in slots 3) child objects stored in slots must also be SlotSavable (or pickleable) ''' def __getstate__(self): return...
1709473
from django.contrib.auth.models import User from rest_framework.test import APITestCase from rest_framework.reverse import reverse from rest_framework import status from rest_api.models import Repo from datetime import datetime from rest_api.tests.assertors import RepoAssertorNested, RepoAssertor from rest_api.tests.co...
1709540
from unittest.mock import MagicMock import pytest import numpy as np import scipy as sp import scipy.stats import tensorflow as tf from decompose.likelihoods.normal2dLikelihood import Normal2dLikelihood from decompose.tests.fixtures import device, dtype from decompose.distributions.distribution import UpdateType @py...
1709560
from sacrebleu import corpus_bleu, TOKENIZERS, DEFAULT_TOKENIZER from sumeval.metrics.lang.base_lang import BaseLang from sumeval.metrics.lang import get_lang class BLEUCalculator(): def __init__(self, smooth_method="floor", smooth_value=0.01, lowercase=False, use_effective_orde...
1709595
from masonite.mail import Mailable class __class__(Mailable): def build(self): return ( self.to("<EMAIL>") .subject("Masonite 4") .from_("<EMAIL>") .text("Hello from Masonite!") .html("<h1>Hello from Masonite!</h1>") )
1709619
import dask.dataframe as dd from hypernets.tabular import sklearn_ex as skex, dask_ex as dex, get_tool_box from hypernets.tabular.cache import cache, CacheCallback from hypernets.tabular.datasets import dsutils from hypernets.utils import Counter class CacheCounter(CacheCallback): def __init__(self): supe...
1709651
from CGATReport.Tracker import * class SpeciesCount(TrackerSQL): def __call__(self, track, slice=None): ''' return the number of reference genomes that are aligned to ''' genomes = self.execute( """SELECT count(*) FROM species_present_fa""").fetchone()[0] ...
1709677
import pytest import numpy as np from pytest import raises from flare.struc import Structure from flare.utils.parameter_helper import ParameterHelper from flare.parameters import Parameters def test_initialization(): """ simplest senario """ pm = ParameterHelper( kernels=["twobody", "threebo...
1709727
import pathlib import pytest from dotenv import load_dotenv from app import create_app from app.models import model def clean_users(): # removing users will remove everything # since all data linked into it users = model.get_all("user") for user in users: user_id = user["id"] model.d...
1709749
import torch from torch import nn class LabelSmoothing(nn.Module): def __init__(self, size, smoothing=0.0): super(LabelSmoothing, self).__init__() self.criterion = nn.KLDivLoss(reduction='mean') self.Logsoftmax = nn.LogSoftmax(dim = 0) self.confidence = 1.0 - smoothing self....
1709753
import io from setuptools import setup, find_packages def readme(): with io.open('README.md', encoding='utf-8') as f: return f.read() setup( name="marketsimulator", version="0.0.1", author="<NAME> and <NAME>", author_email='<EMAIL>', license='MIT License', description="Realistic m...
1709754
import os import json import logging import json logging = logging.getLogger(__name__) class ProjectSettings: art_dir: str assets_dir: str ART_DIR = "art_dir" ASSETS_DIR = "assets_dir" PROJECT_ROOT_FILE_NAME = ".rafx_project" def find_dir_containing_file_recursing_upwards(current_path, file_name): if no...
1709765
from spaceone.core.error import * class ERROR_USER_STATUS_CHECK_FAILURE(ERROR_BASE): _message = 'A user "{user_id}" status is not ENABLED.' class ERROR_EXTERNAL_USER_NOT_ALLOWED_API_USER(ERROR_INVALID_ARGUMENT): _message = 'External user cannot be created with the API_USER type.' class ERROR_NOT_ALLOWED_E...
1709778
from typing import Any, Dict, Optional from airflow.providers.http.sensors.http import HttpSensor from airflow.utils.context import Context from astronomer.providers.http.triggers.http import HttpTrigger class HttpSensorAsync(HttpSensor): """ Executes a HTTP GET statement and returns False on failure caused...
1709797
from IPython.display import Latex, display from nbconvert.filters.pandoc import convert_pandoc def latex(text, color="", **kwargs): """print in latex""" if color: text = "\\textcolor{%s}{%s}" % (color, text) return Latex(text + "\n", **kwargs) def print(text, **kwargs): """wrapper around pri...
1709822
from __future__ import division import numpy as np from numpy import pi from ..Contour import Contour from ..Paths import ComplexArc from .Annulus import Annulus class Circle(Contour): """ A positively oriented circle in the complex plane. Parameters ---------- center : complex The center of the circle. radi...
1709832
import manta_lab as ml from manta_lab.tuning.internal import FunctionAgent, ProgramAgent logger = None class AgentError(Exception): pass def program_agent(api, tune_id, function, entity=None, project=None, count=None): ProgramAgent return def function_agent(api, tune_id, function, entity=None, projec...
1709864
import json import socket from typing import Optional, Any, Mapping, Callable, Type, Tuple import requests from urlobject import URLObject from urlobject.path import URLPath from .common import translate_dict_func def get_host_ip() -> Optional[str]: s = None try: # s = socket.socket(socket.AF_INET, ...
1709885
class Solution: """ @param nums: @param sub: @return: return a Integer array """ def SimpleQueries(self, nums, sub): # write your code here if len(sub) == 0: return [] if len(nums) == 0: return [0 for _ in range(len(sub))] # O(n logn) ...
1709906
import random class Fish(): def __init__(self, name, color, gender, species, weight): self.name = name self.color = color self.gender = gender self.species = species self.weight = weight self.age = 0 self.stamina = "low" if random.randint(0,1) == 0 else "...
1709926
from django.urls import path from system.views import login_view, UserPasswordUpdateView, logout_view, UserInfo, UserLogout,Menu app_name = "system" urlpatterns = [ path('login', login_view, name="login"), path('password_update', UserPasswordUpdateView.as_view(), name="password_update"), path('logout', lo...
1709992
from __future__ import print_function from __future__ import absolute_import from __future__ import division import os import json import glob import h5py import numpy as np import pickle from PIL import Image, ImageOps import torch from torchmeta.utils.data.task import Task, ConcatTask, SubsetTask from collections i...
1710028
from __future__ import print_function # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Versio...
1710080
import datetime from my_app import db class Product(db.Document): created_at = db.DateTimeField( default=datetime.datetime.now, required=True ) key = db.StringField(max_length=255, required=True) name = db.StringField(max_length=255, required=True) price = db.DecimalField() def __repr...
1710088
import unittest import zserio from testutils import getZserioApi class VarSizeRangeCheckTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.api = getZserioApi(__file__, "with_range_check_code.zs", extraArgs=["-withRangeCheckCode"]).varsize_range_check def...
1710101
from gen.javaLabeled.JavaLexer import JavaLexer try: import understand as und except ImportError as e: print(e) from antlr4 import * from antlr4.TokenStreamRewriter import TokenStreamRewriter from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled from gen.javaLabeled.JavaParserLabeledListener import...
1710118
import sys import pytest from konfetti import Konfig from konfetti.exceptions import ForbiddenOverrideError pytestmark = [pytest.mark.usefixtures("settings")] skip_if_py2 = pytest.mark.skipif(sys.version_info[0] == 2, reason="Async syntax is not supported on Python 2.") def test_override_function(testdir): "...
1710121
from utils import run_with_curio @run_with_curio async def test_verify(httpbin_secure): pass @run_with_curio async def test_cert(httpbin_secure): pass
1710125
import sys import os import subprocess import numpy import pyigl as igl from utils.iglhelpers import e2p, p2e from utils import my_utils current_frame = 0 def sample_more_encoded_displacements(encoded_displacements, num_extra_per_pose=10): max_diff = numpy.zeros(encoded_displacements.shape[1]) for i in ran...
1710140
import unittest from contextlib import contextmanager import pytest from flask import Flask from flask_mailman import Mail class TestCase(unittest.TestCase): TESTING = True MAIL_DEFAULT_SENDER = "<EMAIL>" def setUp(self): self.app = Flask(__name__) self.app.config.from_object(self) ...
1710148
import unittest from broca.preprocess import BasicCleaner, HTMLCleaner class PreProcessTests(unittest.TestCase): def test_clean(self): doc = ''' Goats are like mushrooms. If you shoot a duck, I'm scared of toasters. My site's are https://google.com. ''' expected_doc = ''' g...