id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
3388122 | from abc import ABC, abstractmethod
import time
import numpy as np
class MDP(ABC):
"""Base environment for the dynamic programming chapter."""
def __init__(self):
self.init_p()
def renormalize(self):
for s in self.states:
for a in self.moves:
p_sum = sum([self... |
3388218 | import luigi
import luigi.contrib.hadoop
import luigi.contrib.hdfs
class InputFile(luigi.ExternalTask):
"""
A task wrapping the HDFS target
"""
input_file = luigi.Parameter()
def output(self):
"""
Return the target on HDFS
"""
return luigi.contrib.hdfs.HdfsTarget(self.input_file... |
3388234 | import numpy as np
from commons import encode, get_loaded_model
from settings import embeddings_file
from utils import load_embeddings
embeddings = load_embeddings(embeddings_file)
model = get_loaded_model()
def find_best_match(text):
best_cosine = 0
best_match = None
query_embedding = encode(model, te... |
3388242 | import time
from tortoise import fields
from tortoise.models import Model
class SearchRecord(Model):
'''查询使用记录表'''
id = fields.IntField(pk=True, generated=True)
group_id = fields.IntField()
'''群号'''
app_name = fields.CharField(max_length=255)
'''查询类型'''
count = fields.IntField(default=0)
... |
3388254 | import os
import time
import logging
from pathlib import Path
import uvicorn
from fastapi import FastAPI
from api.endpoints.routes.webhooks import get_webhookapp
from api.core.config import settings
from api.endorser_main import get_endorserapp
# setup loggers
# TODO: set config via env parameters...
logging_file_pa... |
3388338 | import ptypes
from ptypes import *
from . import portable
from .headers import *
import logging
class Signature(portable.IMAGE_FILE_HEADER):
_fields_ = [
(Machine, 'Machine'),
(uint16, 'NumberOfSections'),
]
def isImportSignature(self):
return all((self['Machine'].li.int() == sel... |
3388365 | from boa3.builtin import public
from boa3.builtin.interop.iterator import Iterator
from boa3.builtin.interop.storage import find
@public
def find_by_prefix(prefix: int) -> Iterator:
return find(prefix)
|
3388395 | from . import fid, kid, inception_score, inception_model
from .compute_fid import *
from .compute_is import *
from .compute_kid import *
from .compute_metrics import *
|
3388417 | from abc import ABCMeta, abstractmethod
import os
import logging
import yaml
import collections
class WorkloadBase:
__metaclass__ = ABCMeta
success = 0
failure = 0
total_tests = 0
total_scenarios = 0
browbeat = {}
@abstractmethod
def update_scenarios(self):
pass
@abstractme... |
3388432 | from .base import *
DEBUG = False
ALLOWED_HOSTS = ["django-api.staging.motius.de"]
SITE_URL = 'http://django-api.staging.motius.de'
STATIC_URL = 'http://django-api.staging.motius.de/static/'
try:
from .local import *
except ImportError:
pass
|
3388456 | from django import template
from django.template.defaultfilters import stringfilter
from markdown.extensions import Extension
import markdown as mdown
class EscapeHtml(Extension):
def extendMarkdown(self, md):
md.preprocessors.deregister("html_block")
md.inlinePatterns.deregister("html")
registe... |
3388493 | from .dimension import *
from .enums import *
from .text_expression import *
from .value_expressions import *
|
3388495 | import enums_pb2
messageObj = enums_pb2.enumTest();
messageObj.a = enums_pb2.color.blue
messageObj.b = 564
messageObj.c.append(enums_pb2.color.blue)
messageObj.c.append(enums_pb2.color.green)
messageObj.d = messageObj.fruit.orange
messageObj.e.append(messageObj.fruit.orange)
messageObj.e.append(messageObj.fruit.a... |
3388510 | from typing import Any
from netmiko.cisco_base_connection import CiscoSSHConnection
class ExtremeNetironBase(CiscoSSHConnection):
def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self._test_channel_read(pattern=r"[>#]")
self.set_ba... |
3388526 | import numpy as np
import math
import sys
import pickle
def Coord2Pixels(lat, lon, min_lat, min_lon, max_lat, max_lon, sizex, sizey):
#print(max_lat, min_lat, sizex)
ilat = sizex - int((lat-min_lat) / ((max_lat - min_lat)/sizex))
#ilat = int((lat-min_lat) / ((max_lat - min_lat)/sizex))
ilon = int((lon... |
3388569 | import asyncio
import os
import time
from dcr.scenario_utils.azure_models import ComputeManager
from dcr.scenario_utils.common_utils import execute_py_script_over_ssh_on_test_vms, \
execute_commands_concurrently_on_test_vms
from persist_firewall_helpers import SVG_DIR
def get_svg_files():
harvest_dir = os.p... |
3388586 | import boto3
import pandas as pd
from dishpylib.pydecorators import announce_job_decorator_factory
from dishpylib.pydecorators import only_every_nth_stint_decorator_factory
from dishpylib.pydecorators import try_except_missing_data_decorator_factory
from dishpylib.pytabulators import tabulate_strain_fitness
from ._va... |
3388619 | import pyOcean_cpu as ocean
a = ocean.asTensor([1,2,3])
b = ocean.tensor(a.size, a.dtype)
a.byteswap()
b.copy(a)
print(a)
print(b)
|
3388634 | import insightconnect_plugin_runtime
from .schema import ThreatsFetchFileInput, ThreatsFetchFileOutput, Input, Output, Component
# Custom imports below
from insightconnect_plugin_runtime.exceptions import PluginException
class ThreatsFetchFile(insightconnect_plugin_runtime.Action):
def __init__(self):
su... |
3388641 | import sys
sys.path.append("../../")
from appJar import gui
win = 'one'
def launch(win):
app.startSubWindow(win, modal=True)
app.addLabelEntry("Window one") #LabeledEntry considered as duplicate
app.addButton("close window", destroyWindow)
app.stopSubWindow()
app.showSubWindow(win)
def destroyWin... |
3388679 | from unittest import mock
import contexts
class WhenCatchingAnException:
def given_a_function_that_throws_an_exception(self):
self.thrown = ValueError("test exception")
def throwing_function(a, b, c, d=[]):
self.call_args = (a, b, c, d)
raise self.thrown
self.throw... |
3388726 | import logging
import binaryninja
from binaryninja import HighlightStandardColor
from binaryninja.highlight import HighlightColor
from lighthouse.painting import DatabasePainter
from lighthouse.util.disassembler import disassembler
logger = logging.getLogger("Lighthouse.Painting.Binja")
#---------------------------... |
3388736 | import FWCore.ParameterSet.Config as cms
recoChargedRefCandidateToTrackRefProducer = cms.EDProducer("RecoChargedRefCandidateToTrackRefProducer",
src = cms.InputTag('trackRefsForJets')
)
|
3388753 | from __future__ import division
import unittest
import pytest
import numpy as np
from openmdao.utils.assert_utils import assert_near_equal, assert_check_partials
from openmdao.api import IndepVarComp, Group, Problem
from openconcept.utilities.math.integrals import Integrator
class IntegratorTestGroup(Group):
"""An... |
3388761 | import webapp2
from webapp2 import Route
from controllers import pages
from controllers import image
from controllers import api
from controllers.api import Category
from controllers.api import Dish
from controllers.api import CheckRestaurantUid
application = webapp2.WSGIApplication([
('/', pages.Index),
('/api/... |
3388763 | import pickle
import unittest
from os.path import join, abspath
from numpy.testing import assert_allclose
from tests.reactor.closed_reactors.rebless import run
import cantera
if int(cantera.__version__.replace('.', '')) >= 250:
class Test(unittest.TestCase):
def test(self):
output = run()
... |
3388774 | import datetime as dt
import attr
from .journey import Transport
from .station import Station
@attr.s(frozen=True, slots=True)
class BoardEntry:
tofrom: Station = attr.ib()
transport: Transport = attr.ib()
time: dt.datetime = attr.ib()
"Arrival/departure time, without delay"
delay: int = attr.... |
3388792 | from .setup import *
def test_compare_downcoef_coeffs():
r = random.normal(keys[0], (16,))
# compare downcoef against wavedec outputs
for nlevels in [1, 2, 3]:
for wavelet in wt.wavelist(kind='discrete'):
wavelet = wt.build_wavelet(wavelet)
if wavelet is not None:
... |
3388800 | from nowallet import scrape
def test_scrape_electrum_servers(event_loop):
servers = event_loop.run_until_complete(
scrape.scrape_electrum_servers(chain_1209k="btc"))
for server in servers:
assert isinstance(server, tuple)
assert len(server) == 3
host, port, proto = server
... |
3388821 | import os
import sys
sys.path.insert(0, r"..//")
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from hotstepper import Step
from hotstepper import Steps
import hotstepper.samples as samples
import warnings
warnings.filterwarnings("ignore")
temperature_pacf50 = np.array(
[ 1.00000000e... |
3388838 | candies = input("Enter Candies ").split()
max = 0
result = [0]*len(candies)
extra = int(input("Enter extra candies "))
for i in range(len(candies)):
candies[i] = int(candies[i])
if int(candies[i])>max:
max = candies[i]
for i in range(len(candies)):
if(candies[i]+extra>=max):
result[i] = True... |
3388852 | import requests
import hmac
import hashlib
from collections import OrderedDict
from urllib.parse import urlencode
class CoinPaymentsAPI:
api_url = 'https://www.coinpayments.net/api.php'
api_version = 1
def __init__(self, public_key, private_key):
self.public_key = public_key
self.private_... |
3388908 | from flask import Flask, render_template, request, redirect, url_for, send_from_directory
from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError
import helper
# Configure application
app = Flask(__name__)
@app.route('/index', methods=['POST', 'GET'])
@app.route('/', methods=['POST', '... |
3388918 | import os
import json
ext_folder = '/Applications/Visual Studio Code.app/Contents/Resources/app/extensions'
def getBuiltinLanguageInfo():
exts = os.listdir(ext_folder)
with open('scopename.md', 'w') as out:
out.write('# Language ScopeName\n\n|language|scopeName|\n|---|---|\n')
for ext in exts... |
3388924 | import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly
import plotly.express as px
gapminder = plotly.data.gapminder()
app = dash.Dash(__name__)
app.layout = html.Div(
[
dcc.Dropdown(
id="gapminder-dropdown",
# ➊ 辞書内包表記で選択肢を作成
... |
3388938 | import unittest
from setup.settings import *
from numpy.testing import *
from pandas.util.testing import *
import numpy as np
import dolphindb_numpy as dnp
import pandas as pd
import orca
class FunctionDivmodTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
# connect to a DolphinDB server
... |
3388944 | from tensorwatch.watcher import Watcher
import time
from tensorwatch import utils
utils.set_debug_verbosity(10)
def main():
watcher = Watcher()
for i in range(5000):
watcher.observe(x=i)
# print(i)
time.sleep(1)
main()
|
3388966 | from BaseController import BaseController
from api.util import settings
import os
class SettingsController(BaseController):
def get(self):
server_list=""
for server in settings.get_redis_servers():
server_list+= "%(server)s:%(port)s %(group)s %(instance)s\r\n" % server
... |
3388986 | import os
import pathlib
import pickle
import torch
from ..utils.key_points import W_LIST_POSE, W2I_POSE, W_LIST_LEFT_HAND, W2I_LEFT_HAND, W_LIST_RIGHT_HAND, W2I_RIGHT_HAND
from ..utils.normalizer import normalize_data, normalize_hand_data
from ..model import HACModel
class Detector:
def __init__(self, model_dat... |
3389009 | from pyqchem import Structure, QchemInput, get_output_from_qchem
from pyqchem.qchem_core import redefine_calculation_data_filename
from pyqchem.parsers.parser_optimization import basic_optimization
from pyqchem.parsers.parser_cis import basic_cis
from pyqchem.parsers.parser_rasci import parser_rasci
from pyqchem.basis ... |
3389013 | import bayesnewton
import objax
import numpy as np
import matplotlib.pyplot as plt
import time
from scipy.io import loadmat
plot_final = True
plot_intermediate = False
print('loading data ...')
N_sig = 22050
# y = loadmat('../experiments/audio/speech_female')['y'][1000:N_sig+1000]
y = loadmat('../experiments/audio/s... |
3389040 | try:
from twisted.trial import unittest
except ImportError:
from nose import SkipTest
raise SkipTest('twisted not available; skipping')
class TestTwisted(unittest.TestCase):
def test(self):
pass
|
3389048 | import mappyfile
def test():
# START OF API EXAMPLE
# load will accept a filename (loads will accept a string)
mapfile = mappyfile.open("./docs/examples/raster.map")
# search for a layer by name
layer = mappyfile.find(mapfile['layers'], 'name', 'sea')
print(layer['name']) # "sea"
#... |
3389053 | import torch
class ConvNet(torch.nn.Module):
class Block(torch.nn.Module):
def __init__(self, n_input, n_output, stride=1):
super().__init__()
self.net = torch.nn.Sequential(
torch.nn.Conv2d(n_input, n_output, kernel_size=3, padding=1, stride=stride),
... |
3389077 | from __future__ import absolute_import, division, print_function
import boost_adaptbx.boost.python as bp
import libtbx.load_env
if (libtbx.env.build_options.enable_cuda):
cudatbx_ext = bp.import_ext("cudatbx_ext")
from cudatbx_ext import *
|
3389084 | try:
from autoflex.gpu import GPUFlexManager, GPUFlex, gpuflex16 # noqa
except ImportError:
pass
|
3389099 | from django.contrib import messages
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext
from django.urls import reverse, reverse_lazy
from django.views.generic import FormView, RedirectView
from users.models import I... |
3389107 | import sqlite3
from flask import current_app
import traceback
class Connect():
# 数据库连接类,上下文管理
def __init__(self, file_path='./database/arcaea_database.db'):
"""
数据库连接,默认连接arcaea_database.db
接受:文件路径
返回:sqlite3连接操作对象
"""
self.file_path = file_path
def __ente... |
3389120 | def artifact_create(container=None, name=None, label=None, severity=None, cef_field=None, cef_value=None, cef_data_type=None, tags=None, run_automation=None, input_json=None, **kwargs):
"""
Create a new artifact with the specified attributes.
Args:
container (CEF type: phantom container id): Co... |
3389141 | from statsmodels.tsa.holtwinters.model import (
PY_SMOOTHERS,
SMOOTHERS,
ExponentialSmoothing,
Holt,
SimpleExpSmoothing,
)
from statsmodels.tsa.holtwinters.results import HoltWintersResults
__all__ = [
"ExponentialSmoothing",
"SimpleExpSmoothing",
"Holt",
"HoltWintersResults",
"... |
3389185 | from analyze_entropy import comp_entropy
import numpy as np
if __name__ == '__main__':
x = np.asarray([0.89, 0.02] + [0.01] * 9)
ent = comp_entropy(x, nucleus_filter=False)
print(ent)
ent = comp_entropy(x, nucleus_filter=True)
v = [0.89 / 0.91, 0.02 / 0.91]
out = sum([x * np.log(x) for x in ... |
3389201 | from math import factorial
import torch
from torch import nn
from torchvision.models import resnext50_32x4d
from modules import conv2d_bn_relu, deconv_sigmoid, deconv_relu
class ErrorPredictor(torch.nn.Module):
""" graph convolution network"""
def __init__(self, args, n_channels=3, n_imgs=5):
super... |
3389203 | from pathlib import Path
from scipy.interpolate import interp1d
import numpy as np
from msdsl.rf import s4p_to_step
THIS_DIR = Path(__file__).resolve().parent
TOP_DIR = THIS_DIR.parent.parent
COMPARISON_FILE = 'peters_01_0605_B1_thru.s4p'
COMPARISON_TOVER = 0.1e-12
COMPARISON_TDUR = 10e-9
COMPARISON_XDATA = [
... |
3389212 | from abc import ABCMeta, abstractmethod
from collections import Iterator
def _check_methods(C, *methods):
mro = C.__mro__
for method in methods:
for B in mro:
if method in B.__dict__:
if B.__dict__[method] is None:
return NotImplemented
br... |
3389231 | from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet, mixins
from rest_framework.filters import DjangoFilterBackend
from django.conf import settings
from .serializers import IncludedSerializer
class TestAPIView(APIView):
def get(self, request):
"""
TestAPI... |
3389241 | import os
import requests
import json
challenge_name = os.getenv('CHALLENGE_NAME')
test_rate = int(os.getenv('rate', 200))
test_duration = int(os.getenv('duration', 200))
ENDPOINT = os.getenv('ENDPOINT', 'http://localhost:8080')
validation_result = {}
with open(f'workspace/code/{challenge_name}/payload.txt') as payloa... |
3389253 | from setuptools import setup
README_FILE = 'README.rst'
with open(README_FILE, 'r') as d:
desc = d.read()
setup(name='cachepy',
packages=['cachepy', 'cachepy.backends'],
version='1.1',
description='Caching results of functions in Python',
keywords='caching, python, file-based cache, memor... |
3389314 | from scipy.optimize import fsolve
import math
def equations(p):
#vin, imax = p
#return (-78*vin + 3700*imax-2194*vin*imax-23410*imax**2+22.9*vin**3+716382*imax**3)
#vin, imax = fsolve(equations, (0.9, 0.01))
#print (equations((vin, imax)))
fnom = p
return(3.7442024014121142e04 + -6.846677e-05*fnom ... |
3389349 | from simglucose.analysis.report import report
import pandas as pd
from pathlib import Path
# get the path to the example folder
exmaple_pth = Path(__file__).parent
# find all csv with pattern *#*.csv, e.g. adolescent#001.csv
result_filenames = list(exmaple_pth.glob(
'results/2017-12-31_17-46-32/*#*.csv'))
patien... |
3389357 | import sys
import struct
# Convert word embeddings in GloVe format to binary word2vec format.
glove_filename = sys.argv[1]
w2c_filename = sys.argv[2]
# Count number of words and dimensions.
print "Reading Glove embedding vectors from", glove_filename
fin = open(glove_filename, "r")
num_words = 0
num_dims = 0
for line... |
3389394 | from tensorflow.compat.v1.nn import swish
from tensorflow.compat.v1.keras.layers import Lambda
def Swish(name=None):
return Lambda(swish, name=name)
|
3389438 | from django.conf.urls import url
from .views import (
ArchivedView,
CaseCRUDL,
CaseExportCRUDL,
ClosedCasesView,
FlaggedView,
InboxView,
OpenCasesView,
PartnerCRUDL,
PingView,
SentView,
StatusView,
UnlabelledView,
)
urlpatterns = CaseCRUDL().as_urlpatterns()
urlpatterns... |
3389459 | def search(goods_list):
try:
age_input = int(input("Введите возраст для фильтрации -> "))
except ValueError:
print("Некорректный ввод данных")
return
search_flag = False
print("Товары c фильтрацией по возрасту")
for goods in goods_list:
if goods.age_calculation(age_in... |
3389463 | from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render, HttpResponse
from django.views import View
from .models import HashTag
class tags_view(LoginRequiredMixin,View):
def get(self, request, tag, *args, **kwargs):
tag_obj, created = HashTag.objects.get_or_create(tag=... |
3389475 | import numpy as np
import cv2
class Element:
def __init__(self, id, corner, category, text_content=None):
self.id = id
self.category = category
self.col_min, self.row_min, self.col_max, self.row_max = corner
self.width = self.col_max - self.col_min
self.height = self.row_ma... |
3389496 | import os
import importlib
from kivy.core.window import Window
from kaki.app import App
class OnBoardScreenAppLive(App):
KV_FILES = {
os.path.join(os.getcwd(), "boarding_screen.kv"),
os.path.join(os.getcwd(), "slide.kv"),
}
CLASSES = {
"BoardScreen": "boarding_screen",
"S... |
3389503 | from vcs.vtk_ui.behaviors import KeyableMixin
class PriorityEditor(KeyableMixin):
"""
Provides basic keyboard manipulation of object's priority- up
/ down to raise / lower priority, delete/backspace to set it to 0
"""
def key_pressed(self, key, shift=False, alt=False, control=False):
if ... |
3389522 | from libpalette.command import CommandId
class PaletteError(Exception):
pass
class CommandNotFoundError(PaletteError):
def __init__(self, identifier: CommandId) -> None:
super().__init__(f'Command with identifier {identifier} does not exist')
class QuitException(Exception):
def __init__(self) -> ... |
3389531 | from typing import Type
import pytest
from ..core import type_params_issubclass, merge_params
from .. import Proxytype, GenericProxytype, is_generic, validate_typespec
from ... import Struct, List, Tuple, Int, Float, Str
# NOTE: we test with non-Proxytype classes for this first test to be a little more hermetic,
# si... |
3389548 | import asyncio
from bleak import BleakClient, BleakError
from utils import topics, PubSub
import pyacaia
from coroutines import Base
class AcaiaScaleSensor(Base):
def __init__(self, hub, address):
super().__init__(hub)
self.define_ivar('keep_connected', topics.TOPIC_CONNECT_TO_SCALE, default=False... |
3389553 | import pytorch_lightning as pl
import numpy as np
import torch
# noinspection PyProtectedMember
from torch.utils.data import DataLoader
from spanet.options import Options
from spanet.dataset.jet_reconstruction_dataset import JetReconstructionDataset
from spanet.network.learning_rate_schedules import get_linear_schedu... |
3389565 | raise ImportError(
"""
The dask.distributed.AioClient object has been removed.
We recommend using the normal client with asynchonrous=True
client = await Client(..., asynchronous=True)
and a version of Tornado >= 5.
Documentation: https://distributed.dask.org/en/latest/asynchronous.html
Example: https:/... |
3389575 | import random as r
from pprint import pprint
import math as m
def cria_ponto():
return round(r.uniform(0, 1), 4)
def gera_x(n):
x = set()
while len(x) < n:
x.add(cria_ponto())
return x
def gera_y(n):
y = set()
while len(y) < n:
y.add(cria_ponto())
return y
def gera_co... |
3389585 | class RockBotBase:
def get_mulligan_action(self, scene):
raise NotImplementedError()
def get_play_action(self, scene):
raise NotImplementedError()
def report(self, scene):
raise NotImplementedError()
|
3389629 | import torch
from torch.nn import Parameter
from torch_scatter import scatter_add, scatter_max
from torch_geometric.utils import softmax
from torch_geometric.nn.inits import uniform
from torch_geometric.utils.num_nodes import maybe_num_nodes
def topk(x, ratio, batch, min_score=None, tol=1e-7):
if min_score is no... |
3389669 | import dash
import dash_bio as dashbio
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
HOSTED_GENOME_DICT = [
... |
3389701 | import importlib
import os
import shutil
from django.test import TestCase
from django_secrets.startup import check, create_secrets_package
class SecretTest(TestCase):
def test_adding_a_secret(self):
self.assertEqual(True, True)
def test_creating_secrets_folder(self):
self.assertIn('my_sec... |
3389710 | from collections import Counter
from math import factorial
def num_unique_perms(input_str):
n = len(input_str)
hist = Counter(input_str)
# Equal to 1 to prevent div zero errors if there are no repeated characters
reps = 1
for c, cnt in hist.items():
reps *= factorial(cnt)
return( factorial(n)//reps )
def pe... |
3389712 | import unittest
from mock import Mock, MagicMock
from jira_util import *
class TestJiraUtil(unittest.TestCase):
def setUp(self):
pass
def test_flatten_issue_no_expand(self):
get_issue = Mock()
issue = Mock()
issue.fields = Mock()
issue.fields.subtasks = ['issue2', 'i... |
3389714 | from wemake_python_styleguide.violations.refactoring import (
ImplicitElifViolation,
)
from wemake_python_styleguide.visitors.tokenize.conditions import IfElseVisitor
code_that_breaks = """
number = int(input())
if number == 1:
print("1")
else:
if number == 2: print("2")
"""
code_implict_if_else = """
if ... |
3389746 | import cv2
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from SUMNet_bn import SUMNet
import SimpleITK as sitk
import matplotlib.pyplot as plt
import pandas as pd
from glob import glob
import os
def load_itk_image(filename):
itkimage = sitk.ReadImage(filename)
numpyImage... |
3389762 | import unittest
from pypidb._db import Database, reverse_mappings
class TestDB(unittest.TestCase):
def test_basic(self):
db = Database(store_fetch_list=True)
url = db.find_project_scm_url("setuptools-scm")
self.assertEqual(url, "https://github.com/pypa/setuptools_scm")
class TestData(un... |
3389823 | from threading import Event, Thread
class RenderThread(Thread):
"""
Original Code:
https://github.com/tqjxlm/Simple-DQN-Pytorch/blob/master/Pytorch-DQN-CartPole-Raw-Pixels.ipynb
Data:
- Observation: 3 x 400 x 600
Usage:
1. call env.step() or env.reset() to update env state
... |
3389830 | import os
import numpy as np
from scipy.io import loadmat, whosmat
from mindaffectBCI.decoder.utils import block_randomize, butter_sosfilt, upsample_codebook, lab2ind, window_axis
marker2stim=dict(lh=(1,3),rh=(2,4))
def load_twofinger(datadir, sessdir=None, sessfn=None, fs_out=60, stopband=((45,65),(0,1),(25,-1)), su... |
3389832 | from tensorflow.python.keras.metrics import MeanMetricWrapper
# metric module to monitor arbitrary loss
class Metric(MeanMetricWrapper):
"""
A metric module to monitor arbitrary loss.
"""
def __init__(self, metric, name, dtype=None, **kwargs):
self.metric = metric
# self.name = name
... |
3389833 | from setuptools import setup
SETUP_REQUIRES = [
'pyads >= 3.3.5',
'paho-mqtt >= 1.5.0',
'pytz'
]
setup(
name='MQTT-ADS-interface',
version='0.1.0',
url='https://github.com/RWTH-EBC/AixOCAT/tree/develop/Interfaces/Python/MQTT-ADS-interface',
license='',
author='<NAME>, <NAM... |
3389854 | def test_create_project():
import os
import sys
os.system(
f"{sys.executable} -m kivymd.tools.patterns.create_project "
f"MVC "
f"{os.path.expanduser('~')} "
f"TestProject "
f"{sys.executable} "
f"master "
f"--name_screen TestProjectScreen "
f... |
3389856 | import django
from functools import partial
from sys import version_info
from django.shortcuts import render
from django.template.loader import render_to_string
from django.template.response import TemplateResponse as BaseTemplateResponse
if django.VERSION < (1, 6):
from django.conf.urls.defaults import include... |
3389864 | from matplotlib import pyplot as plt
import torch
use_cuda = True
from IPython.display import SVG, display
import numpy as np
import svgwrite
from six.moves import xrange
import math
import torch.nn as nn
import torchvision
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
import torch.nn.functional... |
3389879 | from datetime import datetime
from typing import Tuple, Union, Dict, Type, List
from aat.core.exchange import ExchangeType
from aat.core.instrument import Instrument
from aat.common import _merge
from .cpp import _CPP, _make_cpp_cash
class CashPosition(object):
__slots__ = ["__notional", "__notional_history", "... |
3389923 | from pypy.jit.timeshifter.test.test_portal import PortalTest, P_OOPSPEC
from pypy.jit.timeshifter.test.test_timeshift import StopAtXPolicy
from pypy.rpython.lltypesystem import lltype, llmemory
from pypy.rpython.lltypesystem.rvirtualizable import VABLERTIPTR
from pypy.rlib.jit import hint
import py
S = lltype.GcStruct... |
3389933 | import json
from jsonschema import Draft4Validator as Validator
import pytest
from jupyterlab_sql.request_decoder import decode, RequestDecodeError
test_schema = {
"type": "object",
"properties": {"prop": {"type": "string"}},
"required": ["prop"],
}
test_body = {"prop": "value"}
def test_decode_not_... |
3389947 | from atlas.models import Department
def test_user_cannot_update(gql_client, default_user, design_department):
executed = gql_client.execute(
"""
mutation {
updateDepartment(department:"%s" data:{name:"Not Design"}) {
ok
errors
department { id, name }
... |
3389978 | from django.test import TestCase
from flat_json_widget.widgets import FlatJsonWidget
class TestFlatJsonWidget(TestCase):
def test_render(self):
widget = FlatJsonWidget()
html = widget.render(name='content', value=None)
self.assertIn('flat-json-original-textarea', html)
self.assert... |
3390013 | import pytest
from fastf1.plotting import TEAM_COLORS, TEAM_TRANSLATE
def test_team_colors_dict_warning():
with pytest.raises(KeyError):
with pytest.warns(UserWarning):
TEAM_COLORS['Ferrari']
with pytest.warns(UserWarning):
TEAM_COLORS.get('Ferrari', None)
TEAM_COLORS['ferrar... |
3390024 | from motor.motor_asyncio import AsyncIOMotorClient
import psycopg2
import aiopg
import hashlib
import time
import logging
logger = logging.getLogger()
async def create_storage(config, plugin_manager, loop):
"""Creates and initializes a storage object.
Args:
plugin_manager -- sarlacc plugin_manager ... |
3390060 | import argparse
import pandas as pd
from firecares.firestation.models import FireDepartment
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = """Updates IAFF local numbers using a given CSV. Expects incoming CSV data to have columns including:
firecares_id, fdid, State_Code, I... |
3390064 | from leapp.actors import Actor
from leapp.libraries.actor import updateetcsysconfigkernel
from leapp.tags import PreparationPhaseTag, IPUWorkflowTag
class UpdateEtcSysconfigKernel(Actor):
"""
Update /etc/sysconfig/kernel file.
In order to proceed with Upgrade process, DEFAULTKERNEL entry should be update... |
3390091 | import argparse
from torch2trt import torch2trt
import torch
from models.with_mobilenet import PoseEstimationWithMobileNet
from modules.load_state import load_state
def convert_to_onnx(net, output_name):
input = torch.zeros(1, 3, 256, 448)
input_names = ['data']
output_names = ['features', 'heatmaps', 'p... |
3390107 | import logging
import tensorflow as tf
FLAGS = tf.app.flags.FLAGS
logger = logging.getLogger("Ealiy Stop")
class EarlyStop():
ZERO=0
BEST = 1
CONTINUE = 2
LEARNING_RATE_DECAY = 3
STOP = -1
def __init__(self,max_retry,max_learning_rate_decay):
self.best_f1_value = 0
self.learnin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.