id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
3347409 | import torch
import torch.nn as nn
import torch.nn.functional as F
class UNet(nn.Module):
"""U-Net: Convolutional Networks for Biomedical Image Segmentation
based on https://arxiv.org/abs/1505.04597
Args:
num_classes (int): number of classes to segment
n_init_features (int): number of ... |
3347452 | from flask import _request_ctx_stack, current_app, g, request # type: ignore
from jwt import PyJWTError
from notifications_python_client.authentication import (
decode_jwt_token,
decode_token,
epoch_seconds,
get_token_issuer,
)
from notifications_python_client.errors import (
TokenDecodeError,
... |
3347492 | from __future__ import division
from __future__ import print_function
import os
import os.path as osp
import argparse
import logging
from tqdm import tqdm
import importlib
import random
import numpy as np
import torch
from torch.utils.data import DataLoader
import tools.utils as utils
from evaluation import valida... |
3347494 | import torch
import torch.nn.functional as F
import numpy as np
import pdb, os, argparse
from skimage import io
from tqdm import trange
from model.DCF_models import DCF_VGG
from model.DCF_ResNet_models import DCF_ResNet
from model.fusion import fusion
from evaluateSOD.main import evalateSOD
from data import test_datas... |
3347497 | from iepy.preprocess.ner.base import BaseNERRunner
class CombinedNERRunner(BaseNERRunner):
"""A NER runner that is the combination of different NER runners
(therefore, different NERs).
The entities returned by each NER are combined by the method merge_entities
without any check, possibly leading to d... |
3347547 | import numpy as np
from pupper.ServoCalibration import MICROS_PER_RAD, NEUTRAL_ANGLE_DEGREES
from pupper.HardwareConfig import PS4_COLOR, PS4_DEACTIVATED_COLOR
from enum import Enum
# TODO: put these somewhere else
class PWMParams:
def __init__(self):
self.pins = np.array([[2, 14, 18, 23], [3, 15, 27, 24],... |
3347585 | from sqlalchemy import schema
from sqlalchemy import types as sql_types
from sqlalchemy.engine import default
from sqlalchemy.sql import compiler, operators
RESERVED_WORDS = {"asc", "action", "add", "admin", "after", "aggregate", "all", "alter", "always", "and", "any", "as",
"asymmetric", "atomic", "... |
3347588 | from injector import inject
from domain.connection.CheckDatabaseConnectionTableRowCount.CheckDatabaseConnectionTableRowCountCommand import \
CheckDatabaseConnectionTableRowCountCommand
from domain.connection.CheckDatabaseConnectionTableRowCount.CheckDatabaseConnectionTableRowCountRequest import \
CheckDatabase... |
3347637 | from typing import List
from bunq.sdk.exception.api_exception import ApiException
from bunq.sdk.exception.bad_request_exception import BadRequestException
from bunq.sdk.exception.forbidden_exception import ForbiddenException
from bunq.sdk.exception.method_not_allowed_exception import MethodNotAllowedException
from bun... |
3347645 | import logging
class database:
def __init__(self, conn):
self.conn = conn
@staticmethod
def db_schema(db_conn):
db_conn.execute('''CREATE TABLE "computers" (
"id" integer PRIMARY KEY,
"ip" text,
"hostname" text,
"domain" text,
"... |
3347675 | import tokenize, StringIO, token, parser, symbol, compiler, ast, astpp, sys, random, string
from py65asm.assembler import Assembler
from py65emu.mmu import MMU
from symbols import SymbolTable
labels = {
"and": 0,
"or": 0,
"if": 0,
"while": 0,
"gt": 0,
"gte": 0,
... |
3347698 | from django.db import connection
from django.test import TestCase
from django.test.utils import override_settings
from django_mysql.rewrite_query import rewrite_query
from tests.testapp.utils import CaptureLastQuery
class RewriteQueryTests(TestCase):
def test_it_doesnt_touch_normal_queries(self):
self.ch... |
3347735 | import json
import argparse
parser = argparse.ArgumentParser(description='main', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--dataset', default='mag', choices=['mag', 'amazon'])
args = parser.parse_args()
dataset = args.dataset
metadatas = set()
with open(f'../{dataset}_data/motifs.... |
3347749 | from __future__ import absolute_import
from __future__ import print_function
import sys
import os
import numpy as np
# the next line can be removed after installation
sys.path.insert(0, os.path.dirname(os.path.dirname(
os.path.dirname(os.path.abspath(__file__)))))
from veriloggen import *
import veriloggen.thread... |
3347761 | import yt
from yt.extensions.astro_analysis.halo_analysis.halo_catalog import HaloCatalog
# Load the dataset
ds = yt.load("Enzo_64/RD0006/RedshiftOutput0006")
# Load the halo list from a rockstar output for this dataset
halos = yt.load("rockstar_halos/halos_0.0.bin")
# Create the halo catalog from this halo list
hc ... |
3347780 | import os
from argparse import ArgumentParser
# os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" # see issue #152
# os.environ["CUDA_VISIBLE_DEVICES"]="0"
def build_parser():
parser = ArgumentParser()
parser.add_argument('--num_epochs', default=150, help="Number of training epochs (default: 150)", type=int)
... |
3347787 | import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.zone_airflow import ZoneInfiltrationFlowCoefficient
log = logging.getLogger(__name__)
class TestZoneInfiltrationFlowCoefficient(unittest.TestCase):
def setUp(self):
... |
3347795 | from typing import Callable, Optional, Union
from urllib.parse import quote
import manta_lab as ml
def get_tune_url(api, tune_id):
if api.api_key:
project = api.project
if not project:
return
return "{base}/{entity}/{project}/tune/{tune_id}".format(
bas... |
3347820 | from PyQt5 import QtWidgets
class RenameDialog(QtWidgets.QDialog):
"""
parent: SourceWindow that started the new XrefDialog
"""
def __init__(self, parent=None, win=None, element="", info=()):
super(RenameDialog, self).__init__(parent)
self.sourceWin = parent
self.info = i... |
3347884 | import argparse
import json
import os
import pickle
import numpy as np
import torch
from .config import FLAGS
from .torch_model import Generator
class AttrDict(dict):
def __init__(self, *args, **kwargs):
super(AttrDict, self).__init__(*args, **kwargs)
self.__dict__ = self
def load_checkpoint(f... |
3347952 | import tensorflow as tf
from tf_components import *
from models.celeba_1024_haar import *
# from util import *
def build_training_graph_partial(config,partial_level):
tlog('Started building graph','note')
assert partial_level >= 0 and partial_level <= config.model.n_levels, 'level must be >= 0 and <= n_levels'
# d... |
3347994 | import logging
from collections import defaultdict
import trio
logger = logging.getLogger(__name__)
RATE_MEASURE_PERIOD = .25
class TaskStats(trio.abc.Instrument):
"""Trio scheduler Instrument which logs various task stats at termination.
Includes max task wait time, slow task steps, and highest task sche... |
3348032 | import json
import os
from graphviz import Digraph
import cell
class CnnMarcoNode(cell.EnasNode):
def __init__(self, index, operation=None, previous_indexes=None):
self.index = index
self.operation = operation
self.previous_indexes = previous_indexes
def __str__(self):
instance_string = "Index:... |
3348035 | from .base_tracked_repo import BaseTrackedRepo
from .base_tracked_repo import OverrideLevel
from .local_tracked_repo import LocalTrackedRepo
from detect_secrets_server.storage.s3 import S3Storage
from detect_secrets_server.storage.s3 import S3StorageWithLocalGit
class S3TrackedRepo(BaseTrackedRepo):
STORAGE_CLAS... |
3348077 | import json
from django.contrib.auth.models import Group
from rest_framework import authentication, permissions, serializers, viewsets
from exampleapp.models import Author, Comment, Post, Tag
from . import filters
def update_instance(instance, validated_data):
for attr, value in validated_data.items():
... |
3348085 | import random
import operator
import importlib
from functools import partial
import numpy as np
from dso.functions import function_map
from dso.const import make_const_optimizer
from . import constraints
GP_MOD = "deap"
OBJECTS = ["base", "gp", "creator", "tools", "algorithms"]
gp = importlib.import_module(GP_MOD ... |
3348122 | from django.db import connection
from django.db.models import IntegerField, Count, Case, When
from orcamentos.core.models import Proposal, Entry
def proposals():
e = {
'n': {'total': Entry.objects.all().count(),
'entrada': Entry.objects.filter(is_entry=False).count(),
'proposal... |
3348125 | import argparse
import os
import requests
import six
import subprocess
import sys
import tempfile
import yaml
from six.moves.urllib_parse import urljoin, quote_plus, unquote_plus
this_dir = os.path.realpath(os.path.dirname(__file__))
sys.path.append(os.path.realpath(os.path.join(os.pardir, os.pardir)))
from geodata.... |
3348132 | from evernotebot.bot.shortcuts import get_message_caption, get_telegram_link
def on_message_text(bot, message: dict):
user = bot.ctx['user']
html = format_html(message)
telegram_link = get_telegram_link(message)
if telegram_link:
html = f'<div><p><a href="{telegram_link}">{telegram_link}</a></... |
3348173 | class Node():
def __init__(self, data):
self.data = data
self.nextnode = None
self.prevnode = None
def setNextNode(self,node):
self.nextnode = node
def setPrevNode(self,node):
self.prevnode = node
def getNextNode(self):
return self.nextnode
... |
3348179 | def decompress(data_in, destlen):
positions = [0] * 256
cpage_out = bytearray([0] * destlen)
outpos = 0
pos = 0
while outpos < destlen:
value = data_in[pos]
pos += 1
cpage_out[outpos] = value
outpos += 1
repeat = data_in[pos]
pos += 1
backoffs... |
3348205 | import logging
import numpy as np
import dill
from collections import defaultdict
from skipthought import utils
class Batch:
def __init__(self, data, pad_value, go_value, eos_value):
"""Class which creates batch from data and could be passed into
SkipthoughtModel._fill_feed_dict_* methods.
... |
3348213 | import torch
from torch_geometric.data import DataLoader
import torch.optim as optim
import torch.nn.functional as F
from gnn import GNN
import argparse
import time
import numpy as np
### importing OGB
from ogb.graphproppred import PygGraphPropPredDataset, Evaluator
multicls_criterion = torch.nn.CrossEntropyLoss()
... |
3348214 | import pytest
import mock
from awsshell import app
from awsshell import shellcomplete
from awsshell import compat
@pytest.fixture
def errstream():
return compat.StringIO()
def test_can_dispatch_dot_commands():
call_args = []
class CustomHandler(object):
def run(self, command, context):
... |
3348215 | from unittest import TestCase
from pybricks.tools.__stub.__tools import wait
class TestTools(TestCase):
def test_wait(self):
self.assertIsNone(wait(0))
|
3348226 | import os
import dj_database_url
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
REACT_BASE_DIR = os.path.dirname(BASE_DIR)
ALLOWED_HOSTS = os.getenv('ALLOWED_HOSTS', '*').split(',')
# Application definition
INSTALLED_A... |
3348253 | from __future__ import unicode_literals
import functools
import itertools
import re
from .common import InfoExtractor
from ..compat import (
compat_b64decode,
compat_chr,
compat_ord,
compat_str,
compat_urllib_parse_unquote,
compat_urlparse,
compat_zip
)
from ..utils import (
clean_html... |
3348267 | import unittest
import os
import cv2
class TestSceneLobbyVideos(unittest.TestCase):
scene_name = 'lobby'
def _load_screenshot(self, filename):
filepath = os.path.join('test_data', 'movies',
self.scene_name, filename)
def noop(self, context):
pass
def... |
3348409 | from flask import Flask, render_template, request, jsonify
from guesslang import Guess
app = Flask(__name__)
app.config.update(dict(DEBUG=True, SECRET_KEY='development key'))
guess = Guess()
@app.route('/', methods=['GET', 'POST'])
def index():
return render_template('index.html')
@app.route('/language-name... |
3348429 | from __future__ import annotations
import queue
import subprocess
import sys
import threading
from queue import Queue
class InProcessExecution:
def __init__(self, redirect=None, popen=subprocess.Popen):
self.redirect = redirect
self.popen = popen
def execute(self, cmd):
try:
... |
3348430 | from typing import Union
import tornado
import tornado.httputil
import tornado.testing
import tornado.web
ORG_CODE = "org"
SERVICE_ID = "service"
def test_get_handles_missing_params(self):
with self.subTest("Missing Org Code"):
response = self.fetch(self.build_url(org_code=None, service_id=SERVICE_ID), ... |
3348447 | import pytest
import requests
from src.data.orthofoto.other.fitting_bbox import FittingBbox
from src.data.orthofoto.other.url_builder import UrlBuilder
@pytest.fixture(scope='module')
def urls(small_bbox):
url_builder = UrlBuilder()
fitting_box = FittingBbox()
t_minx, t_miny, t_maxx, t_maxy = fitting_box... |
3348491 | import os
import ctypes
import multiprocessing
import logging
log = logging.getLogger(__name__)
FILE_DIR = os.path.dirname(os.path.abspath(__file__))
SRC_PORT = 20130
DST_PORT = 20130
PACKET_RX_RING = 5
PACKET_TX_RING = 13
class Ring(ctypes.Structure):
pass
class BandwidthController(multiprocessing.Process):
... |
3348492 | import torch
import torch.nn as nn
import torch.autograd as autograd
def Hvp_vec(grad_vec, params, vec, retain_graph=False):
'''
return Hessian vector product
'''
grad_grad = autograd.grad(grad_vec, params, grad_outputs=vec, retain_graph=retain_graph,
allow_unused=True)
... |
3348518 | import numpy as np
from PuzzleLib.Backend import gpuarray
from PuzzleLib.Backend.gpuarray import memoryPool as memPool
from PuzzleLib.Modules.Module import ModuleError, Module
class Slice(Module):
def __init__(self, slc=None, name=None):
super().__init__(name)
self.registerBlueprint(locals())
self.slc = slc... |
3348520 | num_version = (0, 2, 0)
version = '.'.join([str(num) for num in num_version])
classifiers = [
'Development Status :: 3 - Alpha',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: ... |
3348531 | from django.core.exceptions import ImproperlyConfigured
from django.db.models import F, fields
from django.db.models.functions import Cast, Coalesce
from django.utils.translation import gettext_lazy as _
from .conf import get_default_language, get_fallback_chain, get_modeltrans_setting
from .utils import (
Fallbac... |
3348556 | from todo_project.page_objects import Page
from .elements import AFazer, Fazendo, Pronto, Todo
class PageTodo(Page):
a_fazer = AFazer()
fazendo = Fazendo()
pronto = Pronto()
todo = Todo()
|
3348600 | from wallet import Wallet
wallet = Wallet()
account = wallet.getaccount()
for subaccount in account.itervalues():
print "Address: ", subaccount['address']
print "Public key: ", subaccount['public_key']
print "Private key: ", subaccount['private_key']
print "Balance: ", subaccount['balance']
print ... |
3348601 | import cv2
import copy
import numpy as np
def Airlight(HazeImg, AirlightMethod, windowSize):
if(AirlightMethod.lower() == 'fast'):
A = []
if(len(HazeImg.shape) == 3):
for ch in range(len(HazeImg.shape)):
kernel = np.ones((windowSize, windowSize), np.uint8)
... |
3348611 | import json
import warnings
from coreapi.document import Object, Link
from rest_framework import exceptions
from rest_framework.permissions import AllowAny
from rest_framework.renderers import CoreJSONRenderer
from rest_framework.response import Response
from rest_framework.schemas import SchemaGenerator, AutoSchema ... |
3348630 | import abc
from algotrader.utils.model import get_model_id
class HasId(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def id(self) -> str:
raise NotImplementedError()
class Startable(object):
__metaclass__ = abc.ABCMeta
def __init__(self):
self.started = False
de... |
3348663 | from .rest import RestClient
class Prompts(object):
"""Auth0 prompts endpoints
Args:
domain (str): Your Auth0 domain, e.g: 'username.auth0.com'
token (str): Management API v2 Token
telemetry (bool, optional): Enable or disable Telemetry
(defaults to True)
timeou... |
3348664 | import argparse, os
import matplotlib
matplotlib.use('Agg')
import torch
from evaluate import evaluate_synthesis, evaluate_projection
import numpy as np
from synth.synthesize import create_synth
from utils.data import get_external_sounds
parser = argparse.ArgumentParser()
parser.add_argument('--model_path', type=st... |
3348668 | import numpy as np
import pytest
from .. import SlidingWindowSegmenter
@pytest.mark.parametrize(
'multilingual_test_inputs, window_size, step_size',
[
('It is a sunny day!!!! When Andy comes back, we are going to the zoo.', 20, 10),
('It is a sunny day!!!! When Andy comes back, we are going t... |
3348717 | from __future__ import absolute_import
# flake8: noqa
# import apis into api package
from isi_sdk_7_2.api.audit_api import AuditApi
from isi_sdk_7_2.api.auth_api import AuthApi
from isi_sdk_7_2.api.auth_groups_api import AuthGroupsApi
from isi_sdk_7_2.api.auth_providers_api import AuthProvidersApi
from isi_sdk_7_2.ap... |
3348720 | from copy import copy
import numpy as np
import pymc as pm
np.seterr(divide="ignore")
from sys import stdout
import hddm
from scipy.stats import scoreatpercentile
from time import time
from operator import attrgetter
def check_model(model, params_true, assert_=False, conf_interval=95):
"""calculate the posterio... |
3348724 | from deeppavlov.core.common.registry import register
from deeppavlov.core.models.component import Component
from deeppavlov.core.commands.utils import expand_path
from deeppavlov.core.common.file import load_pickle
@register("q_to_page")
class QToPage(Component):
def __init__(self, q_to_page_filename, entities_nu... |
3348729 | import adsk.core
import adsk.fusion
import adsk.cam
import traceback
from .Fusion360Utilities.Fusion360Utilities import get_app_objects
from .Fusion360Utilities.Fusion360CommandBase import Fusion360CommandBase
from .SheetsService import sheets_get_ranges, get_sheets_service, sheets_update_values
from .SheeterUtilities... |
3348754 | import typing as t
from urllib.parse import unquote
from .router import Router
from .utils import parse_path, INDENTITY
class RouteMatch:
"""Keeping route matching data."""
__slots__ = 'path', 'method', 'target', 'params'
def __init__(self, path: bool, method: bool,
target: t.Any = Non... |
3348770 | import FWCore.ParameterSet.Config as cms
from Configuration.Generator.Pythia8CommonSettings_cfi import *
from Configuration.Generator.Pythia8CUEP8M1Settings_cfi import *
generator = cms.EDFilter("Pythia8ConcurrentGeneratorFilter",
pythiaHepMCVerbosity = cms.untracked.bool(False),
... |
3348801 | from brownie import (HomoraBank, UniswapV2SpellV1, SushiswapSpellV1, BalancerSpellV1,
CurveSpellV1, WERC20, WMasterChef, WLiquidityGauge, WStakingRewards)
from brownie import interface, accounts, Contract
from .utils_fork import *
def test_uniswap_spell(bank, uniswap_spell):
alice = accounts[... |
3348804 | from flask import Flask, render_template, flash, redirect, session, url_for, request, g, Markup, jsonify, abort
import requests
import imageio
import torch
import time
import matplotlib.pyplot as plt
from core import Product
app = Flask(__name__)
# name = "AVHRR_OI_L4_GHRSST_NCEI"
name = "20190914_GHRSST"
product = ... |
3348864 | from copy import deepcopy
import re
import sys
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group as DjangoGroup
from django.test import TestCase
from groups_manager import models, exceptions_gm
GROUPS_MANAGER_MOCK = {
'AUTH_MODELS_SYNC': True,
'AUTH_MODELS_GET_OR_CR... |
3348878 | import unittest
from datahub.utilities.urns.data_process_instance_urn import DataProcessInstanceUrn
from datahub.utilities.urns.error import InvalidUrnError
class TestDomainUrn(unittest.TestCase):
def test_parse_urn(self) -> None:
dataprocessinstance_urn_str = "urn:li:dataProcessInstance:abc"
dat... |
3348909 | i = 123456789012345678901234567890
print(i >> 1)
print(i >> 1000)
# result needs rounding up
i = -(1 << 70)
print(i >> 80)
i = -0xffffffffffffffff
print(i >> 32)
|
3348980 | from poop.hfdp.command.remote.ceiling_fan import CeilingFan
class CeilingFanOnCommand:
def __init__(self, ceiling_fan: CeilingFan) -> None:
self.__ceiling_fan = ceiling_fan
def execute(self) -> None:
self.__ceiling_fan.high()
|
3348991 | from curio import run, spawn, tcp_server
from socket import *
async def echo_handler(client, addr):
print('Connection from', addr)
try:
client.setsockopt(IPPROTO_TCP, TCP_NODELAY, 1)
except (OSError, NameError):
pass
s = client.as_stream()
while True:
data = await s.readline... |
3349024 | from unittest.mock import patch
from pythonit_toolkit.emails.backends.local import LocalEmailBackend
from pythonit_toolkit.emails.templates import EmailTemplate
from ward import test
@test("send email just logs the email sent")
async def _():
with patch("pythonit_toolkit.emails.backends.local.print") as mock_log... |
3349041 | import unittest
import time
from collections.abc import Iterable
import numpy as np
import openmdao.api as om
from openmdao.utils.mpi import MPI
from openmdao.utils.array_utils import evenly_distrib_idxs, take_nth
from openmdao.utils.assert_utils import assert_near_equal, assert_warning
try:
from parameterized i... |
3349092 | from __future__ import division, print_function, absolute_import
import pytest
from scipy.special._testutils import MissingModule, check_version
from scipy.special._mptestutils import mp_assert_allclose
from scipy.special._precompute.utils import lagrange_inversion
try:
import sympy
except ImportError:
sympy ... |
3349095 | import json
import subprocess
import time
import pytest
from pprint import pprint
from htdfsdk import HtdfRPC, HtdfTxBuilder, htdf_to_satoshi, Address, HtdfPrivateKey
@pytest.fixture(scope="module", autouse=True)
def check_balance(conftest_args):
print("====> check_balance <=======")
htdfrpc = HtdfRPC(chaid_... |
3349097 | import stribor as st
import torch
import torch.nn as nn
import torch.nn.functional as F
class Coupling(nn.Module):
"""
Coupling transformation via elementwise flows. If `dim = 1`, set `mask = 'none'`.
Splits data into 2 parts based on a mask. One part generates parameters of the flow
that wi... |
3349110 | road_info_dict = {
0:'isonroad',
1:'cannotaccessroadinfo',
2:'forwardVectorX',
3:'forwardVectorY',
4:'forwardVectorZ',
5:'velocityX',
6:'velocityY',
7:'velocityZ',
8:'roadVectorX',
9:'roadVectorY',
10:'roadVectorZ',
11:'leftroadpointX',
12:'leftroadpointY',
13:'leftroadpointZ',
14:'rightroadpointX',
15:'rightroadpointY... |
3349131 | from __future__ import print_function
import os
from datetime import date
from setuptools import setup, find_packages
# --- import your package ---
directory = os.path.dirname(os.path.abspath(__file__))
VERSION = '0.1.5'
SHORT_DESCRIPTION = "A tool for text counterfactual generation."
LICENSE = "BSD 3-Clause License"... |
3349138 | import fire
import wandb
from transformers import Seq2SeqTrainer, Seq2SeqTrainingArguments, default_data_collator
from manga_ocr_dev.env import TRAIN_ROOT
from manga_ocr_dev.training.dataset import MangaDataset
from manga_ocr_dev.training.get_model import get_model
from manga_ocr_dev.training.metrics import Metrics
... |
3349143 | from .parser import GeneSummaryParser
import biothings.hub.dataload.uploader as uploader
class EntrezGeneSummaryUploader(uploader.MergerSourceUploader):
name = "entrez_genesummary"
main_source = "refseq"
def load_data(self, data_folder):
gene2summary = GeneSummaryParser(data_folder).load()
... |
3349158 | from ple.games.catcher import Catcher
from ple import PLE
import numpy as np
import random
class RandomAgent:
def __init__(self, actions):
self.actions = actions
def pickAction(self, state, reward):
return random.choice(self.actions)
'''
State Formate:
{
'player_x': int,
'player_vel': float,
'fruit_x... |
3349163 | from tests.helpers import *
from CTFd.models import Teams, Challenges
from CTFd.utils import get_config, set_config, override_template, sendmail, verify_email, ctf_started, ctf_ended
from CTFd.plugins.challenges import get_chal_class
from freezegun import freeze_time
from mock import patch
def test_admin_post_config_... |
3349172 | input_file = "data/zinc.tab"
output_file = "data/zinc.txt"
with open(input_file, 'r') as fin, open(output_file, 'w') as fout:
lines = fin.readlines()
lines = lines[1:]
for line in lines:
line = line.strip()
line = line[1:-1]
fout.write(line + '\n')
|
3349177 | import os
os.environ["CUDA_VISIBLE_DEVICES"]="0"
import socket
import sys
import tensorflow as tf
import numpy as np
from data_loaders.zhangfeats_loader import zhangfeats_loader
from arch.layer_factory import layer_factory
flags = tf.flags
#MDN Params
flags.DEFINE_integer("feats_height", 28, "")
flags.DEFINE_integ... |
3349184 | import pytest
import numpy as np
from numpy.testing import assert_allclose
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import det_curve
from sklearn.metrics import DetCurveDisplay
@pytest.mark.parametrize("constructor_name", ["from_estimator", "fro... |
3349236 | import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from sklearn.datasets import make_blobs
from sklearn.neighbors import kneighbors_graph
# Set random seed for reproducibility
np.random.seed(1000)
nb_samples = 2000
nb_unlabeled = 1950
nb_classes = 2
if __name__ == '__main__':
X, Y = mak... |
3349248 | from django import forms
from repositories.models import Repository, Credential
from repositories.managers import RepositoryManager
import repository
class RepositoryChoiceField(forms.ModelChoiceField):
def label_from_instance(self, obj):
return obj.name
class RepositoryForm(forms.ModelForm):
class Me... |
3349274 | import os.path
import pickle
import shutil
import tempfile
import unittest
import pcl
import numpy as np
_data = [(i, 2 * i, 3 * i + 0.2) for i in range(5)]
_DATA = """0.0, 0.0, 0.2;
1.0, 2.0, 3.2;
2.0, 4.0, 6.2;
3.0, 6.0, 9.2;
4.0, 8.0, 12.2"""
from nose.plugins.attrib i... |
3349279 | import pytest
import six
from flexmock import flexmock
from sqlalchemy_utils import i18n
from sqlalchemy_utils.primitives import WeekDay, WeekDays
@pytest.fixture
def set_get_locale():
i18n.get_locale = lambda: i18n.babel.Locale('fi')
@pytest.mark.skipif('i18n.babel is None')
@pytest.mark.usefixtures('set_get_... |
3349283 | from pyramid.security import ALL_PERMISSIONS
from pyramid.security import DENY_ALL
from pyramid.security import Allow
from pyramid.security import Everyone
from sqlalchemy import Column, Integer, Text, Unicode
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session, sessionmake... |
3349288 | import numpy as np
SCORING = {
'linear': lambda y, yh: y - yh,
'square': lambda y, yh: np.square(y - yh),
'absolute': lambda y, yh: np.abs(y - yh),
'exponential': lambda y, yh: 1 - np.exp(-np.abs(y - yh)),
'poisson': lambda y, yh: yh.clip(1e-6) - y * np.log(yh.clip(1e-6)),
'hamming': lambda y,... |
3349346 | from .conv_module import ConvModule
from .norm import build_norm_layer
from .weight_init import (xavier_init, normal_init, uniform_init, kaiming_init,
bias_init_with_prob)
from .empty import Empty
from .sequential import Sequential
import inspect
import torch
def get_paddings_indicator(actual... |
3349354 | import torch
def one_hot(src, num_classes=None, dtype=None):
src = src.to(torch.long)
src = src.unsqueeze(-1) if src.dim() == 1 else src
assert src.dim() == 2
if num_classes is None:
num_classes = src.max(dim=0)[0] + 1
elif isinstance(num_classes, int) or isinstance(num_classes, float):
... |
3349392 | import json
import os
import pandas as pd
from ..version import __version__
from .description import describe_label_times
from .plots import LabelPlots
SCHEMA_VERSION = "0.1.0"
class LabelTimes(pd.DataFrame):
"""The data frame that contains labels and cutoff times for the target entity."""
def __init__(
... |
3349460 | import unittest
import pyx12.map_index
import pyx12.params
class GetFilename(unittest.TestCase):
"""
"""
def setUp(self):
param = pyx12.params.params()
self.idx = pyx12.map_index.map_index()
def test_get_837p(self):
self.assertEqual(self.idx.get_filename(
'00401',... |
3349488 | from functools import wraps
from pathlib import Path
import re
from typing import List
from spython.main import Client as client
from oremda.clients.base.client import ClientBase
from oremda.clients.singularity.container import SingularityContainer
from oremda.clients.singularity.image import SingularityImage
from or... |
3349491 | import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
# Set random seed for reproducibility
np.random.seed(1000)
width = 15
height = 5
y_final = width - 1
x_final = height - 1
y_wells = [0, 1, 3, 5, 5, 7, 9, 11, 12, 14]
x_wells = [3, 1, 2, 0, 4, 1, 3, 2, 4, 1]
gamma = 0.... |
3349519 | try:
from unittest import mock
except ImportError:
import mock
from django.urls import reverse
from django.test import TestCase
from django.test.utils import override_settings
from django_push import UA
from django_push.publisher import ping_hub
class PubTestCase(TestCase):
@mock.patch('requests.post')
... |
3349531 | from __future__ import with_statement
import py
import sys
from rpython.rlib.parsing.tree import Nonterminal, Symbol, RPythonVisitor
from rpython.rlib.parsing.codebuilder import Codebuilder
from rpython.rlib.objectmodel import we_are_translated
class BacktrackException(Exception):
def __init__(self, error=None):
... |
3349579 | from flask import current_app
from marshmallow import fields
from marshmallow.exceptions import ValidationError
from zeus.exceptions import UnknownRevision
from zeus.utils import revisions
class RevisionRefField(fields.Str):
def __init__(self, validate_ref=True, resolve_to=None, *args, **kwargs):
self.va... |
3349587 | import io
import discord
from discord.utils import get
from discord.ext import commands
from discord.errors import NotFound
from contextlib import suppress
import asyncio
class Context(commands.Context):
"""
custom Context object passed in every ctx variable
in your commands. provides some useful getter s... |
3349623 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from models.model import model
import sys, os, pdb
import numpy as np
np.random.seed(1)
import utils.dgm as dgm
import tensorflow as tf
tf.set_random_seed(1)
import keras
from keras.layers import Input, D... |
3349635 | class Solution:
def maximumProduct(self, nums: List[int]) -> int:
# min1, min2, .... max3, max2, max1
min1, min2, max3, max2, max1 = float('inf'), float('inf'), float('-inf'), float('-inf'), float('-inf')
for num in nums:
if num <= min1:
min2, min1 = min1, num
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.