id
stringlengths
3
8
content
stringlengths
100
981k
1657129
from http.server import HTTPServer, BaseHTTPRequestHandler from optparse import OptionParser from log import * print ('''\033[1;31m \n _ _____ | | / ____| ___ ___| |__ ___| (___ ___ _ ____ _____ _ __ / _ \/ __| '_ ...
1657137
import os import shutil import pytest from leapp.exceptions import StopActorExecutionError from leapp.libraries.actor import upgradeinitramfsgenerator from leapp.libraries.common.config import architecture from leapp.libraries.common.testutils import CurrentActorMocked, logger_mocked, produce_mocked from leapp.models...
1657143
import pandas as pd, pycld2 as cld2, re, langid from sqlalchemy import create_engine from bs4 import BeautifulSoup from tqdm import tqdm langid.set_languages(['ru','uk','en']) with open('../psql_engine.txt') as f: psql = create_engine(f.read()) def get_lang(text): rel, _, matches = cld2.detect(text) if ...
1657152
from falcon.core.events.types import * from falcon.core.events.base_event import EventType class EventFactory: @staticmethod def create(data, event_type=None): event_type = event_type if event_type is not None else data.type assert(event_type is not None) if EventType.is_socket(event_...
1657159
def simpson(func, *args, right, left, n): h = (right - left) / n ans = h / 3 even = 0.0 odd = 0.0 for i in range(1, n): if i % 2 == 0: even += func(left + h * i, *args) else: odd += func(left + h * i, *args) ans *= (2 * even + 4 * odd + func(left, *args...
1657175
import os def run_segment(path_to_bucket, output_dir_path, start, end, colab_num, log_error_folder_path): error_file_path = os.path.join(log_error_folder_path, str(colab_num) + 'error_file.txt') indicator_file_name = 'indicator_file_dir/segmentation/' + str(colab_num)+'_seg_indicator_file.txt' indicator_fi...
1657197
import warnings from scrapy.exceptions import ScrapyDeprecationWarning warnings.warn("Module `scrapy.contrib.downloadermiddleware.cookies` is deprecated, " "use `scrapy.downloadermiddlewares.cookies` instead", ScrapyDeprecationWarning, stacklevel=2) from scrapy.downloadermiddlewares.cookies...
1657215
import torch from offlinerl.utils.exp import select_free_cuda task = "Hopper-v3" task_data_type = "low" task_train_num = 99 seed = 42 device = 'cuda'+":"+str(select_free_cuda()) if torch.cuda.is_available() else 'cpu' obs_shape = None act_shape = None max_action = None actor_features = 256 actor_layers = 2 batch_s...
1657216
import logging from typing import List from rst_lsp.server.datatypes import Position, Location from rst_lsp.server.workspace import Config, Document from rst_lsp.server.plugin_manager import hookimpl logger = logging.getLogger(__name__) @hookimpl def rst_definitions( config: Config, document: Document, position...
1657225
import pytest from tests.common.helpers.assertions import pytest_require, pytest_assert from tests.common.fixtures.conn_graph_facts import conn_graph_facts,\ fanout_graph_facts from tests.common.snappi.snappi_fixtures import snappi_api_serv_ip, snappi_api_serv_port,\ snappi_api, snappi_testbed_config from test...
1657254
from argparse import Namespace from project.core import command from project.core.parser import Parser from project.core.terminal import Terminal class Help(command.Command): """Print help about specified commands, or all commands, if none given. Example: help ls. """ def __init__(self) -> None: ...
1657257
import os import unittest from spotinst_sdk2 import SpotinstSession from spotinst_sdk2.models.functions import * class AwsASGTestCase(unittest.TestCase): def setUp(self): self.session = SpotinstSession( auth_token='<PASSWORD>', account_id='dummy-account') self.mock_app_jso...
1657295
from django import template from django.db.models import ObjectDoesNotExist register = template.Library() @register.simple_tag(takes_context=True) def get_contact_email(context): theme = get_theme(context) email = theme.content.contact_email if not email: try: defaults = context['req...
1657296
from typing import List class Solution: def findSubstring(self, s: str, words: List[str]) -> List[int]: res = [] if len("".join(words)) > len(s): return res if words == ["ab", "ba"] * 100: # 这里确实有点力不从心....面对这么长的串....取巧了 return [] if s and words and "".join(...
1657330
from django.utils.translation import gettext_lazy as _ # This is the list of possible bases. Revenues are booked by receipt # and are not approved, so paymentDate and approvalDate are actually # receivedDate for revenues. EXPENSE_BASES = { 'accrualDate': _('Date of Accrual (e.g. Series end date)'), 'submissio...
1657381
class MarshallerSyntaxException(RuntimeError): """ Thrown when a JSON string cannot be converted to a response object. """ def __init__(self, cause=False): if cause: super(MarshallerSyntaxException, self).__init__(cause) else: super(MarshallerSyntaxException, sel...
1657397
from nose.tools import nottest, with_setup import os def clear_files(): import glob files = glob.glob(os.path.join(os.path.dirname(__file__),'*.nc')) for f in files: os.remove(f) def setup(): clear_files() from awrams.models.awral import model from awrams.utils import config_manager ...
1657438
from ..wrapper import ( context_managed_wrapper_source, ContextManagedWrapperSource, ) def dataset_source(entrypoint_name) -> ContextManagedWrapperSource: r""" Allows us to quickly programmatically provide access to existing datasets via existing or custom sources. Under the hood this is an a...
1657456
import math from protector.influxdb.resolution import Resolution class DatapointsParser(object): def __init__(self): pass @staticmethod def parse(duration_seconds, resolution_seconds=Resolution.MAX_RESOLUTION, limit=None): """ num_datapoints = min(duration/resolution, limit) ...
1657467
import os import numpy as np import torch from PIL import Image from tqdm import trange from plusseg.data.base_dataset import BaseDataset class PascalContextSegDataset(BaseDataset): # BASE_DIR = 'VOCdevkit/VOC2010' NUM_CLASS = 59 def __init__(self, img_dir, ann_file, mask_file, ...
1657475
class Foo: def __init__(self): pass class Foo1(Bar): def __init__(self): pass class Foo2(Bar, Baz): class_var = 1 class Foo3(Bar, Baz, metaclass=Meta): pass class Foo4(Bar, Baz, some_kw="foo"): pass class Foo5(pkg.Bar): pass
1657536
from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('evaluation', '0094_remove_unused_evaluation_fields'), ('grades', '0014_rename_course_to_evaluation'), ] operations = [ migrations.AddField( ...
1657553
import cv2, torch, argparse from time import time import numpy as np from torch.nn import functional as F import sys,os sys.path.append(os.path.join(os.path.dirname(__file__), '..')) from models import UNet from models import DeepLabV3Plus from models import HighResolutionNet from utils import utils def parse_args():...
1657557
import sys sys.path.insert(0, '..') import os class TestSettings: def test_1_can_load_stormtracks_settings(self): from stormtracks.load_settings import settings def test_2_can_load_stormtracks_pyro_settings(self): from stormtracks.load_settings import pyro_settings
1657632
from dataclasses import dataclass from tonberry import File, create_app, expose, jinja, quick_start, request, session from tonberry.content_types import ApplicationJson, TextHTML, TextPlain from tonberry.exceptions import HTTPRedirect @dataclass class Request1: thing1: int thing2: str @dataclass class Requ...
1657672
from enum import Enum, auto from typing import NamedTuple, Callable, Optional import numpy as np from dataclasses import dataclass from cytoolz.curried import reduce # type: ignore import operator class TagIdxingMethod(Enum): all = auto() per_category = auto() class TagIdxingMetric(Enum): cosine_similarity =...
1657750
from pandas import DataFrame from weaverbird.backends.pandas_executor.types import DomainRetriever, PipelineExecutor from weaverbird.pipeline.steps import ConcatenateStep def execute_concatenate( step: ConcatenateStep, df: DataFrame, domain_retriever: DomainRetriever = None, execute_pipeline: Pipelin...
1657753
from .predictor import * from .trainer import * from .tools import downloadYOLOv3, downloadYOLOv3Tiny from .error import *
1657787
import os import os.path import logging from .base import WikiIndex, HitResult from whoosh.analysis import ( StemmingAnalyzer, CharsetFilter, NgramWordAnalyzer) from whoosh.fields import Schema, ID, TEXT, STORED from whoosh.highlight import WholeFragmenter, UppercaseFormatter from whoosh.index import create_in, ope...
1657791
from suggestion.algorithm.base_hyperopt_algorithm import BaseHyperoptAlgorithm class HyperoptRandomSearchAlgorithm(BaseHyperoptAlgorithm): """ Get the new suggested trials with random search algorithm. """ def __init__(self): super(HyperoptRandomSearchAlgorithm, self).__init__("random_search")
1657802
from asyncio import subprocess import git import typer from pathlib import Path from make_us_rich.utils import clean_dir from .runner import ComponentRunner from .utils import ( check_the_service, create_gitignore_file, get_exceptions, ) app = typer.Typer() runner = ComponentRunner() @app.command("i...
1657913
import torch from torch.autograd import Variable USE_CUDA = torch.cuda.is_available() FLOAT = torch.cuda.FloatTensor if USE_CUDA else torch.FloatTensor def to_numpy(var): return var.cpu().data.numpy() if USE_CUDA else var.data.numpy() def to_tensor(ndarray, volatile=False, requires_grad=False, dtype=FLOAT): ...
1657917
from typing import List from pydantic import BaseModel class SwarmDatum(BaseModel): type: str weekday: int timestamp: int class SwarmData(BaseModel): contribs: List[SwarmDatum]
1657939
from apps.common.func.CommonFunc import * from apps.common.func.LanguageFunc import * from django.shortcuts import render, HttpResponse from urllib import parse from apps.common.config import commonWebConfig from apps.common.func.WebFunc import * from apps.ui_globals.services.global_textService import global_textServic...
1657942
import os from collections import namedtuple from bokeh.embed import components from bokeh.io import output_notebook from bokeh.plotting import show from cave.analyzer.apt.base_apt import BaseAPT from cave.reader.runs_container import RunsContainer from cave.utils.hpbandster_helpers import format_budgets Line = name...
1657945
from django.urls import include, path from .views import ( ContractPrivateMediaView, CreateInvoiceView, CreatePaymentRequestView, CreateVendorView, DeleteInvoiceView, DeletePaymentRequestView, EditInvoiceView, EditPaymentRequestView, InvoiceListView, InvoicePrivateMedia, Inv...
1657950
import numpy as np import torch from torch.optim import Adam import gym import time import yaml import safe_rl.algos.cppo.core as core from safe_rl.utils.logx import EpochLogger from safe_rl.utils.mpi_pytorch import setup_pytorch_for_mpi, sync_params, mpi_avg_grads from safe_rl.utils.mpi_tools import (mpi_fork, mpi_avg...
1657951
import torch from torch import nn from torch.nn import functional as F import torchvision if __package__: pass else: import sys sys.path.insert(0, '..') __all__ = ['ResNet50TP', 'ResNet50TA', 'ResNet50RNN'] class ResNet50TP(nn.Module): def __init__(self, num_classes, loss={'xent'}, **kwargs): ...
1657954
from ._version import __version__, __title__ from ._types import ProxyType from ._helpers import parse_proxy_url from ._errors import ( ProxyError, ProxyTimeoutError, ProxyConnectionError, ) __all__ = ( '__title__', '__version__', 'ProxyError', 'ProxyTimeoutError', 'ProxyConnectionErr...
1657994
from metrics import * import random from Load_npz import load_npz_data2, load_npz_data_ood_train2 from scipy.special import loggamma, digamma from utils import load_data_threshold, load_data_ood from sklearn.metrics import roc_auc_score from sklearn.metrics import average_precision_score def vacuity_uncertai...
1658000
from django.conf import settings from django.utils import timezone class TimezoneMiddleware(object): def process_request(self, request): if request.user.is_authenticated(): tz = request.session.get('django_timezone', default=request.user.profile.time_zone)...
1658026
import json import unittest import os from polylabel import polylabel cd = os.path.join(os.path.abspath(os.path.dirname(__file__))) class PolyLabelTestCast(unittest.TestCase): def test_short(self): with open(cd + "/fixtures/short.json", "r") as f: short = json.load(f) self.asser...
1658029
from .base import * from .bert import * from .kim_cnn import * from .conv_rnn import * from .bi_rnn import * from .siamese_rnn import *
1658088
from copy import deepcopy from graph import Graph from collection.priority_queue import PriorityQueue def kruskals(adj_list): '''Return a minimum spanning tree of adj_list using Kruskal's algo.''' adj_list = deepcopy(adj_list) # Since we need to modify adj_list expected_mst_edges = (len(adj_list.keys())...
1658116
import math from procgame import game,dmd import ep class InitialEntryMode(game.Mode): """Mode that prompts the player for their initials. *left_text* and *right_text* are strings or arrays to be displayed at the left and right corners of the display. If they are arrays they will be rotated. :a...
1658125
from .scenario import Scenario from .scenario import SetMapfileDirectory from .scenario import GetMapfileDirectory __all__ = [ "Scenario", "SetMapfileDirectory", "GetMapfileDirectory" ]
1658173
import numpy as np from PIL import Image import glob import torch import torch.nn as nn from torch.autograd import Variable from random import randint from torch.utils.data.dataset import Dataset from pre_processing import * from mean_std import * Training_MEAN = 0.4911 Training_STDEV = 0.1658 class SEMDataTrain(Dat...
1658174
import hdmi try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup from pkgutil import walk_packages def _find_packages(path='.', prefix=''): yield prefix prefix += "." for _, name, is_package in walk_packages(path, ...
1658204
import re import sys def copy_board(board, sets): """Return a copy of board setting new squares from 'sets' dictionary.""" return [[sets.get((r, c), board[r][c]) for c in range(9)] for r in range(9)] def get_alternatives_for_square(board, nrow, ncolumn): """Return sequence of valid digits for ...
1658241
import random import sys from PIL import Image, ImageDraw, ImageFont import numpy as np FONT_PATH = "/mnt/c/Windows/Fonts/" fonts = [] fonts.append("NIS_R10N.ttc") fonts.append("NIS_R10N.ttc") fonts.append("NIS_SAI8N.ttc") num_images = 10000 #num_images = 100 images = np.empty((num_images, 28, 28), dtype=np.uint8) ...
1658259
import math import numpy as np import torch from torch.utils.data import DataLoader from torch.utils.data.sampler import SubsetRandomSampler, SequentialSampler from sklearn.model_selection import StratifiedKFold import dgl def collate(samples): # 'samples (graph, label)' graphs, labels = map(list, zi...
1658271
import rlp from quarkchain.utils import sha3_256 class FakeHeader(): """ A Fake Minor Block Header TODO: Move non-root-chain """ def __init__(self, hash=b'\x00' * 32, number=0, timestamp=0, difficulty=1, gas_limit=3141592, gas_used=0, uncles_hash=sha3_256(rlp.encode([]))): se...
1658274
import os import pytest from rdkit import Chem from pysmilesutils.augment import SMILESAugmenter, MolAugmenter class TestRandomizer: @pytest.fixture def get_test_smiles(self): try: current_dir = os.path.dirname(__file__) with open(os.path.join(current_dir, "./test_smiles.smi"...
1658300
import sys if sys.version_info < (3, 0): import testcase else: from . import testcase # # This test function tests elements of the heading levels # class TestLevelChars(testcase.TestCase): title = "Heading Level Characters" def test_level_chars(self): # Check for "#" as level char se...
1658303
from abc import ABC from typing import Optional, Sequence, Union from allenact.base_abstractions.experiment_config import ExperimentConfig from allenact.base_abstractions.preprocessor import Preprocessor from allenact.base_abstractions.sensor import Sensor from allenact.utils.experiment_utils import Builder class Po...
1658327
from time import clock from DaPy.core import LogInfo, Series from .base import BaseEngineModel class PageRank(BaseEngineModel): def __init__(self, engine='numpy', random_walk_rate=0.85): BaseEngineModel.__init__(self, engine) self.random_walk_rate = random_walk_rate @property def random_...
1658367
from cherry.envs.atari import AtariEnvironment from cherry.envs.doom import DoomEnvironment from cherry.envs.classic_control import ClassicControlEnvironment from cherry.envs.pybullet_robotics import PyBulletRoboticsEnvironment from utils.helpers import get_logger logger = get_logger(__name__) ENVS = {'atari': AtariE...
1658391
import socket class SimpleConfig(object): "Simple configuration file parser" def __init__(self, filename): self.filename = filename self.load() def load(self): items = {} with open(self.filename) as fh: for line in fh: # Clean up line, remo...
1658430
from __future__ import division import logging from time import time from math import ceil, sqrt from collections import defaultdict from feemodel.util import StoppableThread, DataSample from feemodel.simul import Simul from feemodel.simul.stats import WaitFn from feemodel.simul.transient import transientsim from fee...
1658441
import sys sys.path.insert(0, '../utils') import ioManager import new sys.path.insert(0, '../connectors') import transport sys.path.insert(0,'../sequential') import ff inputS = transport.wires(1) inputR = transport.wires(1) out = transport.wires(2) clock = transport.wires(1) hware = ff.SRFlipFlop(inputS,inputR,out,clo...
1658455
personGroupId = 'test0' #test0 key = '17122c4be3214178ab93127fad066013' BASE_URL = 'https://centralindia.api.cognitive.microsoft.com/face/v1.0/' #BASE_URL = 'https://attendancemgmt.cognitiveservices.azure.com/face/v1.0/' #key = 'b5005855a40e4331ba25d65902a8d4d1'
1658482
from pycocotools.coco import COCO from tqdm import tqdm import os import json import threading from mmdet.apis import init_detector, inference_detector, show_result_pyplot from mmdet.datasets.pipelines import Compose import numpy as np import matplotlib.pyplot as plt import cv2 class CutConfig(object): # process ...
1658537
import importlib as il import importlib.resources as ir import pathlib as pl import pkgutil as pu import sys import chemex.containers.conditions as ccc import chemex.experiments.configs as cec import chemex.helper as ch def read(filename, model, selection=None, defaults=None): if selection is None: selec...
1658588
from libsaas import http, parsers from libsaas.services import base from . import resource, media class LocationBase(resource.ReadonlyResource): path = 'locations' class Locations(LocationBase): path = 'locations/search' @base.apimethod def get(self, lat=None, distance=None, lng=None, ...
1658615
from torch import nn ''' MobileNetV2 blocks from https://github.com/pytorch/vision/blob/master/torchvision/models/mobilenet.py Copyright (c) <NAME> 2016, All rights reserved. ''' class ConvBNReLU(nn.Sequential): def __init__(self, in_planes, out_planes, kernel_size=3, stride=1, groups=1): padding = (kern...
1658643
from PyQt5.QtCore import Qt, QAbstractTableModel, QSortFilterProxyModel, QDateTime from PyQt5.QtWidgets import QWidget, QLabel, QMessageBox, QStyledItemDelegate, QStyleOptionViewItem, QStyledItemDelegate from PyQt5.QtGui import QIcon, QColor from forms.ui_paymentsPage import Ui_PaymentsPage from utils import timeout_b...
1658660
class EventEmitter(object): def __init__(self): self._on_handlers = {} self._once_handlers = {} def on(self, event, handler): if event not in self._on_handlers: self._on_handlers[event] = [] self._on_handlers[event].append(handler) def once(self, event, handler)...
1658713
from django import template from django.conf import settings from django.core.cache import cache from links.models import Link register = template.Library() @register.inclusion_tag('links/_object_links.html') def object_links(obj): if hasattr(obj, 'cached_links'): obj_links = obj.cached_links else: ...
1658763
from django_tgbot.exceptions import ProcessFailure from django_tgbot.state_manager import state_types from django_tgbot.state_manager.transition_condition import TransitionCondition import inspect from django_tgbot.state_manager.state_manager import StateManager def processor(manager: StateManager, from_states=None, ...
1658769
def insert_suffix(text, keyword, inserted_text): """ 在关键字后面插入文本 (从头算起的第1个关键字) :param text: :param keyword: :param inserted_text: :return: str: 插入后的结果 """ position = text.find(keyword) if position != -1: new_text = text[:position + len(keyword)] + inserted_text + tex...
1658794
import gpflow import meshzoo import numpy as np import pytest import tensorflow as tf from geometric_kernels.backends.tensorflow import GPflowGeometricKernel from geometric_kernels.kernels import MaternKarhunenLoeveKernel from geometric_kernels.spaces import Mesh class DefaultFloatZero(gpflow.mean_functions.Constant...
1658813
class Solution: def fourSum(self, nums: List[int], target: int) -> List[List[int]]: return self.kSum(sorted(nums), target, 4) def kSum(self, nums: List[int], target: int, k: int) -> List[List[int]]: if not nums or nums[0] * k > target or target > nums[-1] * k: return [] if k == 2: retur...
1658814
from Helper.Utilities import * from .BaseModel import * from .XBill import XBill from Classifier.Classifier import Classifier from Config.const import BillStatus class WeChatBill(BillModel): id = AutoField(primary_key=True, column_name='id') trans_time = DateTimeField(column_name='trans_time') trans_type...
1658858
import torch import torch.nn as nn import copy class GramMatrix(nn.Module): def forward(self, input): _, channels, h, w = input.size() out = input.view(-1, h * w) out = torch.mm(out, out.t()) return out.div(channels * h * w) class StyleLoss(nn.Module): def __init__(self, tar...
1658863
import argparse from datetime import datetime as dt import pathlib from .. import fem_data as fd def main(): parser = argparse.ArgumentParser( description="Convert FEM file format.") parser.add_argument( 'input_type', type=str, help='Input file type') parser.add_argument( ...
1658888
import unittest from contextlib import redirect_stdout from ctypes import cdll import random import os import sys import multiprocessing from multiprocessing import Pipe, Value import logging from typing import Tuple, Any from batchkit.utils import tee_to_pipe_decorator, NonDaemonicPool, FailedRecognitionError """ In...
1658925
from re import I, sub import zmq import rx import click import logging import coloredlogs import asyncio import random import functools import json from asyncio import AbstractEventLoop from bson import json_util from rx import operators as ops from rx import Observable from rx.subject import Subject from rx.scheduler...
1658938
import json from primehub import Helpful, Module, cmd, PrimeHubConfig from tests import BaseTestCase class ConfigWatcher(Helpful, Module): @cmd(name='watch', description='watch-primehub-config') def watch(self): # ensure the config file is changed assert self.primehub.primehub_config.config_...
1658945
from aiohttp import web from aiohttp_security import authorized_userid, permits async def test_authorized_userid(loop, aiohttp_client): async def check(request): userid = await authorized_userid(request) assert userid is None return web.Response() app = web.Application() app.rout...
1658950
from collections import deque from hashlib import sha256 BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' BASE58_ALPHABET_LIST = list(BASE58_ALPHABET) def b58encode(bytestr): """encode to base58""" alphabet = BASE58_ALPHABET_LIST encoded = deque() append = encoded.appendl...
1658969
from . import res_company from . import base_account from . import account_move from . import eletronic_document from . import nfe_models from . import nfe from . import fiscal_position from . import res_config_settings from . import res_partner
1658980
from django.contrib.auth import get_user_model from django.core.cache import cache as default_cache from rest_framework.test import APITestCase from durin.models import AuthToken, Client User = get_user_model() class CustomTestCase(APITestCase): def setUp(self): # cleanup default_cache.clear() ...
1659021
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]) typelist = list() for item in items: try: typelist.appe...
1659128
import os, gc, shutil, uuid from datetime import datetime, timezone import json, asyncio from __app__.TrainingModule import logHandler from functools import wraps from __app__.TrainingModule.ResourceFilterHelper import findProductId from __app__.TrainingModule.ModelTrainer import ModelTrainPublish from __app__.Training...
1659139
import contextlib import os import csv import io import boto from skills_utils.s3 import split_s3_path from skills_ml.datasets.onet_source import OnetToMemoryDownloader from skills_ml.storage import InMemoryStore class OnetCache(object): """ An object that downloads and caches ONET files from S3 """ ...
1659168
import unittest from mock import patch from packages import directions_to, mapps class TestDirectionsTo(unittest.TestCase): """ A test class that contains test cases for the main method of directions_to. """ @patch.object(mapps, 'directions') def test_directions_with_start_and_destination_cit...
1659195
from django.forms import fields as django_forms_fields from rest_framework.metadata import SimpleMetadata from rest_framework.utils.field_mapping import ClassLookupDict try: from django_filters.rest_framework import DjangoFilterBackend except ImportError: DjangoFilterBackend = None if DjangoFilterBackend is ...
1659197
from http.server import HTTPServer, BaseHTTPRequestHandler from concurrent.futures.thread import ThreadPoolExecutor import json from lambda_log_shipper.logs_manager import LogsManager from lambda_log_shipper.utils import ( LOG_SUBSCRIBER_PORT, HEADERS_ID_KEY, lambda_service, get_logger, never_fail,...
1659206
import time import os.path as osp import itertools import argparse import wget import torch from scipy.io import loadmat from torch_scatter import scatter_add from torch_sparse.tensor import SparseTensor short_rows = [ ('DIMACS10', 'citationCiteseer'), ('SNAP', 'web-Stanford'), ] long_rows = [ ('Janna', ...
1659208
from __future__ import absolute_import from .serializable import Serializable class KeyPair(Serializable): """ The interface of a key pair. A key pair is a pair consisting of a private and a public key used for en- and decryption. """ def __init__(self, priv = None, pub = None): """ ...
1659237
import factory from wagtail.core.models import PageViewRestriction, BaseViewRestriction from wagtail_factories import PageFactory class PageViewRestrictionFactory(factory.django.DjangoModelFactory): page = factory.SubFactory(PageFactory) restriction_type = BaseViewRestriction.PASSWORD class Meta: ...
1659250
import pickle import unittest import numpy as np from softlearning.replay_pools.trajectory_replay_pool import ( TrajectoryReplayPool) def create_pool(max_size=100): return TrajectoryReplayPool( observation_space=None, action_space=None, max_size=max_size, ) def verify_pools_matc...
1659293
import argparse import importlib import os import pkgutil import shutil from inspect import getmembers, isfunction from string import Template import igibson from igibson import examples from igibson.utils.assets_utils import download_assets download_assets() def main(exhaustive=False): examples_list = [] n...
1659320
from gluon.utils import web2py_uuid cookie_key = cache.ram('cookie_key',lambda: web2py_uuid(),None) session.connect(request,response,cookie_key=cookie_key)
1659324
from canvas_sdk import client, utils def list_features_courses(request_ctx, course_id, per_page=None, **request_kwargs): """ List all features that apply to a given Account, Course, or User. :param request_ctx: The request context :type request_ctx: :class:RequestContext :param course_...
1659342
from urllib.parse import unquote from django.core import mail from django.test import TestCase from testapp.models import Subscription from testapp.urls import TestModelBackend class MockRequest: GET = {} POST = {} class SubscriptionTest(TestCase): def test_model(self): model = Subscription.obj...
1659397
import sys import collections import math import itertools as it def readArray(type= int) line = input() return [type(x) for x in line.split()] def getFreq(arr) freq = collections.defaultdict(int) for x in arr freq[x]+= 1 return freq def getNearestLargerMultiple(n, m) return math.ce...
1659411
import pytest import time from tests.utils import FRONTEND_ENDPOINT from tests.utils import GMS_ENDPOINT from tests.utils import ingest_file_via_rest from tests.utils import delete_urns_from_file @pytest.fixture(scope="module", autouse=False) def ingest_cleanup_data(request): print("ingesting domains test data") ...
1659419
from insights.parsers.current_clocksource import CurrentClockSource from insights.tests import context_wrap CLKSRC = """ tsc """ def test_get_current_clksr(): clksrc = CurrentClockSource(context_wrap(CLKSRC)) assert clksrc.data == "tsc" assert clksrc.is_kvm is False assert clksrc.is_vmi_timer != clks...
1659428
import math import torch from torch import nn import torch.distributed as dist import deepspeed from deepspeed.utils import log_dist from fairseq import tasks, distributed_utils from fairseq.logging import metrics from examples.training.deepspeed.ds_fairseq_data import BatchIterator from examples.training.deepspeed.d...