id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1757817 | import torch
from torch import nn
from torch.nn import functional as F
import torchvision
class Flatten(nn.Module):
def forward(self, input):
return input.view(input.size(0), -1)
class UnFlatten(nn.Module):
def forward(self, input, size=256):
return input.view(input.size(0), size, 3, 8)
... |
1757837 | import compas_rrc as rrc
if __name__ == '__main__':
# Create Ros Client
ros = rrc.RosClient()
ros.run()
# Create ABB Client
abb = rrc.AbbClient(ros, '/rob1')
print('Connected.')
# Set tool
abb.send(rrc.SetTool('tool0'))
# Set work object
abb.send(rrc.SetWorkObject('wobj0'))
... |
1757843 | import argparse
from uqcsbot import bot, Command
from bs4 import BeautifulSoup
from datetime import datetime
from requests.exceptions import RequestException
from typing import List
from uqcsbot.utils.command_utils import loading_status, UsageSyntaxException
import requests
MAX_COUPONS = 10 # Prevents abuse
COUPONESE... |
1757857 | from datetime import datetime, timedelta
from flask import url_for, request, flash, redirect
from flask_login import current_user
from flask_rauth import RauthOAuth2, RauthOAuth1
from flaskext.babel import lazy_gettext as _
from ..models import db, Key, User
from ..views import auth
class AbstractRAuth(object):
... |
1757858 | from django.contrib import admin
from django.utils.translation import gettext_lazy as _
from util import html_utils
from web.multilingual.admin import MultiLingualFieldAdmin
from .models import Equipment
class EquipmentAdmin(MultiLingualFieldAdmin):
list_display = ('title', 'get_image', 'priority')
search_fi... |
1757880 | import lldb
from lldbsuite.test.lldbtest import *
from lldbsuite.test.decorators import *
import lldbsuite.test.lldbutil as lldbutil
import os
import unittest2
class TestSwiftRewriteClangPaths(TestBase):
mydir = TestBase.compute_mydir(__file__)
def setUp(self):
TestBase.setUp(self)
@skipUnlessDa... |
1757913 | import unittest
from fftoptionlib.characteristic_funs import (
black_schole_log_st_chf,
merton_jump_log_st_chf,
poisson_log_st_chf,
diffusion_chf,
cpp_normal_chf,
kou_jump_log_st_chf,
double_exponential_chf,
poisson_chf,
vg_log_st_chf,
nig_log_st_chf,
)
from fftoptionlib.moment_... |
1757922 | import numpy as np
from gym.spaces import Dict
from rlkit.data_management.replay_buffer import ReplayBuffer
from rlkit.torch.relational.relational_util import get_masks, pad_obs
class ObsDictRelabelingBuffer(ReplayBuffer):
"""
Replay buffer for environments whose observations are dictionaries, such as
... |
1757951 | class SpamNotFound(Exception):
"""When the system can't find spam the user defined"""
class B16DecodingFail(Exception):
"""When decoding from B16 fails"""
|
1757980 | from random import randint
a = ["Rock", "Paper", "Scissors"]
computer = a[randint(0, 2)]
player = True
while player == True:
player = input("Rock, Paper, Scissors? ")
print("Opponent chose {}".format(computer))
if player == computer:
print("It's a tie!")
elif player == "Rock":
if c... |
1757984 | import polars as pl
import functools as ft
from .utils import _as_list, _col_expr
__all__ = [
"paste",
"paste0",
"str_c",
"str_detect",
"str_extract",
"str_length",
"str_remove_all",
"str_remove",
"str_replace_all",
"str_replace",
"str_ends",
"str_starts",
"str_s... |
1757994 | import socket
DEFAULT_DEBUG_PORT = 1044
def get_port_not_in_use(first_port) -> int:
port_range = range(first_port, 9999)
for port in port_range:
if not is_port_in_use(port):
return port
raise RuntimeError("No port available in range {}".format(port_range))
def is_port_in_use(port: ... |
1758022 | from . import Bench201
from . import BenchNatsss
from .Networks import get_network, get_num_networks, get_search_space_names
from .Metrics import get_metrics, get_metric_names
|
1758038 | import numpy as np
x = np.array([[1, 3, 5], [7, 9, 11]])
y = np.array([[1, 2], [3, 4], [5, 6]])
print(np.dot(x, y)) #行列積
'''
[[ 35 44]
[ 89 116]]
'''
print(x.dot(y)) #行列積
'''
[[ 35 44]
[ 89 116]]
'''
print(x @ y) #行列積
'''
[[ 35 44]
[ 89 116]]
''' |
1758044 | import time
import json
class Head:
def __init__(self):
self._next = self
class Entry:
def __init__(self, cache, stringified, value):
self._cache = cache
self._stringified = stringified
self.when = time.time()
self._next = cache._head._next
self._previous = cach... |
1758069 | import queue
import os, sqlite3
import re
from time import sleep
import threading
import datetime
import flask
import traceback
try:
import simplejson as json
except ImportError:
import json
import copy
import logging
from cbint.utils.templates import binary_template
import dateutil.parser
epoch = datetime.da... |
1758151 | from app.models import RevokedTokens
import mongoengine
class Token:
def __init__(self, token):
self.token = token
def blacklist(self):
try:
profile = RevokedTokens(token=self.token).save()
result = {'result': 'success', 'message': 'Succesfully added token to blacklis... |
1758153 | import os.path, sys
import platform
import distutils.util
# Append the directory in which the binaries were placed to Python's sys.path,
# then import the D DLL.
libDir = os.path.join('build', 'lib.%s-%s' % (
distutils.util.get_platform(),
'.'.join(str(v) for v in sys.version_info[:2])
))
sys.path.append(os.... |
1758158 | from bot.userstorage import MissingUserDatabaseURLError
import pytest
from bot.userstorage import UserStorage
class TestUserStorage:
def test_requires_db_url(self):
with pytest.raises(MissingUserDatabaseURLError):
UserStorage(None)
|
1758168 | from turtle import *
from math import *
from time import sleep
setup()
up()
#speed('normal') #probably redundant at this stage if using delay(0)
#set to middle of the screen I think. I'm commenting a lot of this code more than a year after writing it / learning turtle&python
home()
tracer(0, 0) # make drawing faster... |
1758171 | import csv, os, json
import numpy as np
import time
import progressbar
from math import *
from visible_star import VisibleStar
from nearest_neighbor_map import OrderedGroupOfStars
from cubemap import Cubemap
from bucket_grid import BucketGrid
from PIL import Image
import pandas as pd
from matplotlib import pyplot as pl... |
1758205 | import pytest
from croo.croo import Croo
@pytest.mark.parametrize(
'croo_out_def_json, expected_relpaths',
[
(
{"main.t_main_1": {"out": {"path": "main.t_main_1/${i}/${basename}"}}},
['main.t_main_1/1/t_main_1.1.out', 'main.t_main_1/0/t_main_1.0.out'],
),
(
... |
1758215 | from enum import IntEnum
class CompressionType(IntEnum):
NONE = 0
LZMA = 1
LZ4 = 2
LZ4HC = 3
LZHAM = 4
class NodeFlags(IntEnum):
Default = 0
Directory = 1
Deleted = 2
SerializedFile = 3
class RuntimePlatform(IntEnum):
OSXEditor = 0
OSXPlayer = 1
WindowsPlayer = 2
OSXWebPlayer = 3
OSXDashboardPlayer ... |
1758233 | import dash_bootstrap_components as dbc
from dash import html
left_jumbotron = dbc.Col(
html.Div(
[
html.H2("Change the background", className="display-3"),
html.Hr(className="my-2"),
html.P(
"Swap the background-color utility and add a `.text-*` color "
... |
1758260 | from autumn.projects.covid_19.mixing_optimisation.constants import PHASE_2_START_TIME
from autumn.models.covid_19.mixing_matrix import (
build_dynamic_mixing_matrix,
)
from autumn.tools.inputs.demography.queries import get_iso3_from_country_name
from .mixing_opti import build_params_for_phases_2_and_3
# FIXME th... |
1758317 | import FWCore.ParameterSet.Config as cms
process = cms.Process("MERGE")
process.source = cms.Source("EmptySource")
process.thing = cms.EDProducer ("IntProducer")
process.o = cms.Path(process.thing)
|
1758330 | from os import path
from urllib import request
import numpy as np
import pandas as pd
import torch
from sklearn.model_selection import train_test_split
from datasets import AbstractDataset
class GermanDataset(AbstractDataset):
column_names = [
'status', 'months', 'credit_history', 'purpose', 'credit_amo... |
1758386 | import os
import re
import sys
import logging
import argparse
from enum import Enum
from fractions import Fraction
from typing import List
import mugen.video.video_filters as vf
from mugen import MusicVideoGenerator, VideoFilter
from mugen import paths
from mugen import utility as util
from mugen.events import EventLi... |
1758415 | import os
from install.download_bin import download, PYTORCH_ROOT # type: ignore[import]
# This dictionary maps each platform to the S3 object URL for its clang-format binary.
PLATFORM_TO_CF_URL = {
"Darwin": "https://oss-clang-format.s3.us-east-2.amazonaws.com/mac/clang-format-mojave",
"Linux": "https://oss-... |
1758454 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
def box_propagation(keypoints, flow):
"""Box propagation from previous frame.
Arguments:
keypoints (ndarray): [num_people, num_keypoints, 3] (x, y, score)
... |
1758459 | import os
os.environ["KERAS_BACKEND"] = 'tensorflow'
from test_tube import HyperOptArgumentParser
from floor.util_scripts.test_model import test_model
import pandas as pd
"""
Tests a folder of models
"""
def test_all_models(hparams):
results = []
for model_file in os.listdir(hparams.models_path):
if... |
1758463 | import os
import json
import pickle
import logging
from urllib.request import urlretrieve
import torch
from torch import nn
from wavegan import WaveGANGenerator
from coala import TagEncoder, AudioEncoder
from audio_prepro import preprocess_audio
logging.basicConfig(level = logging.INFO)
class Word2Wave(nn.Module):
... |
1758495 | import torch
import torch.nn as nn
class ProjHead(nn.Module):
'''
Nonlinear projection head that maps the extracted motion features to the embedding space
'''
def __init__(self, feat_dim, hidden_dim, head_dim):
super(ProjHead, self).__init__()
self.head = nn.Sequential(
nn.L... |
1758504 | import functools
import operator
from django.db.models import Q
from django.utils.translation import gettext
from django_filters import CharFilter, ChoiceFilter
class AnyChoiceFilter(ChoiceFilter):
"""
Extended ChoiceFilter which adds an "any" choice to the choices from the
field / provided options by se... |
1758521 | import typing as T
class BaseView:
def __init__(self, screen: T.Any) -> None:
self.screen = screen
def start(self) -> None:
pass
def stop(self) -> None:
pass
def idle(self) -> None:
pass
def keypress(self, key: int) -> None:
pass
|
1758533 | import json as _json
from ..types import record
__all__ = ["JSONEncoder", "dump", "dumps", "load", "loads"]
class JSONEncoder(_json.JSONEncoder):
def default(self, o):
try:
method = o.__json__
except AttributeError:
return super().default(o)
else:
retu... |
1758548 | import os.path as osp
import cv2 as cv
import numpy as np
from torch.utils.data import Dataset
from PIL import Image
from sklearn.model_selection import StratifiedKFold
class FivePointsAligner():
"""This class performs face alignmet by five reference points"""
ref_landmarks = np.array([30.2946 / 96, 51.6963 ... |
1758556 | import os
import ldap
from django_auth_ldap.config import LDAPSearch, GroupOfNamesType
PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
PACKAGE_ROOT = os.path.abspath(os.path.dirname(__file__))
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = [
# ("<NAME>", "<EMAIL>"),
]
MANAGERS... |
1758577 | import sys
import pysam
import subprocess
from re import sub
import os
from itertools import izip
bamsortfn = sys.argv[1]
bamrepairedfn = sub('.sorted.bam$', ".repaired.bam", bamsortfn)
bamrepairedsortfn = sub('.sorted.bam$', ".repaired.sorted.bam", bamsortfn)
if(os.path.isfile(bamsortfn)):
inbam = pysam.Samfi... |
1758586 | import pytrap
import json
c = pytrap.TrapCtx()
c.init(["-i", "f:/dev/stdout:w"], 0, 1)
a = json.dumps({"a": 123, "b": "aaa"})
c.setDataFmt(0, pytrap.FMT_JSON, "JSON")
c.send(bytearray(a, "utf-8"))
c.finalize()
print("\nFinished")
|
1758593 | from collections import OrderedDict
import numpy as np
def get_vocab(text):
"""Get all tokens"""
vocab = OrderedDict()
i = 0
for word in text:
if word not in vocab:
vocab[word] = i
i += 1
return vocab
def get_token_pairs(window_size, text):
"""Build token_pai... |
1758597 | import FWCore.ParameterSet.Config as cms
from Validation.RecoParticleFlow.Filter_cfi import metFilter
Filter = cms.Sequence(
metFilter
)
|
1758638 | from unittest.mock import patch
from geocube.logger import get_logger, log_to_console, log_to_file
def test_log_to_console(capsys):
log_to_console(False) # clear any other loggers
log_to_console(level="INFO")
logm = get_logger()
logm.info("here")
captured = capsys.readouterr()
assert "INFO-g... |
1758639 | from if_name_main_pkg.bad_script import UsefulClass
import pickle
def main():
with open('test.pickle', 'wb') as f:
x = UsefulClass(0)
pickle.dump(x, f)
if __name__ == '__main__':
main()
|
1758660 | from ballet.eng.base import *
from ballet.eng.misc import *
from ballet.eng.missing import *
from ballet.eng.ts import *
# needed for sphinx
from ballet.eng.base import __all__ as _base_all
from ballet.eng.misc import __all__ as _misc_all
from ballet.eng.missing import __all__ as _missing_all
from ballet.eng.ts import... |
1758679 | import torch.nn.functional as F
from torch import nn
class CrossEntropyLoss(nn.Module):
def __init__(self, weight=None, ignore_index=255, reduction='mean'):
''' NLLLoss: negative log likelihood loss.
# nll_loss: weights: None | a tensor of size C
pred in [N, C, d1, d2, .... |
1758699 | import os
from tests.config import redis_cache_server
EXTENSIONS = (
'lux.ext.base',
'lux.ext.rest',
'lux.ext.content',
'lux.ext.admin',
'lux.ext.auth',
'lux.ext.odm'
)
APP_NAME = COPYRIGHT = HTML_TITLE = 'website.com'
SECRET_KEY = '<KEY>'
SESSION_STORE = redis_cache_server
EMAIL_DEFAULT_FRO... |
1758704 | import traceback
from spikeforest2_utils import AutoRecordingExtractor
class Recording:
def __init__(self):
super().__init__()
self._recording = None
def javascript_state_changed(self, prev_state, state):
self._set_status('running', 'Running Recording')
if not self._recording:
... |
1758727 | import tensorflow as tf
from tfsnippet.ops import assert_shape_equal
from tfsnippet.utils import (add_name_and_scope_arg_doc, get_static_shape,
validate_enum_arg, assert_deps,
get_shape)
from .base import FeatureMappingFlow
from .utils import SigmoidScale, ExpS... |
1758747 | from itertools import cycle
from bokeh.plotting import figure
from bokeh.layouts import layout, gridplot
from bokeh.models.widgets import (
Button, RadioButtonGroup, Spinner,
Slider, RangeSlider, Select
)
from bokeh.models.widgets.tables import DataTable, TableColumn, NumberFormatter
from bokeh.models.callback... |
1758749 | import cfscrape
import sys
scraper = cfscrape.create_scraper()
url = sys.argv[1]
print scraper.get(url).content |
1758756 | import logging
from settings.secrets import GR_API_KEY
from google.appengine.api import urlfetch
from google.appengine.ext import ndb
from lxml import etree
from StringIO import StringIO
from models import Readable
from constants import READABLE
import urllib
def get_books_on_shelf(user, shelf='currently-reading'):
... |
1758766 | import logging
logging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__) |
1758827 | from .datasets_basic import Dataset as BasicDataset
from .datasets_multithread import COCODataset
from .datasets_multithread import Dataset as BasicCOCODataset
def Dataset(datadir, img_size, batch_size, n_embed, mode, multithread=True):
# we don't create multithread loader for bird and flower
# because we n... |
1758848 | import matplotlib.pyplot as plt
import numpy as np
if __name__ == "__main__":
fig, ax = plt.subplots(figsize=(10,5))
for clients in (10, 50, 100, 200):
median_data = np.zeros(5)
for k in (1, 2, 3, 4, 5):
data = np.loadtxt("notor/loss_" + str(clients) + "_nt_" + str(k) + ".csv",... |
1758867 | from math import log
def epmi(matrix):
"""
Exponential pointwise mutual information
"""
row_sum = matrix.sum(axis=1)
col_sum = matrix.sum(axis=0)
total = row_sum.sum(axis=0)[0, 0]
inv_col_sum = 1 / col_sum # shape (1,n)
inv_row_sum = 1 / row_sum # shape (n,1)
inv_col_sum = inv... |
1758871 | from obspy import UTCDateTime
import numpy as np
import pickle
import stdb
from obspy.clients.fdsn import Client
from splitpy import Split, utils
from . import test_args, get_meta
from pathlib import Path
def test_split(tmp_path):
args = test_args.test_get_args_calc_auto()
args.startT = UTCDateTime('2016-08-2... |
1758878 | import json
from urllib.parse import urlparse
import time
import click
SKIP_CATEGORIES = frozenset({
# 'apple-tv',
# 'apple-watch',
})
def parse_gh_link(url):
parse = urlparse(url)
path_items = parse.path.strip().split('/')
if len(path_items) == 3 and 'github.com' == parse.netloc:
usernam... |
1758888 | import os
import sys
from PyQt5 import QtCore, QtGui, QtQml
import qml_rc
if __name__ == '__main__':
os.environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "1"
app = QtGui.QGuiApplication(sys.argv)
app.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
#Initialize the QML rendering engine
engine = QtQml.QQmlApplicationEngine... |
1758934 | from django import forms
from django.forms.widgets import RadioSelect
from crits.campaigns.campaign import Campaign
from crits.core import form_consts
from crits.core.forms import add_bucketlist_to_form, add_ticket_to_form
from crits.core.handlers import get_source_names, get_item_names
from crits.backdoors.handlers i... |
1758936 | from .identifier import id_enroll, ImageCharacterIdentifier, \
ImageCharacterIdentifierBBox
from .res18_single import Res18_CharacterIdentifier
from .res18_bbox import Res18_CharacterIdentifier_BBox |
1758938 | import datetime
import scrapy
import locale
import datetime
locale.setlocale(locale.LC_ALL, "es_AR.utf8")
BASE_URL = 'http://www.losandes.com.ar'
class LosAndesSpider(scrapy.Spider):
name = "losandes"
def start_requests(self):
urls = [
'http://www.losandes.com.ar/article/inde... |
1758957 | from abc import ABC, abstractmethod
from typing import Union, List, Any
class ParallelWrapperBase(ABC):
def __init__(self, *_, **__):
"""
Note:
Parallel wrapper is designed to wrap the same kind of environments,
they may have different parameters, but must have the same act... |
1758969 | import pybullet as p
import numpy as np
from rlschool.quadrupedal.envs.utilities.pose3d import QuaternionFromAxisAngle
import time
STEP_HEIGHT_INTERVAL = 0.002
SLOPE_INTERVAL = 0.02
STEP_WIDTH_INTERVAL = 0.02
STEP_HEIGHT = np.arange(0.08,0.101,STEP_HEIGHT_INTERVAL)
SLOPE = np.arange(0.3,0.501,SLOPE_INTERVAL)
STEP_WIDT... |
1758973 | from staffjoy.resource import Resource
from staffjoy.resources.timeclock import Timeclock
from staffjoy.resources.time_off_request import TimeOffRequest
class Worker(Resource):
"""Organization administrators"""
PATH = "organizations/{organization_id}/locations/{location_id}/roles/{role_id}/users/{user_id}"
... |
1758977 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
def nearest_neighbor(components, X, distance='L1'):
# Initializing the tensor flow variables
init = tf.global_variables_initializer()
# Launch the session
sess ... |
1758979 | VALID_NET_NTRIP = b'SOURCETABLE 200 OK \n' \
b'NET;Str1;Str2;B;N;https://example.htm;http://example.htm;http://sample;none\n' \
b'ENDSOURCETABLE'
VALID_STR_NTRIP = b'SOURCETABLE 200 OK \n' \
b'STR;Str3;Str4;B;N;https://example2.htm;http://example2.htm;http://sample... |
1758991 | class TwoSum(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.hash_map = {}
def add(self, number):
"""
Add the number to an internal data structure..
:type number: int
:rtype: void
"""
self.hash_map[n... |
1758994 | from .field.effect import effect_applied
from .field.util import diffuse
from .physics import Physics, StateDependency
class HeatDiffusion(Physics):
def __init__(self, diffusivity=0.1):
Physics.__init__(self, [StateDependency('effects', 'temperature_effect', blocking=True)])
self.diffusivity = di... |
1758995 | from copy import deepcopy
import numpy as np
from .imprt import preset_import
from .log import get_logger
logger = get_logger()
def normalize_uint(arr):
r"""Normalizes the input ``uint`` array such that its ``dtype`` maximum
becomes :math:`1`.
Args:
arr (numpy.ndarray): Input array of type ``ui... |
1759037 | from pythonforandroid.bootstraps.service_only import ServiceOnlyBootstrap
class ServiceLibraryBootstrap(ServiceOnlyBootstrap):
name = 'service_library'
bootstrap = ServiceLibraryBootstrap()
|
1759075 | class Record:
def __init__(self, id, control_type, account_id, updated_timestamp, partition, region_name, resource_id, title, description, akas, control_state, tags) -> None:
self.id = id
self.control_type = control_type
self.account_id = account_id
self.updated_timestamp = updated_t... |
1759086 | import numpy as np
import fcl
from scipy.spatial.transform import Rotation
v1 = np.array([1.0, 2.0, 3.0])
v2 = np.array([2.0, 1.0, 3.0])
v3 = np.array([3.0, 2.0, 1.0])
x, y, z = 1.0, 2.0, 3.0
rad, lz = 1.0, 3.0
n = np.array([1.0, 0.0, 0.0])
d = 5.0
t = fcl.TriangleP(v1, v2, v3) # Triangle defined by three points
b = ... |
1759135 | from typing import Optional
from nornir.core.task import Result, Task
from nornir_napalm.plugins.connections import CONNECTION_NAME
def napalm_configure(
task: Task,
dry_run: Optional[bool] = None,
filename: Optional[str] = None,
configuration: Optional[str] = None,
replace: bool = False,
) -> R... |
1759156 | from __future__ import with_statement
# thanks ASPN Python Cookbook
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/498245
from collections import deque
from threading import RLock
from functools import wraps
from pprint import pformat
from timeit import default_timer
def lru_cache(maxsize):
'''Decorat... |
1759170 | import os
from glob import glob
from typing import Dict
from PIL import Image
from torch.utils.data import Dataset
class ScoreClassificationDataset(Dataset):
"""
:param dataset_directory: Absolute path to the directory that must contain two
folders named 'scores' and 'other' th... |
1759177 | from version import ELECTRUM_VERSION
from util import format_satoshis, print_msg, print_error, set_verbosity
from wallet import Synchronizer, Wallet, Imported_Wallet
from storage import WalletStorage
from coinchooser import COIN_CHOOSERS
from network import Network, pick_random_server
from interface import Connection, ... |
1759209 | import torch
import torchvision
import os
import re
import time
import zipfile
import shutil
import tqdm
import random
from torch.utils.data import sampler
from PIL import Image
from itertools import cycle, islice
# ========================================================
# Dataset-related functions and classes
# ===... |
1759226 | from .bbox_head import BBoxHead
from .convfc_bbox_head import (ConvFCBBoxHead, Shared2FCBBoxHead,
Shared4Conv1FCBBoxHead)
from .double_bbox_head import DoubleConvFCBBoxHead
from .transformer_bbox_head import TransformerBBoxHead
from .tail_bbox_head import TailBBoxHead
from .tail_gs_bbox_h... |
1759233 | from .basic_callbacks import Callback, CancelTrainException
from ..hook import Hooks
from ..utils import ToolBox as tbox
import torch
import torch.nn as nn
import math
from functools import partial
import matplotlib.pyplot as plt
class LR_Find(Callback):
_order = 1
def __init__(self, max_iter=100, min_lr=1e-... |
1759252 | from __future__ import print_function
import numpy as np
from neuralforecast.models import NeuralAR, NeuralMA
from neuralforecast.data_generator import arma_sample
import statsmodels.api as sm
np.random.seed(1337)
n = 1010
ar1_params = [[0.9], [0.0]]
ar1_sample = arma_sample(n, ar1_params[0], ar1_params[1])
for p i... |
1759258 | import os
import sys
import logging
import argparse
import re
import glob
VARIABLE_DECL = r'^variable\s+\"([\w_]+)\"\s+{'
VARIABLE = r'var\.([\w_]+)'
found = 0
log = logging.getLogger(__name__)
log.setLevel(level=os.environ.get("LOGLEVEL", logging.INFO))
loghandler = logging.StreamHandler()
formatter = logging.Format... |
1759261 | from blackwidow import error
def test_blackwidow_error():
assert isinstance(error.BlackWidowIOError(), IOError)
|
1759264 | def partial(func, *args, **kwargs):
def _partial(*more_args, **more_kwargs):
kw = kwargs.copy()
kw.update(more_kwargs)
return func(*(args + more_args), **kw)
return _partial
def update_wrapper(wrapper, wrapped, assigned=None, updated=None):
# Dummy impl
return wrapper
def wra... |
1759272 | from .visa_status import *
from tabulate import tabulate
import pandas as pd
import argparse
import sys
pd.set_option("display.max_rows", None)
__version__ = "0.2.0"
def tabprint(print_df):
print(tabulate(print_df, headers="keys", tablefmt="fancy_grid", showindex=True))
def main(argv=None):
argv = sys.ar... |
1759292 | from super_gradients.training.datasets.detection_datasets.detection_dataset import DetectionDataSet
from super_gradients.training.datasets.detection_datasets.coco_detection import COCODetectionDataSet
from super_gradients.training.datasets.detection_datasets.pascal_voc_detection import PascalVOCDetectionDataSet
__all_... |
1759293 | from future.moves.urllib.parse import urlparse
from django.db import connection
from django.db.models import Sum
import requests
import logging
from django.apps import apps
from api.caching.utils import storage_usage_cache
from framework.postcommit_tasks.handlers import enqueue_postcommit_task
from api.caching impor... |
1759322 | from __future__ import annotations
from typing import Any, List, Optional
from pydantic import BaseModel, HttpUrl
from ikea_api.wrappers import types
from ikea_api.wrappers._parsers.item_base import ItemCode
__all__ = ["main"]
class Catalog(BaseModel):
name: str
url: HttpUrl
class CatalogRef(BaseModel):... |
1759355 | import matplotlib.pyplot as plt
import numpy as np
class MultiprocessPlotter:
def __init__(self, processes, env):
self.processes = processes
self.width = int(np.ceil(np.sqrt(self.processes)))
self.heigth = self.width
self.env = env
self.closed = True
def create_figure(... |
1759381 | import gym
import gym_gomoku
env = gym.make('Gomoku9x9-v0')
# example 1: take an action
env.reset()
env.render()
env.step(15) # place a single stone, black color first
# example 2: playing with beginner policy, with basic strike and defend 'opponent'
env.reset()
for _ in range(20):
action = env.action_space.sampl... |
1759401 | from django.urls import path
from parsifal.apps.reviews.planning import views
app_name = "planning"
urlpatterns = [
path("save_source/", views.save_source, name="save_source"),
path("remove_source/", views.remove_source_from_review, name="remove_source_from_review"),
path("suggested_sources/", views.sugg... |
1759402 | from django.conf.urls import include, url
from django_sorcery import routers
from .testapp import views
router = routers.SimpleRouter()
router.register("owners", views.OwnerViewSet)
urlpatterns = [
# list views
# r"^(?P<id>[0-9]+)/$"
url(r"^list/owners/$", views.OwnerListView.as_view(), name="owners_lis... |
1759416 | from fastai.callback import Callback
from fastai.basic_train import Learner
from fastai.torch_core import torch, dataclass
import numpy as np
import pdb
def choose_corruption(inp, alpha):
nrows, ncols = inp.shape
lambd = []
for i in range(nrows):
col_idx = np.random.choice(ncols, (1,int(ncols*alp... |
1759431 | from typing import Optional
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton
from telegram_bot.database import models
WELCOME_TEXT = """\
基于「和风」的天气预报机器人;根据定位查询精准实时天气,并每天自动播报。
如有任何问题,请联系 @daya233
"""
ENABLE_SUB, DISABLE_SUB = "enable_sub", "disable_sub"
GET_WEATHER, UPDATE_LOCATION = "weathe... |
1759436 | description = "Maintenance setup for SPHERES. Includes all basic devices."
group = 'basic'
includes = ['spheres',
'qmesydaq']
|
1759440 | import os, sys
def include_headers():
inc = [
"#include <linux/module.h> /* Needed by all modules */",
"#include <linux/kernel.h> /* Needed for KERN_ALERT */",
"",
"#include <linux/aio_abi.h> //aio_context_t",
"#include <trace/syscall.h> //struct perf_event_attr, struct pollfd",
"#inc... |
1759449 | import logging as logmodule
import time
from django.core.management.base import BaseCommand
from django.db.models import Q
from le_utils.constants import content_kinds
from le_utils.constants import exercises
from contentcuration.models import ContentNode
from contentcuration.models import License
logmodule.basicCon... |
1759492 | import sys
class IOManipulator:
def __init__(self, function=None):
self.function = function
def do(self, output):
self.function(output)
class OStream:
def __init__(self, output=None):
if output is None:
output = sys.stdout
self.output = output
def __lsh... |
1759576 | from .graph_cnn_layer import GraphCNN
from .multi_graph_cnn_layer import MultiGraphCNN
from .graph_attention_cnn_layer import GraphAttentionCNN
from .multi_graph_attention_cnn_layer import MultiGraphAttentionCNN
from .graph_convolutional_recurrent_layer import GraphConvLSTM |
1759599 | import numpy as np
import tensorflow as tf
import keras.backend as K
from mnist import *
from cifar10 import load_data, set_flags, load_model
from attack_utils import gen_grad
from tf_utils_adv import batch_eval
from os.path import basename
import numpy as np
from rpy2.robjects.packages import importr
from rpy2.robjec... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.