id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
9901085 | from typing import (
Any,
Tuple, List, Iterator,
Callable,
TypeVar,
NoReturn, # functions that always raise or exit the interpreter
)
Fun = Callable
A = TypeVar('A')
from indented import flatten_tree
from indented.codegen import (
lit, apply, tuple_,
def_, cond, when,
join_with_op,
eval_def,
)
from operato... |
9901088 | import subprocess
from typing import Optional
from micmon.audio import AudioSegment
class AudioPlayer:
def __init__(self, sample_rate: int = 44100, channels: int = 1, ffplay_bin: str = 'ffplay'):
self.sample_rate = sample_rate
self.channels = channels
self.ffplay_bin = ffplay_bin
... |
9901105 | import pykd
import argparse
from enum import Enum, auto
def hex_byte(byte_str):
"""validate user input is a hex representation of an int between 0 and 255 inclusive"""
if byte_str == "??":
# windbg shows ?? when it can't access a memory region, but we shouldn't stop execution because of it
ret... |
9901111 | import boto3
import os
import uuid
from urllib.parse import unquote_plus
source_bucket_name = os.environ['RAW_BUCKET']
target_bucket_name = os.environ['PROCESSED_BUCKET']
s3_client = boto3.client('s3')
def handler(event, context):
'''
Handler - will be called on *each* file update / no batching
:param eve... |
9901126 | from pathlib import Path
from unittest import TestCase
from webassets.filter import register_filter
from webassets.test import TempEnvironmentHelper
from webassets_elm import Elm
MAIN = Path(__file__).parent / "Main.elm"
JSON = Path(__file__).parent / "elm.json"
register_filter(Elm)
class ElmFilterTestCase(TempEnv... |
9901134 | from microbit import *
while not button_a.was_pressed():
display.scroll("Press A")
display.scroll("Terminating!")
|
9901154 | import os
import numpy as np
import pytest
from Starfish import Spectrum
from Starfish.spectrum import Order
class TestOrder:
def test_no_sigma(self, mock_data):
wave, flux = mock_data
order = Order(wave, flux)
assert np.all(order._sigma == 0.0)
assert np.all(order.mask)
def... |
9901172 | from featureflow import Feature
from .arraywithunits import ArrayWithUnitsDecoder, ArrayWithUnitsEncoder
from zounds.spectral import FrequencyAdaptive
class FrequencyAdaptiveDecoder(ArrayWithUnitsDecoder):
def __init__(self):
super(ArrayWithUnitsDecoder, self).__init__()
def __call__(self, flo):
... |
9901193 | from typing import List, Union
import reversion
from django.core.management.base import BaseCommand
from reqs.models import Agency, AgencyGroup, Requirement
class Command(BaseCommand):
help = ("Associate agencies and agency groups with requirements " # noqa
"based on impacted entity field.")
d... |
9901212 | import pickle
import json
from functools import partial
from suit_dashboard import Widget
from django_redis import get_redis_connection
from config import charts
from . import insights
cache = get_redis_connection('default')
class InsightWidget(Widget):
data_func = None
chart_template = None
@property... |
9901218 | from typing import Any, Dict
class ClientError(Exception):
"""Base class of Dokklib-DB client errors."""
def __init__(self,
message: str,
error_response: Dict[str, Any],
operation_name: str):
"""Initialize a ClientError instance.
Args:
... |
9901228 | import os
import argparse
import pandas as pd
from tqdm import tqdm
def get_args():
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--data_path", type=str, default="./data")
args = parser.parse_args()
return args
def main():
args = ge... |
9901237 | import FWCore.ParameterSet.Config as cms
#-------------------------------------------------
# Tracking Monitor
#-------------------------------------------------
from DQM.TrackingMonitor.TrackingMonitor_cfi import *
# properties
TrackMon.MeasurementState = cms.string('ImpactPoint')
# which plots to do
TrackMo... |
9901262 | from threading import Thread
from pyinotify import IN_CLOSE_WRITE, IN_OPEN, Notifier, ProcessEvent, WatchManager
class MiniscreenLockFileMonitor:
def __init__(self, lock_path):
self.thread = Thread(target=self._monitor_lockfile)
self.when_user_stops_using_oled = None
self.when_user_starts... |
9901265 | from django.conf import settings
from django.template import TemplateDoesNotExist
from django.test import TestCase
from django_jsx.template.engine import JsEngine
from django_jsx.template.loaders import JsLoader
class TestLoader(TestCase):
def test_load_missing_template(self):
engine = JsEngine(dirs=[sett... |
9901277 | import torch
import torchdrift.utils
class Detector(torch.nn.Module):
"""Detector class.
The detector is is a `nn.Module` subclass that, after fitting, performs a drift test when called and returns a score or p-value.
Constructor Args:
return_p_value (bool): If set, forward returns a... |
9901300 | import pytest
import numpy as np
from discolight.annotations import annotations_to_numpy_array
@pytest.mark.usefixtures("coco_imageset", "coco_equiv_csv_imageset")
def test_coco_loader(coco_imageset, coco_equiv_csv_imageset):
for image_name in coco_equiv_csv_imageset:
_, cc_annotations = coco_imageset[... |
9901328 | import argparse
import os
import numpy as np
from PIL import Image
import kitti_util
import sys
sys.path.append('../')
import object3d_utils.kitti_utils as od_utils
def generate_rect_from_velo(pc_velo, height, width, calib):
pts_2d = calib.project_velo_to_image(pc_velo)
fov_inds = (pts_2d[:, 0] < width - 1)... |
9901369 | class index(object):
_name = ''
_index_type = ''
_columns = None
_errors = None
_warnings = None
def __init__(self, name, columns, index_type='INDEX'):
""" Index constructor
:param name: The name of the index
:param columns: The columns in the index
:param inde... |
9901377 | token="homme"
token_stem = stemmer.stem(token)
columns = ["CBOW", "skip-gram", "pretrained"]
df_ = []
msw_cbow = model_cbow.wv.most_similar([token_stem])
df_.append([msw_cbow[k][0] for k in range(10)])
msw_sg = model_sg.wv.most_similar([token_stem])
df_.append([msw_sg[k][0] for k in range(10)])
msw_pretrained = model_... |
9901405 | import os
#from qtpy.QtCore import Qt
from qtpy.QtWidgets import (
QApplication, QLabel, QPushButton, QLineEdit,
QGridLayout, QHBoxLayout, QVBoxLayout,
QComboBox, )
#from qtpy.compat import getexistingdirectory
from qtpy.QtWidgets import QLabel, QGridLayout, QVBoxLayout, QLineEdit
from pyNastran.gui.utils... |
9901407 | from sys import stdin, stdout
while True:
try:
line = stdin.readline()
if len(line) == 0:
break
n, m = list(map(int, line.strip().split()))
nums = {}
for i, num in enumerate(map(int, input().split())):
if num in nums:
nums[num].append(i+1)
else:
nums[num] = [i+1... |
9901408 | from .. import utils
from .._lazyload import matplotlib as mpl
from .utils import _get_figure
from .utils import parse_fontsize
from .utils import temp_fontsize
import numpy as np
import warnings
plt = mpl.pyplot
@utils._with_pkg(pkg="matplotlib", min_version=3)
def create_colormap(colors, name="scprep_custom_cmap"... |
9901425 | import matplotlib.pyplot as plt
import numpy as np
from LoadData import load_rating_data, spilt_rating_dat
from sklearn.model_selection import train_test_split
from ProbabilisticMatrixFactorization import PMF
if __name__ == "__main__":
file_path = "data/ml-100k/u.data"
pmf = PMF()
pmf.set_params({"num_feat... |
9901438 | from dbeditor.database import Database
from dbeditor.loaders.csv_loader import CSVLoader
from dbeditor.loaders.merger import Merger
def test_merge(database: Database, csv_loader: CSVLoader) -> None:
table = database.get_table("second")
merger = Merger(table)
with database.session as s:
merger.merg... |
9901519 | from django.db import models
from busshaming.enums import ScheduleRelationship
class RouteStopHour(models.Model):
route = models.ForeignKey('Route')
stop = models.ForeignKey('Stop')
date = models.DateField(db_index=True)
hour = models.PositiveSmallIntegerField(db_index=True)
scheduled_bus_count ... |
9901581 | from pyspark.sql.dataframe import DataFrame
from pyspark.sql.types import NumericType
from visions.types.numeric import Numeric
@Numeric.contains_op.register
def numeric_contains(sequence: DataFrame, state: dict) -> bool:
if len(sequence.schema) != 1:
return False
dtype = sequence.schema[0].dataType... |
9901670 | from tos.compat import url as tos_url, get_library
Library = get_library()
register = Library()
@register.tag
def url(parser, token):
return tos_url(parser, token)
|
9901697 | import os
import tempfile
import shutil
from pyunpack import Archive
from pathlib import Path
import requests
cwd = os.getcwd()
temp_folder = os.path.join(tempfile.mkdtemp(), ("temp_storage_dir%s" % os.path.sep))
Path(temp_folder).mkdir(parents=True, exist_ok=True)
ffmpeg_7z_path = os.path.join(temp_folder, "ffmpeg... |
9901699 | import argparse
from model import TCN
from utils import data_generator
import tensorflow as tf
tf.enable_eager_execution()
parser = argparse.ArgumentParser(description='Sequence Modeling - The Adding Problem')
parser.add_argument('--batch_size', type=int, default=32, metavar='N', help='batch size')
parser.add_argument... |
9901703 | import sys
from time import sleep
from visadore import get
osc = get(sys.argv[1])
print(osc.idn)
print(osc.features)
print(osc.curve().sources)
for i in osc.acquire(count=5, timeout=30):
pass
sleep(5)
settings = osc.setup()
osc.default_setup()
sleep(5)
osc.setup(settings)
print()
|
9901731 | import _init_paths
from PIL import Image as pil_image
from cute.cute_writer import CuteWriter
from datasets.image_format_pb2 import Image
from io import BytesIO
from wider import WIDER
def run(wider, cw):
for data in wider.next():
f_name = data.image_name.split('/')[-1].split('.')[0]
print f_name
... |
9901784 | from collections import OrderedDict
from timeit import timeit
d1 = OrderedDict(a=1, b=2, c=3, d=4)
d2 = dict(a=1, b=2, c=3, d=4)
print(d1)
print(d2)
OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)])
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
for k in reversed(d1):
print(k)
for k in reversed(list(d2.keys())):
... |
9901845 | import json
from django.urls import reverse
from wagtail.tests.utils import WagtailPageTests
from wagtail.core.models import Site
import wagtail_factories
from main.factories.base_page import BasePageFactory
from nextjs.factories import PageViewRestrictionFactory
class PasswordProtectedPageApiTest(WagtailPageTests)... |
9901853 | def search_and_replace(name, file_from, file_to, find, replace):
native.genrule(
name = name,
srcs = [file_from],
outs = [file_to],
output_to_bindir = 1,
cmd = "sed 's/$find/$replace/g' $< > $@",
)
|
9901880 | from pymeos.range import RangeFloat as MEOSRangeFloat
from sqlalchemy.types import UserDefinedType
from .BaseType import BaseType
class RangeFloat(BaseType):
base_class = MEOSRangeFloat
def get_col_spec(self):
return "FLOATRANGE"
|
9902025 | import pytest
import numpy as np
from numpy.testing import (assert_almost_equal, assert_allclose, assert_,
assert_equal, assert_raises, assert_raises_regex,
assert_array_equal, assert_warns)
# from jax.config import config
# config.update("jax_enable_x64", True)
i... |
9902053 | from django.http import HttpResponseNotFound
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .models import Room
from .models import SimpleUser
from .forms import RoomNameForm
from .forms import LoginForm
from .services import MessageService, RoomService
def index(request):
r... |
9902063 | from typing import Tuple
from torch.utils.data import Dataset
from src.data import RotationDataset, JigsawDataset
from src.data import ContrastiveAugmentor
from .base_dataset_wrapper import BaseDatasetWrapper
class PretextTaskDatasetWrapper(BaseDatasetWrapper):
"""Dataset wrapper for pretext task learning"""
... |
9902100 | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class LinearNorm(torch.nn.Module):
def __init__(self, in_dim, out_dim, bias=True, w_init_gain='linear'):
super(LinearNorm, self).__init__()
self.linear_layer = torch.nn.Linear(in_dim, out_dim, bias=bias)
... |
9902129 | from __future__ import annotations
import ast
import pytest
from flake8_pie import Flake8PieCheck
from flake8_pie.pie805_prefer_literal import PIE805
from flake8_pie.tests.utils import Error, ex, to_errors
EXAMPLES = [
ex(
code="""
"foo".encode()
""",
errors=[PIE805(lineno=2, col_offset=0)],
... |
9902158 | def get_lexem(lexer):
r =[]
t = lexer.token()
while t:
r.append(t)
t = lexer.token()
return r |
9902186 | try:
import unittest2 as unittest
except ImportError:
import unittest # NOQA
import webtest
from cliquet.tests.support import (BaseWebTest as CliquetBaseTest,
get_request_class)
from readinglist import API_VERSION
class BaseWebTest(CliquetBaseTest):
"""Base Web Test t... |
9902188 | import os, sys
import numpy as np
import copy
import MMTK
from MMTK.ParticleProperties import Configuration
from MMTK.ForceFields import ForceField
from AlGDock.BindingPMF import scalables
from AlGDock.BindingPMF import R
from AlGDock.BindingPMF import HMStime
term_map = {
'cosine dihedral angle': 'MM',
'electr... |
9902235 | import os
import arcpyext
import pytest
#TOOLBOX_PATH=os.path.abspath("{0}/../samples/test_python_toolbox.pyt".format(os.path.dirname(__file__)))
TOOLBOX_PATH=os.path.abspath("{0}/../samples/Toolbox.pyt".format(os.path.dirname(__file__)))
def test_update_toolbox_descriptions():
pt=arcpyext.toolbox.PythonToolbox(T... |
9902236 | from __future__ import annotations
import sys
from unittest.mock import ANY
from tox.pytest import MonkeyPatch, ToxProjectCreator
def test_gh_not_in_actions(monkeypatch: MonkeyPatch, tox_project: ToxProjectCreator) -> None:
monkeypatch.delenv("GITHUB_ACTIONS", raising=False)
project = tox_project({"tox.ini"... |
9902293 | import collections
import logging
import os
import queue
import subprocess
import threading
import time
from pykube.config import KubeConfig
from pykube.http import HTTPClient
from pykube.objects import Pod
Host = collections.namedtuple('Host', 'action,name,ip')
class MultipleFilesHostsManager:
def __init__(se... |
9902376 | from . import serializer, exceptions # noqa
from .account import EosAccount # noqa
from .keys import EosKey # noqa
from .rpc import EosJsonRpc # noqa
from .types import (
UInt8, UInt16, UInt32, UInt64, Int8, Int16, Int32, Int64, VarUInt, Float32,
Float64, TimePointSec, TimePoint, Name, AbiBytes, BaseAbiObje... |
9902381 | import math
import numpy as np
def get_class(class_divpnt, idx):
for c in class_divpnt:
if idx <= c:
return class_divpnt.index(c)
return len(class_divpnt)
def get_class_dist(cls_list, num_cls):
cls_dist = [1e-9] * num_cls
for i in cls_list:
if i is not -1:
cls... |
9902382 | from json import dumps as json_dumps
from typing import Optional, List
from pydantic import Field, PrivateAttr
from pydantic.main import BaseModel
# todo: add select carousel
# todo: add select list
class OpenUrlAction(BaseModel):
url: str
class Image(BaseModel):
url: str
accessibilityText: str
class I... |
9902467 | import sigopt
from data_and_model_setup import LoadTransformData, log_inference_metrics
import time
import platform
from xgboost.sklearn import XGBClassifier
def train_xgboost_model(dataset, random_state=1):
print("loading and transforming data")
load_transform_data = LoadTransformData()
trainX, testX, tr... |
9902498 | import copy
import numpy as np
from .optimizer import *
class CMAESO(Optimizer):
def __init__(self, func, count):
super().__init__(func, count)
self.nn = self.f.D
self.xx = np.random.random(self.nn)
self.xmean = self.xx[:]
self.sigma = 0.2
self.lam = 4 + int(3 * n... |
9902508 | import torch
from torch.utils.data import DataLoader, WeightedRandomSampler
import os
from sklearn.metrics import roc_auc_score
from models.nfm import NeuralFactorizationMachineModel
from models.hen import HENModel
from models.m3r import SeqM3RModel
from models.wd import WideAndDeepModel
from models.lstm4fd import LST... |
9902532 | import os
from mock import mock
from rest_framework import status
__author__ = "<NAME>"
__copyright__ = "Copyright 2019, Helium Edu"
__version__ = "1.4.38"
def given_urlopen_mock_from_file(filename, mock_urlopen, status_code=status.HTTP_200_OK):
data = open(os.path.join(os.path.dirname(__file__), '..', filename... |
9902537 | import numpy as np
def xyz2uvd(pts, paras, flip=1):
# paras: [fx, fy, fu, fv]
pts_uvd = pts.copy()
pts_uvd = pts_uvd.reshape(-1, 3)
pts_uvd[:, 1] *= flip
pts_uvd[:, :2] = pts_uvd[:, :2] * paras[:2] / pts_uvd[:, 2:] + paras[2:]
return pts_uvd.reshape(pts.shape).astype(np.float32)
def uvd2xyz(... |
9902570 | import sys
import requests
from .entry import Entry
from .league import LeagueStandings
from .league import LiveLeagueStandings
from .player import Player
from .picks import Picks
from .urls import FPL_URL
from .urls import LIVE_SUBURL
from .urls import PICKS_SUBURL
from .urls import PLAYERS_INFO_SUBURL
from .urls imp... |
9902576 | import datetime, sys
from core.utils import date_format, html_escape, csrf_tag, csrf_hash, trunc, create_basename_core
from core.template import tpl
from settings import (DB_TYPE, DESKTOP_MODE, BASE_URL_ROOT, BASE_URL, DB_TYPE_NAME,
SECRET_KEY, ENFORCED_CHARFIELD_CONSTRAINT, DEFAULT_THEME, LOOP_TIMEOUT)... |
9902603 | import dash_bootstrap_components as dbc
from dash import Input, Output, State, html
placement_selector = html.Div(
[
dbc.Label("Placement:"),
dbc.RadioItems(
id="offcanvas-placement-selector",
options=[
{"label": "start (Default)", "value": "start"},
... |
9902614 | import pandas as pd
import re
from heritageconnector import logging
logger = logging.get_logger(__name__)
# methods to transform different typed fields
def transform_series_str_to_list(series: pd.Series, separator: str) -> pd.Series:
"""
Splits the list column according to a specified separator. Removes lead... |
9902663 | import numpy as np
import OpenGL.GL as gl
import pangolin
import cv2
import matplotlib as mpl
from .utils import waitKey
UNKNOWN_FLOW_THRESH = 1e7
SMALLFLOW = 0.0
LARGEFLOW = 1e8
class FrameDrawer():
def __init__(self, K):
# camera intrinsic
self.K = K
self.img_h = 200... |
9902677 | from .base_options import BaseOptions
class TrainOptions(BaseOptions):
def initialize(self, parser):
parser = BaseOptions.initialize(self, parser)
parser.add_argument('--src_train_datafile', type=str, default='train.txt', help='stores data list, in src_root')
parser.add_argument('--tgt_tra... |
9902713 | import logging
import typing as t
from collections import Counter
from functools import cmp_to_key
from gkeep.query import Query
from gkeep.status import status
from gkeep.thread_util import background
from gkeep.util import NoteType, escape
from gkeepapi import Keep, exception
from gkeepapi.node import Label, TopLeve... |
9902721 | import math
from statistics import NormalDist
import numpy as np
from numpy.random import RandomState
def distress_insurance_premium(
default_prob: np.ndarray,
correlations: np.ndarray,
default_threshold: float = 0.15,
random_seed: int = 0,
n_simulated_returns: int = 500_000,
n_simulations: in... |
9902722 | import FWCore.ParameterSet.Config as cms
l1tSummaryStage2HltDigis = cms.EDAnalyzer(
"L1TSummary",
tag = cms.string("Stage 2 Digis Unpacked by HLT L1 unpack sequence"),
egCheck = cms.bool(True),
tauCheck = cms.bool(True),
jetCheck = cms.bool(True),
sumCheck = cms.bool(True),
... |
9902755 | import redis
def main():
try:
conn = redis.Redis(host="192.168.36.123", port=6379, password="<PASSWORD>")
conn.set("name", "hello")
if conn.exists("name"):
result = conn.get("name")
print(result)
except Exception as ex:
print(ex)
if __name__ == "__main... |
9902814 | from collections import deque
import types
import copy
import z3
from p4z3.base import log
from p4z3.base import StaticType, P4Z3Class, P4Expression
from p4z3.base import P4Slice, P4ComplexType, P4Member, P4Index
from p4z3.base import StructInstance, P4ComplexInstance, HeaderStack
from p4z3.base import z3_cast, propag... |
9902827 | import numpy as np
import pandas as pd
def od_weighted_time_delta(reference_od, scenario_od):
columns = [
'origin', 'destination', 'volume',
'volume_pt', 'volume_car', 'volume_walk',
'duration_car', 'duration_pt'
]
ref = reference_od[columns].set_index(['origin', 'destination'])
... |
9902832 | from django.core.management.base import BaseCommand, CommandError
from django.core.files import File
import slugid
import tilesets.models as tm
import django.core.files.uploadedfile as dcfu
import os.path as op
from django.conf import settings
class Command(BaseCommand):
def add_arguments(self, parser):
p... |
9902859 | import functools
import platform
import traceback
import sys
from shared.common import log_critical
# Decorator to catch exceptions and avoid stop script.
def exception(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
# pylint: disable=import-outside-toplevel
from botocore.client... |
9902862 | import os
import shutil
from pathlib import Path
from uuid import uuid4
from wikidict import gen_dict
def test_simple():
output = Path(os.getenv("CWD", "")) / str(uuid4())
output.mkdir()
try:
ret = gen_dict.main("fr", "logiciel", output)
assert ret == 0
finally:
shutil.rmtree(... |
9902892 | import cherrypy
import tangelo
# This service reports the value of cherrypy's thread pool setting
def run(**kwargs):
if kwargs.get('pool'):
tangelo.util.set_server_setting('server.thread_pool', int(kwargs['pool']))
response = 'pool="%r"' % cherrypy.config.get('server.thread_pool')
return response
|
9902934 | import torch
import torch.nn as nn
import torch.nn.functional as F
def coord_list_grid_sample(values, points, mode='bilinear'):
dim = len(points.shape)
points = points.view(values.size(0), 1, -1, 2) if dim == 3 else points
output = F.grid_sample(values, points, mode, align_corners=True).permute(0, 2, 3, 1... |
9902939 | from collections import defaultdict
import pickle
import pymysql.cursors
import os
import random
from common.dataset.corpus import Corpus
from common.util.log_helper import LogHelper
def preprocess(p):
return p.replace(" ","_").replace("(","-LRB-").replace(")","-RRB-").replace(":","-COLON-").split("#")[0]
lut ... |
9902974 | from . import BaseCommand
from flask import render_template
class FaqCommand(BaseCommand):
def process(self, request, filename, db_session):
return render_template('faq.html')
def newInstance():
return FaqCommand()
|
9903016 | import os
import platform
import shutil
import subprocess
import sys
from distutils.dir_util import copy_tree
from distutils.file_util import copy_file
from distutils.version import LooseVersion
from setuptools import Extension, setup
from setuptools.command.build_ext import build_ext
class CMakeExtension(Extension)... |
9903032 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import shutil
import sys
import tempfile
from observations.r.life_cycle_savings import life_cycle_savings
def test_life_cycle_savings():
"""Test module life_cycle_savings.py by downloading
life_cycle_sa... |
9903098 | from amaranth_boards.ecpix5 import *
from amaranth_boards.ecpix5 import __all__
import warnings
warnings.warn("instead of nmigen_boards.ecpix5, use amaranth_boards.ecpix5",
DeprecationWarning, stacklevel=2)
|
9903100 | from django.shortcuts import render
from rest_framework import viewsets, status
from rest_framework.decorators import list_route
from rest_framework.response import Response
from images.models import Image
from images.serializers import ImageSerializer
# Create your views here.
def index(request):
return render(... |
9903111 | from django.db.models import Q
from django.db.models.signals import m2m_changed
from django.dispatch import receiver
from guardian.shortcuts import assign_perm, remove_perm
from grandchallenge.algorithms.models import Job
from grandchallenge.components.models import ComponentInterfaceValue
@receiver(m2m_changed, sen... |
9903122 | import numpy as np
from ipywidgets import Image as WidgImage
from PIL import Image
import io
class ImageVisualizer(object):
"""Visualizer for images.
This visualizer can display images (e.g., MNIST), which are stored as rows
in a dataframe.
"""
def __init__(self, columns_range, img_shap... |
9903159 | def setting_arg():
parser = argparse.ArgumentParser(description='FlowGrid Parameters')
parser.add_argument('--f',type=str,required=True,dest="file",
help='input the file name')
parser.add_argument('--n',type=int,required=True,dest="bin_n",
help='input the number of bins')
parser.add_argument('--eps',type=float,... |
9903177 | from jinja2 import FileSystemLoader, Environment
template_engine = Environment(loader=FileSystemLoader("html"))
def get_template(name):
return template_engine.get_template(name)
|
9903191 | import tensorflow as tf
import numpy as np
from tf_util import mlp, mlp_conv,gen_grid, gen_1d_grid
from tf_sampling import farthest_point_sample, gather_point
def encoder(inputs, embed_size=1024):
with tf.variable_scope('encoder_0', reuse=tf.AUTO_REUSE):
features = mlp_conv(inputs, [128, 256], bn=None, bn_... |
9903211 | from docopt import docopt, DocoptExit
from chemaboxwriters.ontopesscan import write_abox
import json
doc = """aboxwriter
Usage:
opesscan <fileOrDir> [(--os-iris=<iri> --os-atoms-iris=<iris> --oc-atoms-ids=<ids>)]
[--inp-file-type=<type>]
[--qc-log-ext=<ext>]
... |
9903220 | import os
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
import torchvision
import torchvision.transforms as transforms
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.layer1 = nn.Seq... |
9903243 | import socket
hostname = socket.gethostname()
egg_config = {'DESKTOP-99MRARG':'C:\my_project\CARLA_0.9.5\PythonAPI\carla\dist\carla-0.9.5-py3.7-win-amd64.egg',
'LVANYANG-PC1':'E:\game\CARLA_0.9.4\PythonAPI\carla-0.9.4-py3.7-win-amd64.egg'}
egg_file = egg_config[hostname]
world_ops_logger = False
no_re... |
9903251 | import torch
import torch.nn as nn
def add_layer(seq, ix, n_inputs, n_outputs, nonlin, normalization):
seq.add_module('L'+str(ix), nn.Linear(n_inputs, n_outputs))
if ix > 0 and normalization: # only LN/IN after first layer.
if normalization == 'LN':
seq.main.add_module('A'+str(ix), nn.Laye... |
9903265 | from __future__ import absolute_import
# Copyright (c) 2010-2015 openpyxl
class Legend(object):
def __init__(self):
self.position = 'r'
self.layout = None
|
9903306 | import pytest
@pytest.fixture
def reset_mock():
cache = []
def set_mock(obj, attr, mock):
cache.append((obj, attr, getattr(obj, attr)))
setattr(obj, attr, mock)
yield set_mock
for obj, attr, value in cache:
setattr(obj, attr, value)
cache[:] = []
|
9903326 | import datetime
import logging
import six
from tastypie import fields
class SimpleHandler(logging.Handler):
logged = []
def emit(self, record):
SimpleHandler.logged.append(record)
def adjust_schema(schema_dict):
for field, field_info in schema_dict['fields'].items():
if isinstance(fiel... |
9903334 | import geosoft.gxapi as gxapi
import geosoft.gxpy.gx as gx
import geosoft.gxpy.grid as gxgrid
# create context
gxc = gx.GXpy()
# create a gxapi.GXST instance to accumulate statistics
stats = gxapi.GXST.create()
# open the grid
with gxgrid.Grid.open('elevation_surfer.grd(SRF;VER=V7)') as grid:
# add data from ea... |
9903356 | from engine.configs.registry import Registry
# from .defaults import _C as cfg
import sys
sys.dont_write_bytecode = True
Loggers = Registry('Loggers')
Networks = Registry('Networks')
Datasets = Registry('Datasets')
LossFuncs = Registry('LossFuncs')
EvalFuncs = Registry('EvalFuncs')
Schedulers = Registry('Schedulers'... |
9903368 | from .base import BaseLearningRule
class Langevin(BaseLearningRule):
""" This class is implemented by <NAME>
"""
def __init__(self, evaluated_model, x_pred=None, optimizer='adam', sd=-1, num_burnin_steps=1000, adapt_lr=True,
desired_accept=0.7, adapt_power=0.51, burnin=100, **kwargs):
... |
9903372 | from __future__ import division
import numpy as np
from scipy.io import wavfile
from scipy import signal
import matplotlib.pyplot as plt
import matplotlib.mlab as mlb
def ApplySigmoidScale (ltsv_sigmoidThr, ltsv_sigmoidSlope, ltsv_input):
"""This function applies sigmoid scale on the input
Args:
ltsv_sigm... |
9903409 | from .exceptions import DumpException
class DD:
def __init__(self, container):
self.app = container
def dump(self, *args):
dump_list = []
for i, obj in enumerate(args):
dump_name = "ObjDump{}".format(i)
self.app.bind(dump_name, obj)
dump_list.append... |
9903428 | from argo_dataflow import pipeline, git
if __name__ == '__main__':
(pipeline("106-git-python-generator")
.owner('argoproj-labs')
.describe("""This example of a pipeline using Git, showing how to use Generator Step.
The Git handler allows you to check your application source code into Git. Dataflow will ... |
9903573 | from __future__ import print_function
import json
import os
import sys
def print_file_tree(startpath):
""" Prints a directory and its contents
"""
for root, dirs, files in os.walk(startpath):
# skip hidden dirs
dirs[:] = [d for d in dirs if not d.startswith(".")]
level = root.re... |
9903609 | from __future__ import absolute_import, unicode_literals
from contextlib import contextmanager
import pytest
from case import Mock, mock, patch
from celery.fixups.django import (DjangoFixup, DjangoWorkerFixup,
FixupWarning, _maybe_close_fd, fixup)
class FixupCase:
Fixup = None... |
9903654 | import tensorflow as tf
import numpy as np
from mann.utils.tf_utils import variable_one_hot
class MANNCell():
def __init__(self, lstm_size, memory_size, memory_dim, nb_reads,
gamma=0.95, reuse=False):
self.lstm_size = lstm_size
self.memory_size = memory_size
self.memory_di... |
9903687 | import pytest as pytest
from ripper.context.target import Target
class DescribeTarget:
def it_can_validate_connection_status(self):
stat = Target(target_uri='http://google.com')
assert stat.validate_connection(120) is True
assert stat.validate_connection(-3600) is False
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.