id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
3265862 | from __future__ import annotations
from typing import TYPE_CHECKING
from typing import Union
if TYPE_CHECKING:
from app.objects.beatmap import Beatmap, BeatmapSet
bcrypt: dict[bytes, bytes] = {} # {bcrypt: md5, ...}
beatmap: dict[Union[str, int], Beatmap] = {} # {md5: map, id: map, ...}
beatmapset: dict[int, ... |
3265866 | import math
import torch
from torch.utils.data.distributed import DistributedSampler
class StepDistributedSampler(DistributedSampler):
def __init__(self, dataset, num_replicas=None, rank=None):
super(StepDistributedSampler, self).__init__(dataset, num_replicas, rank)
self.step = 0
def set_ste... |
3265986 | import abc
import itertools
from typing import Iterable
from .indexes import Index
from .internal import _InternalAccessor
from .merge import MergeExpression
from .operator import (ArithExpression, BooleanExpression, DataFrameLike,
SeriesLike, StatOpsMixin)
from .series import Series
from .utils... |
3265988 | from stellar_sdk import Keypair
from stellar_sdk import TransactionBuilder, Server, Network, Keypair
from stellar_sdk import Server
from stellar_sdk import Asset
from XLM_Wallet import XLM_Wallet
class Call_Builder:
def BASE_CALL_BUILDER():
print("Test")
def ACCOUNTS_CALL_BUILDER():
print("Tes... |
3265995 | import json
import os
import psycopg2
import pytest
from aiohttp import web
from services.data.postgres_async_db import AsyncPostgresDB
from services.utils.tests import get_test_dbconf
from services.metadata_service.api.admin import AuthApi
from services.metadata_service.api.flow import FlowApi
from services.metadata_... |
3266030 | import sys
from cvangysel import argparse_utils, io_utils, logging_utils, trec_utils
import argparse
import ast
import gzip
import logging
import os
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--loglevel', type=str, default='INFO')
parser.add_argument('--shard_size',
... |
3266052 | from datetime import datetime, timezone
from typing import Any, Dict, Optional
from ..models import Snowflake
from ..utils import Event, _get_as_snowflake
__all__ = ('TypingEvent', 'ChannelPinsUpdateEvent')
class TypingEvent(Event):
"""Dispatched when a user starts typing in a channel."""
user_id: Snowflak... |
3266059 | from abc import ABCMeta, abstractmethod
from typing import Dict
_all_transforms = None
class TransformException(Exception):
pass
def get_all_transforms():
global _all_transforms
def get_subclasses(cls):
classes = []
for subclass in cls.__subclasses__():
classes.append(subcl... |
3266065 | import pytest
from glob import glob
from fontTools.ttLib import TTFont
import tempfile
import os
from gftools.html import *
import re
from copy import deepcopy
TEST_DATA = os.path.join("data", "test")
@pytest.fixture
def SimpleTemplate():
class SimpleTemplate(HtmlTemplater):
def __init__(self, out, temp... |
3266074 | from functools import singledispatch
from typing import Any
import numpy
import pandas
import scipy.sparse
@singledispatch
def as_columns(data: Any) -> Any:
"""
Get the columns for `data`. If `data` represents a single column, or is a
dictionary (the format used to store columns), it is returned as is.
... |
3266076 | import gen_utils
from module_base import ModuleBase
from module_mixins import NoConfigModuleMixin
import module_utils
import vtk
import vtkdevide
class greyReconstruct(NoConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
# initialise our base class
ModuleBase.__init__(self, module_... |
3266084 | import tensorflow as tf
import tensorbayes as tb
import numpy as np
from tensorbayes.layers import *
from tensorbayes.distributions import *
from tensorflow.contrib.framework import arg_scope, add_arg_scope
################
# Extra layers #
################
@add_arg_scope
def basic_accuracy(a, b, scope=None):
with... |
3266092 | from canoser import *
import pytest
import pdb
def test_read():
data = [6,2,3,4,5]
cursor = Cursor(data)
assert cursor.read_u8() == 6
assert cursor.offset == 1
assert cursor.position() == cursor.offset
assert cursor.peek_bytes(3) == b'\x02\x03\x04'
assert cursor.offset == 1
... |
3266094 | import logging, yaml, os, sys, argparse, math
import torch
from Modules import GE2E
from Arg_Parser import Recursive_Parse
class Tracer(torch.nn.Module):
def __init__(self, hp_path: str, checkpoint_path: str):
super().__init__()
self.hp = Recursive_Parse(yaml.load(
open(hp_path, encodi... |
3266141 | from more_itertools import ilen
from my.google import events
from my.google.models import (
Location,
AppInstall,
LikedVideo,
HtmlComment,
HtmlEvent,
)
def test_google_types():
all_ev = list(events())
assert len(all_ev) > 100
all_types = set([Location, AppInstall, LikedVideo, HtmlComm... |
3266178 | from rdkit import Chem
from rdkit.Chem import QED
import numpy as np
import networkx as nx
from openchem.utils.sa_score import sascorer
from rdkit.Chem import Descriptors
def reward_penalized_log_p(smiles, return_mean=True):
"""
Reward that consists of log p penalized by SA and # long cycles,
as described... |
3266190 | from pygame.rect import Rect
from battle_city.collections.sliced_array import SlicedArray
from battle_city.monsters import Coin
import pytest
def test_init_empty():
array = SlicedArray(grid=32)
assert array._parts == {}
assert array._grid == 32
assert len(array) == 0
def test_init_filled():
co... |
3266193 | import numpy as np
import scipy.sparse as sparse
import torch
import torch.nn as nn
import dgl
import dgl.nn as dglnn
from dgl.base import DGLError
import dgl.function as fn
from dgl.nn.functional import edge_softmax
class GraphGRUCell(nn.Module):
'''Graph GRU unit which can use any message passing
net to rep... |
3266252 | import aiohttp
import asyncio
import json
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
async def main(urls):
tasks = []
results = []
async with aiohttp.ClientSession() as session:
for url in urls:
tasks.append(fetch(se... |
3266255 | import asyncio
from copy import deepcopy
from sage_utils.constants import VALIDATION_ERROR
from sage_utils.wrappers import Response
from app.groups.documents import Group
from app.microservices.documents import Microservice
from app.permissions.documents import Permission
from app.rabbitmq.workers import RegisterMicr... |
3266269 | import time
import random
from tqdm import tqdm
import numpy as np
def efficient_greedy(
measure,
dataset_size,
subset_size,
start_indices,
intermediate_target=None,
clustering_combinations=None,
celf_ratio=0,
verbose=True
):
candidates = list(set(range(dataset_size)) - set(start... |
3266284 | from sphinxext.rediraffe import create_graph
import pytest
from sphinx.errors import ExtensionError
def test_create_graph(tmp_path):
path = tmp_path / "rediraffe.txt"
path.write_text(
"""
a b
c d
d e
"""
)
graph = create_graph(path)
assert graph == {
... |
3266325 | from __future__ import annotations
import math
import typing as t
def percentile(seq: t.Iterable[float], percent: float) -> float:
"""
Find the percentile of a list of values.
prometheus-client 0.6.0 doesn't support percentiles, so we use this implementation
Stolen from https://github.com/heaviss/per... |
3266359 | from fireo.fields import Field, errors
from google.cloud import firestore
class GeoPoint(Field):
"""GeoPoint field for firestore
Examples
-------
.. code-block:: python
class User(Model):
location = GeoPoint()
u = User()
u.location = fireo.GeoPoint(latitude=123.23... |
3266390 | from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
from colors import *
from shapes import SolidCylinder
angle_h = 300.0
angle_v = 0
spin = True
turn_h = 1
turn_v = 0
render_quality = 100 # max = 100
def keyboard(key, x, y):
global spin, turn_h, turn_v, angle_h, angle_v, render_quality
... |
3266409 | import torch
from torchvision import datasets, transforms, utils
from torch.utils.data import Dataset, DataLoader
import numpy as np
import scipy.io as sio
import platform
import copy
import math
import matplotlib.pyplot as plt
import glob
from PIL import Image
import os
def generate_dataset(input_channel,input_width... |
3266424 | import os
import django
from django.test.utils import setup_databases
def pytest_configure(config):
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.test_settings'
django.setup()
setup_databases(verbosity=1, interactive=False)
|
3266426 | from binascii import hexlify
from typing import Dict
class CANFrame:
"""
Class for calculating the bitstream of a CAN frame.
"""
FIELD_NAMES = ['sof',
'ida',
'idb',
'ide',
'srr',
'rtr',
'r... |
3266429 | from util import *
from net import Net
from trainers import Trainer
from vol import Vol
"""
An agent is in state0 and does action0
environment then assigns reward0 and provides new state, state1
Experience nodes store all this information, which is used in the
Q-learning update step
"""
class Experience(object):
... |
3266508 | import os
from setuptools import setup, find_packages
about = {}
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'copperhead', '__version__.py'), 'r') as f:
exec(f.read(), about)
with open('README.md', 'r') as f:
readme = f.read()
setup(
name=about['__title__'],
version... |
3266567 | import csv
import time
from pathlib import Path
from shutil import copyfile
from ConfigValidator.Config.Models.RobotRunnerContext import RobotRunnerContext
from ProgressManager.Output.OutputProcedure import OutputProcedure as output
class INA219Profiler:
__path_to_data_file: str
def __init__(self, path_to_da... |
3266621 | import SimpleHTTPServer
import SocketServer
import os
import time
class BasicServer(object):
def __init__(self, path, reporter, port=None):
PORT = 8000
if port != None:
PORT = port
os.chdir(path)
try:
reporter.log("Starting a server" , "blue")
... |
3266625 | import math
from collections import Counter
from torch.optim.lr_scheduler import _LRScheduler
class CosineAnnealingWithLinearWarmup(_LRScheduler):
def __init__(
self, optimizer, warmup_epoch,
T_max, adjust_epoch=False, eta_min=0,
last_epoch=-1, verbose=False):
self.war... |
3266629 | from .data_viewer import ScatterViewer # noqa
def setup():
from glue.config import qt_client
qt_client.add(ScatterViewer)
|
3266650 | from sqlalchemy.orm import raiseload, joinedload
from typing import Optional
from app import db
from app.models.oauth.client import OAuthClient
from app.models.oauth.code import OAuthAuthorizationCode
from app.models.oauth.token import OAuthToken
from app.models.user import User
def get_client_by_id(client_id):
... |
3266655 | import torch
def mae_loss(y_pred, y_true):
err = torch.abs(y_true - y_pred)
mae = err.mean()
return mae
|
3266696 | from lxml import etree
from tqdm import tqdm
NEWLINE_TOKEN = "<|n|>"
END_TOKEN = "<|endoftext|>"
PARAPHRASE_TOKEN = " <PASSWORD>: "
TEXT_FRAGMENT_END = "\n" + END_TOKEN + "\n"
root = etree.parse(
r'C:\Users\kiva0319\IdeaProjects\hrdmd1803\Strong-Paraphrase-Generation-2020\raw_data\paraphrases.xml')
root = root.ge... |
3266708 | import tensorflow as tf
from tensorflow.contrib.layers.python.layers import fully_connected
from flip_gradient import flip_gradient
def pdist(x1, x2):
"""
x1: Tensor of shape (h1, w)
x2: Tensor of shape (h2, w)
Return pairwise distance for each row vector in x1, x2 as
a Tensor of sh... |
3266716 | import click
import torch
from test import load_arxiv, load_reddit, to_sparse_gpu, csr_dmm_gpu, csr_fuse_gpu
def dense(iters, b, n):
print("dense", b, n)
x = torch.randn((b, n)).cuda()
w = torch.randn((n, n)).cuda()
with torch.autograd.profiler.emit_nvtx():
for _ in range(iters):
... |
3266725 | from .roi_head_template import RoIHeadTemplate
from .ct3d_head import CT3DHead
__all__ = {
'RoIHeadTemplate': RoIHeadTemplate,
'CT3DHead': CT3DHead
}
|
3266856 | import numpy as np
from typing import List, Tuple, Optional
from pathlib import Path
from PIL import Image
IMG_FORMATS = ['JPEG', 'PNG']
def load_image(path: Path, target_size=None) -> Image:
img = Image.open(path)
f = img.format # store format after opening as it gets lost after conversion
if img.mode... |
3266889 | import configparser
import os
import platform
import re
import shutil
import tempfile
from appdirs import user_config_dir
from colorama import Fore, Style
from copy import deepcopy
from toncli.modules.utils.system.check_executable import safe_get_version, check_executable
from toncli.modules.utils.system.log import lo... |
3266892 | from __future__ import annotations
from typing import Any, Union, List, Dict
import collections
def ref(token: Any) -> str:
"""Wraps the token so it can be used as an attribute token"""
return f"#ref{token}"
def val(token: Any) -> str:
"""Wraps the token so it can be used a value token"""
return f":... |
3266943 | import FWCore.ParameterSet.Config as cms
from DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer
doubleEle5SWL1RDQM = DQMEDAnalyzer('EmDQM',
genEtaAcc = cms.double(2.5),
genEtAcc = cms.double(2.0),
reqNum = cms.uint32(2),
filters = cms.VPSet(cms.PSet(
PlotBounds = cms.vdouble(0.0, 0.0),
... |
3266960 | from time import sleep
from multiprocessing.dummy import Pool as ThreadPool, Lock
class People(object):
def __init__(self, name, money=5000):
self.name = name
self.lock = Lock()
self.money = money # 设置一个初始金额
def transfer(p_from, p_to, money):
with p_from.lock:
p_from.money -... |
3267017 | from django.views.decorators.csrf import csrf_exempt
from django.conf.urls import re_path
from tg import views
import hashlib
from django.conf import settings
app_name = 'telegram'
urlpatterns = [
re_path(r'^me/$', views.me, name='me'),
re_path(r'^unlink/$', views.unlink, name='unlink'),
re_path(
... |
3267027 | import sys, os
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.dirname(CURRENT_DIR))
from db import Database
''' Every location row has an array of place_id of length 1.
This update converts that array of only one string, to string
'''
for loc in Database.locations.find():
Databa... |
3267155 | from spherov2.commands import Commands
from spherov2.listeners.api_and_shell import ApiProtocolVersion
class ApiAndShell(Commands):
_did = 16
@staticmethod
def ping(toy, data, proc=None) -> bytearray:
return toy._execute(ApiAndShell._encode(toy, 0, proc, data)).data
@staticmethod
def get... |
3267176 | class Solution:
def nextGreaterElements(self, nums: List[int]) -> List[int]:
stack = []
stack.append(0)
res = [-1]*len(nums)
for i in range(1,len(nums)*2):
i %= len(nums)
while stack and nums[i]>nums[stack[-1]]:
idx = stack.pop()
... |
3267216 | import traceback
from django.core.paginator import Paginator
from django.http import Http404, QueryDict
from django.shortcuts import get_object_or_404
from django.utils import timezone
from django.utils.text import slugify
from board.models import *
from modules.response import StatusDone, StatusError
from board.view... |
3267220 | import unittest
import tests.settings_mock as settings_mock
from tests.activity.classes_mock import FakeLogger
from workflow.workflow_DepositCrossref import workflow_DepositCrossref
class TestWorkflowDepositCrossref(unittest.TestCase):
def setUp(self):
self.workflow = workflow_DepositCrossref(
... |
3267255 | import sys
import os
sys.path.append(os.path.abspath(os.path.join('../..', 'app')))
from mongoengine import *
from influxdb import InfluxDBClient
from models.account import StudentModel
from models.apply import ExtensionApply11Model, ExtensionApply12Model
from collections import defaultdict
connect(**{
'db': '... |
3267268 | from django.core.exceptions import FieldDoesNotExist
from django.utils.html import format_html
from django.utils.translation import gettext_lazy as _
from wagtail.admin.edit_handlers import EditHandler
class ReadOnlyPanel(EditHandler):
"""
Read only panel for Wagtail. You can pass in a ``formatter`` function
... |
3267330 | from airflow.contrib.kubernetes.secret import Secret
# GCP service account for dbt operations with BigQuery
# TODO: make this a volume deploy type?
DBT_SERVICE_ACCOUNT = Secret(
# Expose the secret as environment variable.
deploy_type="env",
# The name of the environment variable, since deploy_type is `en... |
3267386 | import unittest
import numpy as np
import torch
from torchcast.utils import TimeSeriesDataset
class TestUtils(unittest.TestCase):
def test_pad_x(self, num_times: int = 10):
from pandas import DataFrame
df = DataFrame({'x1': np.random.randn(num_times), 'x2': np.random.randn(num_times)})
df[... |
3267423 | import cv2
import os
from matplotlib import pyplot as plt
from model import *
from utils import *
import os
import time
import logging
import argparse
import numpy as np
import random
from numpy import expand_dims
from keras.preprocessing.image import load_img, img_to_array
import tensorflow as tf
def main():
pa... |
3267440 | import pickle
def read_dataset(eval_path):
difficult_words = []
pos_tags = []
with open(eval_path, 'r', encoding='utf-8') as reader:
while True:
line = reader.readline()
if not line:
break
row = line.strip().split('\t')
difficult_word,... |
3267446 | from sqlite3 import Cursor
from typing import TYPE_CHECKING, Dict, List, Literal, NamedTuple, Optional, Tuple, Union
from eth_utils import is_checksum_address
from rotkehlchen.accounting.structures.balance import BalanceType
from rotkehlchen.assets.asset import Asset
from rotkehlchen.chain.substrate.types import Kusa... |
3267464 | import numpy as np
import os
import h5py
import argparse
parser = argparse.ArgumentParser(description='Spike Encoding')
parser.add_argument('--save-dir', type=str, default='../datasets', metavar='PARAMS', help='Main Directory to save all encoding results')
parser.add_argument('--save-env', type=str, default='indoor_fl... |
3267491 | import logging
import kubernetes.config as k8s_config
import kubernetes.client as k8s_client
import kopf
from crds.monitor import MonitorV1Beta1, MonitorType
from crds.psp import PspV1Beta1
from crds.maintenance_window import MaintenanceWindowV1Beta1
from crds.alert_contact import AlertContactV1Beta1, AlertContactTyp... |
3267498 | import random
import time
import arcade
from cactus import Cactus
from pterodactyl import Pterodactyl
from dino import Dino
from ground import Ground
DEFAULT_FONT_SIZE = 40
class Game(arcade.Window):
def __init__(self):
self.w = 800
self.h = 600
self.gravity = 0.3
super(... |
3267515 | from website.files.models.base import File, Folder, FileNode
__all__ = ('AzureBlobStorageFile', 'AzureBlobStorageFolder', 'AzureBlobStorageFileNode')
class AzureBlobStorageFileNode(FileNode):
provider = 'azureblobstorage'
class AzureBlobStorageFolder(AzureBlobStorageFileNode, Folder):
pass
class AzureBlo... |
3267527 | from cli_ui.tests import MessageRecorder
from tsrc.test.helpers.cli import CLI
from tsrc.test.helpers.git_server import GitServer
def test_happy(
tsrc_cli: CLI, git_server: GitServer, message_recorder: MessageRecorder
) -> None:
"""
Scenario:
* Create a manifest with two repos, foo and bar
* Init... |
3267588 | import numpy as np
import pytest
import tensorflow as tf
import pytoolkit as tk
def _run(func, *args, **kwargs):
"""funcをグラフモードで実行する。"""
return tf.function(func)(*args, **kwargs)
def test_binary_crossentropy():
# 通常の動作確認
_binary_loss_test(tk.losses.binary_crossentropy, symmetric=True)
# alpha
... |
3267590 | import sys
import os
from typing import List, Tuple, Union
from collections import OrderedDict
import csv
from fuse.metrics.classification.metric_bss import FuseMetricMultiClassBSS
import pandas as pd
import numpy as np
from fuse.utils.utils_hierarchical_dict import FuseUtilsHierarchicalDict
from fuse.utils.utils_fil... |
3267591 | import pandas as pd
def klifs_kinase_from_uniprot_id(uniprot_id: str) -> pd.DataFrame:
"""
Retrieve KLIFS kinase details about the kinase matching the given Uniprot ID.
Parameters
----------
uniprot_id: str
Uniprot identifier.
Returns
-------
kinase: pd.Series
... |
3267596 | import abc
import tweepy
class TweetSelectorInterface(metaclass=abc.ABCMeta):
@classmethod
def __subclasshook__(cls, subclass):
return (hasattr(subclass, 'rate_tweet') and
callable(subclass.rate_tweet) or
NotImplemented)
@abc.abstractmethod
def rate_tweet(self... |
3267599 | import torch
from .generate_dataloader import dataloader, inverse_norm, norm_use_scaler
from .model import LSTMDrop
def evaluate(
lat, lon, test_years, seq_length, model_name, start_date, end_date,
hidden_size, num_layers, **kwargs
):
DROPOUT, BATCH_SIZE = 0, 1
dates, test_loader = dataloader(
... |
3267613 | import numpy as np
import pickle as pkl
import networkx as nx
from networkx.readwrite import json_graph
import scipy.sparse as sp
from scipy.sparse.linalg.eigen.arpack import eigsh
from sklearn.metrics import f1_score
import sys
import tensorflow as tf
import json
from time import time
import os, copy
flags = tf.app.f... |
3267645 | import shlex
from click.testing import CliRunner
import pytest
from line_item_manager import cli
@pytest.mark.parametrize("command",
[
('config'),
('bidders'),
]
)
def test_cli_show_good(command):
runner = CliRunner()
result = runner.invoke(
cli.show,
shlex.split(command)
)
asse... |
3267659 | def none_or(val, func=None, levels=None):
if val is None:
return None
else:
if levels is not None:
if val not in set(levels):
raise KeyError(val)
return val
else:
return func(val)
def try_keys(dictionary, keys):
attempted_keys = ... |
3267665 | from collections import OrderedDict
import numpy as np
import torch.optim as optim
from torch import nn as nn
import torch
from torch import autograd
from torch.autograd import Variable
import torch.nn.functional as F
import rlkit.torch.pytorch_util as ptu
from rlkit.core.eval_util import create_stats_ordered_dict
fr... |
3267695 | from PIL import Image
import os
import numpy as np
import torch
import torchvision
from typing import Any, Callable, List, Optional, Tuple, Union
def pil_loader(path: str) -> Image.Image:
with open(path, 'rb') as f:
img = Image.open(f)
return img.convert('RGB')
class Folder(torch.utils.data.D... |
3267743 | import FWCore.ParameterSet.Config as cms
from RecoBTag.Skimming.btagDijetOutputModuleAODSIM_cfi import *
from RecoBTag.Skimming.btagDijetOutputModuleRECOSIM_cfi import *
|
3267744 | import tensorflow as tf
import numpy as np
from PIL import Image
from PIL import ImageDraw
from PIL import ImageColor
from moviepy.editor import VideoFileClip
SSD_V4 = "retrained_SSD/frozen_inference_graph.pb"
cmap = ImageColor.colormap
COLOR_LIST = sorted([c for c in cmap.keys()])
def filter_boxes(min_score, boxes, ... |
3267781 | import sys
from pathlib import Path
from collections import defaultdict
import yaml
"""
Create stubs for all API reference *.md files
and propose a menu tree (you probably need to edit it to your liking)
Redefine docs and package below and execute from repository root
"""
docs = "apidocs"
package = "kinoml"
here = ... |
3267795 | import getpass
import tempfile
from datetime import datetime
from unittest.mock import call
import pytest
from dateutil.tz import tzutc
from typer.testing import CliRunner
from cli.webapp import app
runner = CliRunner()
@pytest.fixture
def mock_webapp(mocker):
mock_webapp = mocker.patch("cli.webapp.Webapp")
... |
3267862 | from .jsonpipeline import JsonPipeline
from .school_pipeline import SchoolPipeline
from .db_pipeline import DatabasePipeline
|
3267882 | from . import multioutput
from .inducing_patch import InducingPatches
from .inducing_variables import InducingPoints, InducingVariables, Multiscale
from .multioutput import (
FallbackSeparateIndependentInducingVariables,
FallbackSharedIndependentInducingVariables,
MultioutputInducingVariables,
SeparateI... |
3267906 | import torch
from torch import nn
from torch.nn import Parameter
# https://github.com/ajbrock/BigGAN-PyTorch/blob/master/TFHub/biggan_v1.py
def l2normalize(v, eps=1e-4):
return v / (v.norm() + eps)
class SpectralNorm(nn.Module):
def __init__(self, module, name='weight', power_iterations=1):
super(SpectralNorm, se... |
3267984 | from share.transform.chain import * # noqa
from share.transform.chain.utils import format_address
def format_mendeley_address(ctx):
return format_address(
address1=ctx['name'],
city=ctx['city'],
state_or_province=ctx['state'],
country=ctx['country']
)
RELATION_MAP = {
'r... |
3268016 | import os
import numpy as np
import cv2
camera_matrix = np.load("camera_matrix.npy")
dist_coeffs = np.load("dist_coeffs.npy")
new_camera_matrix = np.copy(camera_matrix)
new_camera_matrix[:2, :2] /= 2.
for jpgname in os.listdir("."):
if not jpgname.endswith(".jpg"):
continue
if "undistort" in jpgname:... |
3268023 | from setuptools import setup, find_packages
install_requires = [
'opencv-python >= 4.1.0',
'Pillow >= 6.0.0',
]
setup(
name='bounding_box',
version='0.1.3',
python_requires='>=2.7',
packages=find_packages(),
include_package_data=True,
author='<NAME>',
author_email='<EMAIL>',
... |
3268072 | import queue
import threading
import urllib
from itoolkit.transport import HttpTransport
from itoolkit import *
class iDB2Async():
def __init__(self, isql):
self.itran = HttpTransport('http://yips.idevcloud.com/cgi-bin/xmlcgi.pgm','*NONE','*NONE')
self.itool = iToolKit()
self.itool.add(iSqlQuery('iq... |
3268096 | import os
def import_from(module, name):
module = __import__(module, fromlist=[name])
return getattr(module, name)
def test_grammars():
for fname in os.listdir("parsetron/grammars"):
if fname.endswith('.py') and not fname.startswith("__"):
module = fname[0:-3] # numbers.py -> number... |
3268101 | import torch
import torch.nn as nn
from mmcv.runner import BaseModule
from mmdet.models.builder import HEADS
from ...core import bbox_cxcywh_to_xyxy
@HEADS.register_module()
class InitialQueryGenerator(BaseModule):
"""
This module produces initial content vector $\mathbf{q}$ and positional vector $(x, y, z, ... |
3268107 | import pytest
import allure
from locators.locators import SearchResultsLocators
from pages.phptravels.search_hotels_form import SearchHotelsForm
from utils.read_xlsx import XlsxReader
@pytest.mark.usefixtures("setup")
class TestHotelSearch:
@allure.title("Search hotel test")
@allure.description("This is test... |
3268117 | import os
import sys
import gzip
import time
import numpy
import argparse
import math
import random
import copy
import theano
import denet.model.model_cnn as model_cnn
import denet.dataset as dataset
import denet.common.logging as logging
import denet.common as common
#compute per class error rates
def compute_error(... |
3268152 | import hashlib as hsh
phonebook = {}
def hashthat(name):
hashvalue = hsh.md5(name.encode())
hashed = hashvalue.hexdigest()
return hashed
def addContact(name, num):
h = hashthat(name)
phonebook[h] = {}
phonebook[h]['name'] = name
phonebook[h]['number'] = num
print('Successfully save... |
3268167 | from setuptools import find_packages
from setuptools import setup
setup(
name="trainer",
packages=["trainer", "tfmodel"],
include_package_data=True,
)
|
3268211 | from bs4 import BeautifulSoup
from django.urls import reverse
from django.utils.html import escape as html_escape
from calcification.tests.utils import create_default_calcify_table
from images.model_utils import PointGen
from images.models import Source
from lib.tests.utils import (
BasePermissionTest, ClientTest,... |
3268232 | import tvm.tensor_graph.core2.nn.functional as F
from tvm.tensor_graph.core2.nn.module import Module, Conv2d, BatchNorm2d, ReLU, AvgPool2d, Linear
class YOLOV1(Module):
def __init__(self, channel=3, height=448, width=448, num_classes=1470):
super(YOLOV1, self).__init__()
self.conv1 = Conv2d(chan... |
3268294 | import unittest
from honeygrove.core.FilesystemParser import FilesystemParser
from honeygrove.tests.testresources import __path__ as resources
from honeygrove.tests.testresources import testconfig as config
class FilesystemParserUnixTest(unittest.TestCase):
def setUp(self):
FilesystemParser.honeytoken_di... |
3268299 | from typing import Any, Protocol
from .exceptions import RPCError, RPCUserError, RPCInternalError
from .message import RPCMessage
from .channel import Peer
class FunctionHandler(Protocol):
def __call__(self, request: RPCMessage, /) -> Any: # noqa: E225
...
__all__ = (
'RPCError',
'RPCUserError... |
3268315 | import json
import os
from threading import Thread
from kivy.app import App
from kivy.clock import Clock
from kivy.utils import platform
from util.morse_app_api import MorseAppApi
from .morse_helper import MorseHelper
if platform not in ['ios', 'android']:
from third_party.py_morse_code.morse import Morse, DotDa... |
3268362 | import data_wizard
from .models import CustomSource
data_wizard.set_loader(CustomSource, "tests.source_app.loaders.CustomLoader")
|
3268378 | from zeus import auth, factories
from zeus.constants import Permission
from zeus.models import Repository
def test_tenant_does_not_query_repo_without_access(default_repo):
auth.set_current_tenant(auth.Tenant())
assert list(Repository.query.all()) == []
def test_tenant_queries_repo_with_tenant(default_repo):... |
3268445 | from .main import *
from .tatabahasa import *
from .num2word import to_cardinal, to_ordinal, to_ordinal_num, to_currency, to_year
from .word2vec import *
from .topic import train_lda, train_lsa, train_nmf
from .sentiment import deep_sentiment
|
3268484 | import os
import sys
import intervaltree
import argparse
import logging
logging.basicConfig(format='%(message)s', level=logging.INFO)
def Run(args):
Calc(args)
def Calc(args):
logging.info("Loading BED file ...")
tree = {}
f = subprocess.Popen(shlex.split("gzip -fdc %s" % (args.bed_fn) ), stdout=su... |
3268485 | import sys
import netifaces
from netifaces import AF_INET
from spaceship.core.Handshake import Handshake, ServerBroadcast, BroadcastListener
import argparse
class Main:
def __init__(self):
"""Entry point for the whole project."""
ip = netifaces.ifaddresses("eth0")[AF_INET][0]['addr']
par... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.