id
stringlengths
3
8
content
stringlengths
100
981k
3225327
from django.template.base import Template, TemplateDoesNotExist class Loader(object): is_usable = False # Only used to raise a deprecation warning. Remove in Django 2.0. _accepts_engine_in_init = True def __init__(self, engine): self.engine = engine def __call__(self, template_name, temp...
3225368
from shaape.drawable import Drawable from shaape.style import Style import nose import unittest from nose.tools import * class TestDrawable(unittest.TestCase): def test_init(self): drawable = Drawable() assert type(drawable.style()) == Style def test_style(self): drawable = Drawable()...
3225370
import models import util.validation from database import db_txn from linkr import db from util.exception import * @db_txn def add_link(alias, outgoing_url, password=<PASSWORD>, user_id=None, require_recaptcha=False): """ Add a new link to the database after performing necessary input validation. :param ...
3225376
import os from tqdm import tqdm import torch import torch.nn as nn import torch.optim as optim import torch.backends.cudnn as cudnn class PairFM(nn.Module): def __init__(self, user_num, item_num, factors=84, epochs=20, lr=0....
3225379
from AL import usdmaya from pxr import Tf class UnknownTypeTranslator(usdmaya.TranslatorBase): def __init__(self): usdmaya.TranslatorBase.__init__(self) def initialize(self): return True # return the scheam type this class translates def getTranslatedType(self): ret...
3225395
import sys from .__init__ import pyptexmain if __name__ == "__main__": # execute only if run as a script pyptexmain(sys.argv)
3225419
from bitmovin_api_sdk.encoding.encodings.muxings.progressive_ts.drm.fairplay.customdata.customdata_api import CustomdataApi
3225453
import os import tempfile import unittest import logging from pyidf import ValidationLevel import pyidf from pyidf.idf import IDF from pyidf.hvac_design_objects import SizingSystem log = logging.getLogger(__name__) class TestSizingSystem(unittest.TestCase): def setUp(self): self.fd, self.path = tempfile....
3225456
from typing import Optional from torch import nn from torch.nn import functional as F from ..ff import FF class SpeechLSTM(nn.Module): """A bidirectional LSTM encoder with subsampling for speech features. The number of LSTM layers is defined by the `layers` argument, i.e. `1_1_2_2_1_1` denotes 6 LSTM l...
3225503
from vmaf.config import VmafConfig dataset_name = 'test_image' yuv_fmt = 'yuv444p' ref_videos = [ {'content_id': 0, 'content_name': '100007', 'height': 321, 'path': VmafConfig.test_resource_path('test_image_yuv', '100007.yuv'), 'width': 481}, {'content_id': 1, 'content_name': '100039', 'height': 321, ...
3225504
from functools import cached_property from typing import Optional from pydantic import Field, SecretStr, validator from .base import BaseCustomSettings class RegistrySettings(BaseCustomSettings): REGISTRY_AUTH: bool = Field(..., description="do registry authentication") REGISTRY_PATH: Optional[str] = Field...
3225547
from bresenham import bresenham from scipy.spatial import Voronoi import numpy as np from queue import PriorityQueue import networkx as nx def closest_node(graph, current_position): ''' Compute the closest node in the graph to the current position ''' closest_node = None dist = 100000 xy_posit...
3225555
import torch import math import numpy as np class LabelGuessor(object): def __init__(self, thresh): self.thresh = thresh def __call__(self, model, ims, balance, delT): org_state = { k: v.clone().detach() for k, v in model.state_dict().items() } is_train...
3225583
from __future__ import print_function import itertools from PhysicsTools.Heppy.analyzers.core.VertexHistograms import VertexHistograms from PhysicsTools.Heppy.analyzers.core.Analyzer import Analyzer from PhysicsTools.Heppy.analyzers.core.AutoHandle import AutoHandle from PhysicsTools.HeppyCore.statistics.average impor...
3225604
import math from collections import defaultdict import bisect import numpy as np from unittest.mock import MagicMock from mmdet.datasets import (ClassBalancedDataset, ConcatDataset, CustomDataset, MultiImageMixDataset, RepeatDataset) def test_dataset_wrapper(): CustomDataset.load_ann...
3225625
from __future__ import division, unicode_literals, print_function, absolute_import import numpy as np import traitlets as tl from podpac.core.node import NodeException from podpac.core.units import UnitsDataArray from podpac.core.utils import common_doc from podpac.core.compositor.compositor import COMMON_COMPOSITOR_...
3225662
import sublime from . import emmet_sublime as emmet from . import syntax def split_join_tag(view: sublime.View, edit: sublime.Edit): for sel in view.sel(): pt = sel.begin() syntax_name = syntax.from_pos(view, pt) xml = syntax.is_xml(syntax_name) tag = emmet.get_tag_context(view, pt,...
3225713
import discord, sqlite3, asyncio from discord.ext import commands from discord_slash import cog_ext, ButtonStyle from discord_slash.utils.manage_commands import create_option from discord_slash.utils.manage_components import * class Slash(commands.Cog): def __init__(self, bot): self.bot = bot @cog_ext...
3225760
import pytest from allennlp.data.tokenizers import WhitespaceTokenizer from allennlp.data.token_indexers import SingleIdTokenIndexer from tests import FIXTURES_ROOT import re from typing import List from allennlp_models.rc.dataset_readers.record_reader import RecordTaskReader """ Tests for the ReCoRD reader from Supe...
3225772
from .feed import Feed, RawFeed, UserFeed, FeedStatus from .feed_creation import FeedCreation, FeedUrlMap from .union_feed import FeedUnionId, UnionFeed, FeedImportItem from .story import Story, UserStory from .feed_story_stat import FeedStoryStat from .union_story import UnionStory, StoryUnionId from .registery import...
3225782
from __future__ import absolute_import, division, print_function, unicode_literals from .inertia_tensor import inertia_tensor_per_object from .tensor_derived_quantities import *
3225787
import torch import torch.nn as nn from src.utils.custom_typing import EncoderOutput class BaseEncoder(nn.Module): def __init__( self, img_size: int, in_channels: int, num_filters: int, kernel_size: int, repr_dim: int, ): """Encoder to extract the repres...
3225822
import asyncio import logging import time import typing import ydb from ydb import issues, settings, table from ydb.table import ( BaseSession, BaseTableClient, _scan_query_request_factory, _wrap_scan_query_response, BaseTxContext, ) from . import _utilities from ydb import _apis, _session_impl ...
3225832
import inspect from collections import OrderedDict from typing import Callable, Any, Union, Iterable, Dict, Tuple from typish._types import Empty from typish.classes._cls_dict import ClsDict class ClsFunction: """ ClsDict is a callable that takes a ClsDict or a dict. When called, it uses the first argume...
3225862
from functools import wraps from typing import Any, Callable, Optional, Union, no_type_check from pydantic import errors from pydantic_yaml.compat.types import YamlStr from semver import VersionInfo __all__ = ["SemVer"] Comparator = Callable[["SemVer", Any], bool] def _comparator(operator: Comparator) -> Comparat...
3225895
from unittest import mock from django.db import connections from django.test import TestCase, TransactionTestCase, override_settings class TestSerializedRollbackInhibitsPostMigrate(TransactionTestCase): """ TransactionTestCase._fixture_teardown() inhibits the post_migrate signal for test classes with ser...
3225948
from typing import Dict, List, Union import unittest from rating.manager.bisect import get_closest_configs_bisect import yaml def generate_test_from_timestamp(timestamp: int) -> Union[int, Dict, Dict]: """Generate multiple configurations procedurally, to be tested afterward.""" rules = """ rules...
3225980
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import torch.optim as optim import models import util if torch.cuda.is_available(): device = torch.device('cuda') else: device = torch.device('cpu') def squared_l2_norm(x): flattened = x.view(x.unsqueeze...
3226028
import pytest from ceph_deploy.cli import get_parser from ceph_deploy.tests.util import assert_too_few_arguments class TestParserPkg(object): def setup(self): self.parser = get_parser() def test_pkg_help(self, capsys): with pytest.raises(SystemExit): self.parser.parse_args('pkg ...
3226046
import os import re from enum import Enum from pathlib import Path from typing import Union, Optional from typing import TYPE_CHECKING from pydantic import BaseSettings, Field from typhoon import local_config if TYPE_CHECKING: from typhoon.core.metadata_store_interface import MetadataStoreInterface def _join_u...
3226079
import asyncio import pytest from dask_gateway_server.workqueue import WorkQueue, Backoff, WorkQueueClosed from dask_gateway_server.utils import cancel_task def test_backoff(): backoff = Backoff(base_delay=0.5, max_delay=5) assert backoff.failures("foo") == 0 assert backoff.backoff("foo") == 0.5 a...
3226085
from . import database as database def update(params): try: database.update('insert or replace into settings(key, value_1, value_2) values ("' + params['setting'] + '", "' + params['value_1'] + '", "' + params['value_2'] + '")') return {'class': 'alert-success', 'message': 'Settings updated successfully.'} ...
3226094
from __future__ import annotations import logging from datetime import datetime, timedelta from time import gmtime, strftime from typing import Any, Dict, Optional, Sequence, Tuple, Union from wyze_sdk.errors import WyzeRequestError from wyze_sdk.models import datetime_to_epoch from wyze_sdk.models.devices import Dev...
3226133
from django.contrib import admin from strategy.models import Strategy, Order, Symbol from strategy.utils import get_model_field_names @admin.register(Symbol) class SymbolAdmin(admin.ModelAdmin): list_display = get_model_field_names(Symbol) list_filter = ('base_asset', 'quote_asset') search_fields = ('nam...
3226136
from __future__ import unicode_literals from __future__ import print_function from ...command import SubCommand from ...wsgi import WSGIApplication from ...console import Cell from ...template.moyatemplates import Template from datetime import datetime from fs.path import join import os.path from collections import ...
3226174
import os import torch import cPickle import tarfile import misc_data_util.transforms as trans from zipfile import ZipFile from misc_data_util.url_save import save def load_dataset(data_config): """ Downloads and loads a variety of standard benchmark sequence datasets. Arguments: data_config (dict...
3226200
PATH_NONE = "NONE" PATH_UNION = "UNION" PATH_INTER = "INTERSECT" PATH_EXCEPT = "EXCEPT" PATH_WHERE = "WHERE" PATH_HAVING = "HAVING" PATH_PAR = "PARALLEL" # To represent the multiple selection clauses in a single WHERE clause. VEC_AGGREGATORS = [ 'none', 'max', 'min', 'count', 'sum', 'avg' ] VEC_OPERATORS ...
3226203
import sys import taichi as ti sys.path.append('../tests/python/') from bls_test_template import bls_test_template ti.init(arch=ti.gpu, print_ir=True, kernel_profiler=True, demote_dense_struct_fors=False) stencil = [(0, 0), (0, -1), (0, 1), (-1, 0), (1, 0)] bls_test_template(2, ...
3226215
from sklearn.preprocessing import Normalizer scaler = Normalizer().fit(X_train) normalized_X = scaler.transform(X_train) normalized_X_test = scaler.transform(X_test)
3226237
import datetime from wagtail.contrib.routable_page.templatetags.wagtailroutablepage_tags import ( # noqa: B950 routablepageurl, ) import jinja2 from dateutil import parser from jinja2.ext import Extension from jinja2.filters import do_mark_safe from regdown import regdown as regdown_func def ap_date(date): ...
3226324
from lib.base import QualysBaseAction __all__ = [ 'ListReportsAction' ] class ListReportsAction(QualysBaseAction): def run(self): reports = self.connection.listReports() return self.resultsets.formatter(reports)
3226326
def test(): assert ( "doc1.similarity(doc2)" or "doc2.similarity(doc1)" in __solution__ ), "Compares-tu la similarité entre les deux docs ?" assert ( 0 <= float(similarity) <= 1 ), "La valeur de similarité doit être un nombre flottant. L'as-tu calculé correctement ?" __msg__.good("Bi...
3226393
import ffmpeg import argparse import sys import os def to_int(a, rel_to): ''' Converts string to integer. If string contains "%" it converts it to a float and multiplies by rel_to EG: 50% -> 0.5*rel_to ''' if type(a) == int: return a else: if '%' in a: return i...
3226413
import torch import torch.nn as nn import torch.nn.functional as F import math def conv(in_planes, out_planes, kernel_size=3, stride=2, padding=1, dilation=1, bn_layer=False, bias=True): if bn_layer: return nn.Sequential( nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, padding=paddin...
3226416
import torch from torch.autograd import Variable import itertools from util.image_pool import ImagePool from .base_model import BaseModel from . import networks import scipy.io as sio import numpy as np class DecGANModel(BaseModel): def name(self): return 'DecGANModel' def initialize(self, opt): ...
3226417
import torch.nn as nn import torch.nn.utils.spectral_norm as SN import torchvision import torch def conv_block(in_channels, out_channels, kernel_size, stride, padding=1, bias=True, activation=nn.ReLU(), transpose=False, no_BN=False, all_tanh=False, spec_norm=False): if(transpose): block = [nn.ConvTranspo...
3226475
from django_cradmin.viewhelpers.listbuilder import base class RowList(base.List): def get_test_css_class_suffixes_list(self): css_class_suffixes = super(RowList, self).get_test_css_class_suffixes_list() css_class_suffixes.append('cradmin-listbuilder-list') return css_class_suffixes de...
3226491
import pytest import datetime from pupa.scrape import Event def event_obj(): e = Event( name="get-together", start_date=datetime.datetime.utcnow().isoformat().split('.')[0] + 'Z', location_name="Joe's Place", ) e.add_source(url='http://example.com/foobar') return e def test_b...
3226493
import numpy as np import pytest import pandas as pd import pandas._testing as tm @pytest.mark.parametrize("align_axis", [0, 1, "index", "columns"]) def test_compare_axis(align_axis): # GH#30429 df = pd.DataFrame( {"col1": ["a", "b", "c"], "col2": [1.0, 2.0, np.nan], "col3": [1.0, 2.0, 3.0]}, ...
3226564
newEngland = ["Maine","New Hampshire","Vermont", "Rhode Island", "Massachusetts","Connecticut"] def problem2_3(ne): for item in ne: print(item,"has",len(item),"letters.") pass # replace this pass (a do-nothing) statement with your code
3226581
import gym from .reversible_action_wrapper import ReversibleActionWrapper import numpy as np class AnssiActionShaping(ReversibleActionWrapper): def __init__( self, env: gym.Env, camera_angle: int = 10, always_attack: bool = False, camera_margin: int = 5, ...
3226599
import torch.nn.modules as nn import torch class ConvBlock(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, max_pool_factor=1.0): super().__init__() stride = (int(2 * max_pool_factor)) self.max_pool = nn.MaxPool1d(kernel_size=stride, stride=stride, ceil_mode=False) ...
3226614
import re def generate_cors_origin_regex_list(domains): regex_list = [] for domain in domains: regex_list.append(r"^(https?://)?(.*\.)?{0}$".format(re.escape(domain))) return regex_list
3226626
from functools import wraps def check_file_directory(method): """ decorator to be used on method to load data from file to check that file directory is not None :raises: ValueError: If file_directory is None """ @wraps(method) def decorated_method(self, *method_args, **method_kwargs): ...
3226637
import os import platform import sys from subprocess import check_output def main(): if platform.system().lower() == "windows": # Add sys.base_prefix which contains python3y.dll to PATH # otherwise running `pyo3-bin` might return exit code 3221225781 path = os.environ["PATH"] path ...
3226640
import numpy as np import torch import torch.nn as nn import math import torch.nn.functional as F from SRNN_layers.spike_neuron import mem_update_adp b_j0 = 1.6 class spike_cov2D(nn.Module): def __init__(self, input_size,output_dim, kernel_size=5,strides=1, pooling_type = None,po...
3226651
from django.core.urlresolvers import reverse from rest_framework.status import HTTP_200_OK from api.models import InterfaceText from common.tests.core import SimpleTestCase class MobileInterfaceTextTest(SimpleTestCase): def call_interface_text_api(self, params={}): response = self.client.get(reverse('mob...
3226662
import optparse import tokenize import warnings # Polyfill stdin loading/reading lines # https://gitlab.com/pycqa/flake8-polyfill/blob/1.0.1/src/flake8_polyfill/stdin.py#L52-57 try: from flake8.engine import pep8 stdin_get_value = pep8.stdin_get_value readlines = pep8.readlines except ImportError: from...
3226665
from __future__ import division, print_function import os, os.path import copy import pickle import numpy from ..util import plot, conversion, config from .Potential import PotentialError, flatten from ..util.conversion import physical_conversion,\ potential_physical_input, physical_compatible class linearPotentia...
3226681
import sys import os from probeCOCOATek.cli import main if __name__ == "__main__": sys.exit(main())
3226692
def lat_to_ibz(lat): """Returns the Bravais lattice ibz code based on the input string code. e.g. lat='bcc' or lat='fco' :param lat: lattice string code :type lat: str :returns: ibz code corresponding to the Bravais lattice given by the 'lat' key :rtype: int """ # One shou...
3226704
from test.conftest import MockUQCSBot, TEST_CHANNEL_ID def test_help_help(uqcsbot: MockUQCSBot): """ Tests `!help help` """ uqcsbot.post_message(TEST_CHANNEL_ID, '!help help') messages = uqcsbot.test_messages.get(TEST_CHANNEL_ID, []) assert len(messages) == 2 assert messages[-1]['text'] ==...
3226706
import numpy as np import cv2 as cv import k4a class kinect: # Kinect _device = None _capture = None # Infrared _infrared_image = None _infrared = None def __init__(self): self.initialize() def __del__(self): self.finalize() def initialize(self): self.ini...
3226740
from pathlib import Path from typing import Tuple from typing import Union import numpy as np import torch from typeguard import check_argument_types from espnet.nets.pytorch_backend.nets_utils import make_pad_mask from espnet2.layers.abs_normalize import AbsNormalize from espnet2.layers.inversible_interface import I...
3226768
from fuzz_lightyear.request import FuzzingRequest from fuzz_lightyear.response import ResponseSequence from fuzz_lightyear.runner import validate_sequence def test_basic(mock_client): responses = validate_sequence( [ FuzzingRequest( tag='basic', operation_id='ge...
3226797
class InterfaceTypeAttribute(Attribute,_Attribute): """ Indicates whether a managed interface is dual,dispatch-only,or IUnknown -only when exposed to COM. InterfaceTypeAttribute(interfaceType: ComInterfaceType) InterfaceTypeAttribute(interfaceType: Int16) """ def __init__(self,*args): """ x.__in...
3226819
import json import os from firecloud import api as fapi from firecloud.errors import FireCloudServerError from firecloud.entity import Entity class Workspace(object): """A FireCloud Workspace. Attributes: api_url (str): API root used to interact with FireCloud, normally https://api.firecl...
3226833
import unittest from getgauge.validator import _random_word, _is_valid, _format_params class ValidateTests(unittest.TestCase): def test_random_word(self): self.assertNotEqual(_random_word(), _random_word()) def test_is_valid(self): self.assertTrue(_is_valid("param", "{} = None")) sel...
3226835
from CommonServerPython import * import traceback SECTIONS_TO_KEEP = ('Threat Hunting', 'Mitigation', 'Remediation', 'Eradication') HEADER_TRANSFORM = {'id': 'Task ID', 'name': 'Task Name', 'state': 'Task State', 'completedDate': 'Completion Time'} ''' COMMAND FUNCTION ''' def add_url_to_tasks(tasks: Dict, workpl...
3226841
from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.decorators import login_required, permission_required, user_passes_test from django.views import generic from django.http import Http404 from django.contrib import messages from django.utils.decorators import method_decorator from...
3226870
from threading import Timer from olo.database import BaseDataBase, MySQLCursor from olo.libs.class_proxy import ClassProxy from olo.libs.pool import Pool, ConnProxy def create_conn(host, port, user, password, dbname, charset): try: from MySQLdb import connect conn = connect( # pragma: no cover ...
3226896
from unittest import mock import pytest from h_matchers import Any from h.traversal.group import GroupContext from h.views.admin import groups from h.views.admin.groups import GroupCreateViews, GroupEditViews class FakeForm: appstruct = None def set_appstruct(self, appstruct): self.appstruct = apps...
3226911
import cv2 import time import argparse import os import torch import posenet parser = argparse.ArgumentParser() parser.add_argument('--model', type=int, default=101) parser.add_argument('--scale_factor', type=float, default=1.0) parser.add_argument('--notxt', action='store_true') parser.add_argument('--image_dir', t...
3226931
import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoint as cp from fairseq.incremental_decoding_utils import with_incremental_state @with_incremental_state class MaskedConvolution(nn.Conv2d): """ 2d convolution with masked kernel """ def __init__(self, ...
3226949
from typing import List, Tuple import torch import torch.nn as nn from OpenMatch.modules.embedders import Embedder from OpenMatch.modules.encoders import Conv1DEncoder from OpenMatch.modules.matchers import KernelMatcher class ConvKNRM(nn.Module): def __init__( self, vocab_size: int, embe...
3226959
import logging import re logger = logging.getLogger(__name__) class SubjectParser: """ Parses git commit subject lines to determine the type of change (breaking, feature, fix, etc...) """ # order must be aligned with associated increment_type (major...post) _CHANGE_TYPES = ["breaking", "depreca...
3227010
def test_metadata(consul_config) -> None: assert consul_config.provider_code == "consul" assert consul_config.folder == "test/" def test_get_variable(monkeypatch, consul_config) -> None: consul_config._consul._env["test/key1"] = "1" consul_config._consul._env["test/key2"] = "2" assert consul_conf...
3227031
from typing import Any, Optional from cx_core.action_type.base import ActionType from cx_core.integration import EventData class DelayActionType(ActionType): delay: int def initialize(self, **kwargs: Any) -> None: self.delay = kwargs["delay"] async def run(self, extra: Optional[EventData] = Non...
3227032
import tensorflow as tf import numpy as np np.set_printoptions(precision=2, linewidth=200) import cv2 import os import time import sys #import tf_nndistance import argparse import glob import PIL import scipy.ndimage as ndimage sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from utils imp...
3227080
import tkinter as tk class TextLineNumbers(tk.Canvas): def __init__(self, min_width, *args, **kwargs): tk.Canvas.__init__(self, *args, **kwargs) self.textwidget = None self.min_width = min_width self.font = "Helvetica 12" def attach(self, text_widget): self.textwidget =...
3227089
import tensorflow as tf from detection.models.backbones import resnet from detection.models.necks import fpn from detection.models.rpn_heads import rpn_head from detection.models.bbox_heads import bbox_head from detection.models.roi_extractors import roi_align from detection.models.detectors.test_mixins import RPNTest...
3227093
from itertools import repeat from random import choice from pprint import pprint import asyncio import aiofiles import netdev import yaml async def connect_ssh(device, command): print(f"Подключаюсь к {device['host']}") async with netdev.create(**device) as ssh: sleep_sec = choice([4, 1, 8]) pr...
3227101
import os import sys import cv2 import numpy as np #PYCAFFE_DIR = '/home/kevin/Development/caffe3/python' PYCAFFE_DIR = '/usr/local/opt/caffe-2015-07/python' def _create_net(specfile, modelfile): if not PYCAFFE_DIR in sys.path: sys.path.insert(0, PYCAFFE_DIR) import caffe return caffe.Net(specfil...
3227110
import requests import re import uuid from flask import current_app from app.book.models import Book, SearchableBookMapping, searchable_book_index, searchable_book_doc_type from app.search import services as es_service def check_connection(): if not es_service.check_connection(): raise ValueError("Connect...
3227129
import numpy as np import logging from ..common.utils import get_command_args, configure_logger from ..common.gen_samples import read_anomaly_dataset from .aad_globals import ( IFOR_SCORE_TYPE_NEG_PATH_LEN, ENSEMBLE_SCORE_LINEAR, AAD_IFOREST, INIT_UNIF ) from .data_stream import DataStream, IdServer from .random...
3227229
from gpcharts import figure #simple line graph, as described in the readme. fig1 = figure() fig1.plot([8,7,6,5,4]) #another line graph, but with two data types. Also adding title fig2 = figure(title='Two lines',xlabel='Days',ylabel='Count',height=600,width=600) xVals = ['Mon','Tues','Wed','Thurs','Fri'] yVals = [[5,4...
3227279
MyPyStubsInfo = provider( fields = { "srcs": ".pyi stub files", }, ) def _mypy_stubs_impl(ctx): pyi_srcs = [] for target in ctx.attr.srcs: pyi_srcs.extend(target.files.to_list()) transitive_srcs = depset(direct = pyi_srcs) return [ MyPyStubsInfo( srcs = ctx....
3227305
from __future__ import absolute_import from collections import defaultdict from itertools import chain import logging import os from pip._vendor import pkg_resources from pip._vendor import requests from pip.compat import expanduser from pip.download import (is_file_url, is_dir_url, is_vcs_url, url_to_path, ...
3227315
class Solution: def climbStairs(self, n: int) -> int: def method_count(n): # base case if n in memo: return memo[n] # general cases memo[n] = method_count(n-1) + method_count(n-2) return memo[n] ...
3227320
from torch.nn.modules.loss import _Loss from package_core.losses import VariationLoss, L1Loss, PerceptualLoss from package_core.image_proc import * # L2 loss def MSE(para): return nn.MSELoss() # L1 loss def L1(para): return nn.L1Loss() def MaskedL1(para): return L1Loss() # Varianc...
3227325
import time import numpy as np import matplotlib import matplotlib.pyplot as plt from sklearn import svm from sklearn.datasets import make_moons, make_blobs from sklearn.covariance import EllipticEnvelope from sklearn.ensemble import IsolationForest from sklearn.neighbors import LocalOutlierFactor matplotlib.rcParam...
3227349
from core.test_blind_ft import Fine_tuning as test_ft from scipy import misc import numpy as np file_name = 'cman' file_name_clean = file_name + '_clean.png' file_path = './data/' noise_mean = 0 noise_sigma = 30 clean_image = misc.imread(file_path + file_name_clean) noisy_image = clean_image + np.random.normal(noise...
3227377
import math from django import template from django.utils.safestring import mark_safe from django.contrib.humanize.templatetags.humanize import intcomma from django.contrib.staticfiles.storage import staticfiles_storage from django.utils import timezone register = template.Library() @register.simple_tag(takes_cont...
3227382
from django.utils.translation import gettext_lazy as _ from app.admin.filters import BooleanFilter class IsRootFilter(BooleanFilter): title = _('Is root answer') parameter_name = 'is_root' def t(self, request, queryset): return queryset.filter(parent__isnull=True) def f(self, request, query...
3227399
import warnings import numpy as np def valid_rows_in_u(U: np.ndarray) -> np.ndarray: """ Checks that the matrix U supplied has elements between 0 and 1 inclusive. :param U: ndarray, matrix matrix where rows is the number of data points and columns is the dimension :return: ndarray a ...
3227481
def test_get(session, document): from dispatch.document.service import get t_document = get(db_session=session, document_id=document.id) assert t_document.id == document.id def test_get_all(session, document): from dispatch.document.service import get_all t_documents = get_all(db_session=session...
3227534
from snovault import upgrade_step @upgrade_step('biosample', '1', '2') def biosample_1_2(value, system): if 'cell_culture_details' in value: value['cell_culture_details'] = [value['cell_culture_details']]
3227538
import os.path as osp import os, sys from shutil import copy, rmtree import pdb import argparse import random import numpy as np from tqdm import tqdm import torch import torch.nn.functional as F import torch_geometric.transforms as T from qm9 import QM9 from dataloader import DataLoader # use a custom dataloader to ...
3227545
import pandas as pd from collections import defaultdict from tl.exceptions import RequiredInputParameterMissingException from tl.features import normalize_scores def read_csv(file_path, dtype=object): try: df = pd.read_csv(file_path, dtype=dtype) except UnicodeDecodeError: # try latin_1 encode...
3227590
import numpy as np from enum import Enum class BasePalette(Enum): """Palette Enum class with additional helper functions""" def __len__(self): """Number of colors in palette""" return len(self.value) def __iter__(self): self.n = 0 return self def __next__(self...