id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
11414481 | from numpy import array, asarray, ndarray, prod, ufunc, add, subtract, \
multiply, divide, isscalar, newaxis, unravel_index, dtype
from bolt.utils import inshape, tupleize, slicify
from bolt.base import BoltArray
from bolt.spark.array import BoltArraySpark
from bolt.spark.chunk import ChunkedArray
from functools im... |
11414507 | import py, os, sys
from pypy.module._cppyy import interp_cppyy, executor
class AppTestREGRESSION:
spaceconfig = dict(usemodules=['_cppyy', '_rawffi', 'itertools'])
def setup_class(cls):
cls.w_example01 = cls.space.appexec([], """():
import ctypes, _cppyy
_cppyy._post_import_st... |
11414520 | import unittest, random, sys, time, re
sys.path.extend(['.','..','../..','py'])
import h2o, h2o_cmd, h2o_browse as h2b, h2o_import as h2i
# Result from exec is an interesting key because it changes shape depending on the operation
# it's hard to overwrite keys with other operations. so exec gives us that, which allows ... |
11414556 | import scrapy
import dateutil.parser as dparser
from ..items import NewsSitesItem
class RoarSpider(scrapy.Spider):
name = "roar"
allowed_domains = ["roar.lk"]
start_urls = [
"https://roar.media/english/life/",
"https://roar.media/english/tech/",
]
def __init__(self, date=None, *a... |
11414577 | from setuptools import setup, find_packages
setup(
name='octoprint-grbl-plugin',
version='1.0.2',
packages=find_packages(),
license='MIT',
author='mic159',
author_email='<EMAIL>',
url='https://github.com/mic159/octoprint-grbl-plugin',
description='Support GRBL type CNC & Laser machines'... |
11414589 | import logging
from flask import current_app, abort, request
from functools import wraps
AUTH_ROLES = {
'discovery': 'discovery',
'lyftapi': 'lyftapi',
'tom': 'tom',
}
def basic_authenticate(f):
@wraps(f)
def decorated(*args, **kwargs):
if not current_app.config.get("USE_AUTH"):
... |
11414640 | import six
from copy import deepcopy
from .fields import PrimaryKeyField, FieldDescriptor, Field, ForeignRelatedObject
from .query import UpdateQuery, InsertQuery, SelectQuery
from .signals import pre_save, post_save
from .utils import force_text, force_str
from . import get_default_handler
class DoesNotExist(Excep... |
11414641 | from django.conf import settings as django_settings
def settings(request):
# return the value you want as a dictionary. you may add multiple values.
return {'SFM_UI_VERSION': django_settings.SFM_UI_VERSION, 'CONTACT_EMAIL': django_settings.CONTACT_EMAIL,
'INSTITUTION_NAME': django_settings.INSTITU... |
11414657 | from flask import jsonify
from flask import request
from clover.views import CloverView
from clover.core.exception import catch_exception
from clover.history.service import HistoryService
class HistoryView(CloverView):
def __init__(self):
super(HistoryView, self).__init__()
self.service = Histor... |
11414668 | data = (
'[?]', # 0x00
'[?]', # 0x01
'[?]', # 0x02
'[?]', # 0x03
'[?]', # 0x04
'[?]', # 0x05
'[?]', # 0x06
'[?]', # 0x07
'[?]', # 0x08
'[?]', # 0x09
'[?]', # 0x0a
'[?]', # 0x0b
'[?]', # 0x0c
'[?]', # 0x0d
'[?]', # 0x0e
'[?]', # 0x0f
'[?]', # 0x10
'[?]... |
11414685 | from my_module.operations.elementary import multiply, divide
from my_module.operations.exponentiation import square
def universal_gravitation_of_newton(m1, m2, r):
"""
This function return Newton's law of universal gravitation
"""
G = 6.6726e-11
return multiply(G, divide(multiply(m1, m2), square(r)... |
11414689 | import sys, os
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, os.path.join(CURRENT_DIR, "..", ".."))
import constants
OPEN_FILE_BROWSER = "nautilus ~ &"
if sys.platform.startswith(constants.MAC_OS_X_IDENTIFIER):
OPEN_FILE_BROWSER = "open ~ %"
TRIGGER_MODEL = "OPEN_FILE_BROWSER.model"... |
11414704 | class ArbitrageConfig(object):
def __init__(self, options={}):
self.name = options['name']
self.base_coin = options['base_coin']
self.quote_coin = options['quote_coin']
self.symbol = f"{self.base_coin}/{self.quote_coin}"
self.one_to_two_pure_profit_limit = float(options['one_... |
11414707 | import abc
class AbstractEarlyStopAlgorithm(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def get_early_stop_trials(self, trials):
"""
Pass the trials and return the list of trials to early stop.
Args:
trials: The all trials of this study.
Returns:
... |
11414714 | from pulsar.api import PulsarException
from pulsar.utils.log import LazyString
from ..utils.serializers import Message
from . import states
__all__ = ['TaskError',
'TaskNotAvailable',
'TaskTimeout',
'Task']
class TaskError(PulsarException):
status = states.FAILURE
class TaskN... |
11414775 | import os
import configparser
class Setup:
def start_sconfig(self, config):
default = 'default'
config.add_section('default')
bot_name = str(input("Enter Bot name (default=jarvis): ") or "jarvis")
user_name = str(input("Enter User name (default=dipesh): ") or "Dipesh")
pho... |
11414790 | import sys, os, pytest
sys.path.append(os.getcwd())
from do_grader_lib import PartQuality
from tsp import grader
with open('tsp/data/tsp_5_1', 'r') as input_data_file:
input_data = input_data_file.read()
quality = PartQuality('test', 5, 4)
greedy_submission = '4.8 0\n0 1 2 4 3\n123\n'
opt_submission = '4.0 ... |
11414816 | from backend.common.cache.noop_cache import NoopCache
def test_noop_cache() -> None:
cache = NoopCache()
assert cache.get(b"key") is None
assert cache.set(b"key", "value") is True
assert cache.get(b"key") is None
stats = cache.get_stats()
assert stats is not None
assert stats["misses"] =... |
11414852 | def extractBruinTranslation(item):
"""
# 'Bruin Translation'
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol or frag) or 'preview' in item['title'].lower():
return None
if not item['title']:
return False
if item['tags'] == ['Uncategorized'] and item['title'].s... |
11414902 | import os
import torch
from tools import model_name_search
from affordance_vaed import Decoder, Encoder, AffordanceVAED
from torchvision import transforms
class RosPerceptionVAE(object):
def __init__(self, model_dir, latent_dim):
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
... |
11414934 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import time
from torch.utils.data import DataLoader
import dgl
def edge_attention(edges):
e = edges.data['e']
return {'e': e}
def edge_attention_without_e(edges):
z2 = torch.cat([edges.src['z'],... |
11414978 | pkgname = "lmdb"
pkgver = "0.9.29"
pkgrel = 0
build_wrksrc = "libraries/liblmdb"
build_style = "makefile"
make_cmd = "gmake"
make_check_target = "test"
make_use_env = True
hostmakedepends = ["gmake"]
pkgdesc = "Lightning Memory-Mapped Database Manager"
maintainer = "q66 <<EMAIL>>"
license = "OLDAP-2.8"
url = "http://sy... |
11414985 | import numpy as np
import pandas as pd
import asyncio
from ..workbench.em_framework.ema_distributed import AsyncDistributedEvaluator
from ..workbench.util import get_module_logger
_logger = get_module_logger(__name__)
class AsyncExperimentalDesign:
def __init__(self, model, design, stagger_start=0):
self.model = ... |
11414989 | import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import tensorflow.compat.v1 as tf
import math
import numpy as np
import itertools
import json
from PIL import Image
tf.enable_eager_execution()
from waymo_open_dataset.utils import range_image_utils
from waymo_open_dataset.utils import transform_utils
from waymo_ope... |
11415019 | from proud.unification.interface import TCState
import proud.unification.type_encode as te
cnt = 0
tcs = TCState()
list = te.InternalNom("list")
var = tcs.user_var()
t1 = te.normalize_forall(["x"], te.App(te.UnboundFresh("x"), te.UnboundFresh("x")))
t2 = te.normalize_forall(["x"], te.App(te.UnboundFresh("x"), var))... |
11415031 | from __future__ import division, print_function
import os, sys, re
import numpy as np
import tensorflow as tf
from scipy import stats
import soundfile as sf
from emotion_inferring.model.model import Model_Creator
from emotion_inferring.utils import *
from emotion_inferring.dataset.audio import acoustic_gen
... |
11415042 | from __future__ import absolute_import
import json
from math import floor, sqrt
from os import sep as os_sep
from os import path
from helper.utilities import all_in
from poketrainer.game_master import GAME_MASTER, PokemonData
from poketrainer.poke_lvl_data import POKEMON_LVL_DATA, TCPM_VALS, get_tcpm
POKEMON_NAMES =... |
11415062 | from setuptools import setup
setup(name='pycrayon',
description='Crayon client for python',
author='torrvision',
url='https://github.com/torrvision/crayon',
packages=['pycrayon'],
version='0.5',
install_requires=[
"requests"
]
) |
11415087 | state_capitals = {
"Ohio" : "Columbus",
"Alabama" : "Montgomery",
"Arkansas" : "Little Rock"
}
print(state_capitals["Ohio"])
|
11415096 | from __future__ import absolute_import, division, print_function
from imps.core import Sorter, split_imports
def test_base_bad_order():
input = """import Z
import X
import Y
"""
output = """import X
import Y
import Z
"""
assert Sorter().sort(input) == output
def test_base_more_spaces():
input = """... |
11415100 | import pycom
import time
pycom.heartbeat(False)
while True:
pycom.rgbled(0xFF0000)
time.sleep(1)
pycom.rgbled(0x00FF00)
time.sleep(1)
pycom.rgbled(0x0000FF)
time.sleep(1)
|
11415114 | import torch
from torch.nn import functional as F
from PIL import Image
from models.flownet2.models import *
from torchvision import transforms
import matplotlib.pyplot as plt
import argparse
from utils.general import get_gpu_id_with_lowest_memory
class FlownetPipeline:
def __init__(self):
super(Flownet... |
11415137 | loader_defaults = {
'loader_kwargs':{
'num_workers': 4,
'pin_memory': True,
},
'n_groups_per_batch': 4,
}
|
11415160 | from collections import OrderedDict
import logging
import scipy
import numpy as np
from theano import tensor
from theano.tensor.signal.pool import pool_2d, Pool
from blocks.extensions import SimpleExtension
from blocks.extensions.monitoring import (DataStreamMonitoring,
Monit... |
11415172 | from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from example.users.models import User
admin.site.register(User, UserAdmin)
|
11415189 | from __future__ import print_function, unicode_literals
import os
import sys
import six
import urlparse
import traceback
from sqlalchemy.orm import scoped_session, sessionmaker
import flask
from flask import Flask, request, redirect, escape, url_for
from flask_admin import Admin
from flask_admin.menu import MenuLink
... |
11415258 | from celery import app
import random
import time
from celery_progress import backend
@app.task(bind=True)
def test_task(self):
for i in range(100):
time.sleep(float(random.randrange(1, 10))/10)
backend.set_progress(self.request.id, i)
return 'done'
|
11415275 | from importlib import import_module
from shapeworld import util
class CaptionRealizer(object):
def __init__(self, language):
self.language = language
self.attributes = None
self.relations = None
self.quantifiers = None
@staticmethod
def from_name(name, language):
... |
11415278 | import argparse
import json
import os
import pickle
import sys
from itertools import chain
from utils.io import load_mesh
def load_meshes(args: argparse.Namespace, mappings: list):
meshes = []
unique_cads = set(
(model['catid_cad'], model['id_cad'],
mapping['category_id'], mapping['sym'])
... |
11415284 | import logging
from pathlib import Path
from gd.typing import IO, Optional, Union
__all__ = (
"enable_file_handler_for",
"enable_stream_handler_for",
"get_logger",
"log",
"setup_logging",
)
ALL_STYLES = ("%", "{", "$")
DEFAULT_LOG_FORMAT = "[{levelname}] ({asctime}) [{name}] {module}.{funcName}:... |
11415376 | def helper(got,expected):
if got == expected:
print True
else:
print False, expected, got
print "\nstr.strip"
helper("hello".strip(),'hello')
helper("hello".strip(''),'hello')
helper(" hello ".strip(),'hello')
helper(" hello ".strip(''),' hello ')
helper("..hello..".strip(),'..hello..')
h... |
11415394 | from testutils import assert_raises
class Fubar:
def __init__(self):
self.x = 100
@property
def foo(self):
value = self.x
self.x += 1
return value
f = Fubar()
assert f.foo == 100
assert f.foo == 101
assert type(Fubar.foo) is property
class Bar:
def __init__(self):... |
11415466 | import xarray as xr
from starfish.core.util.try_import import try_import
from starfish.types import Features
class ExpressionMatrix(xr.DataArray):
"""Container for expression data extracted from an IntensityTable
An ExpressionMatrix is a 2-dimensional ``cells`` x ``genes`` array whose values are the
nu... |
11415536 | from datetime import timedelta
from django.contrib.postgres.fields import RangeField, IntegerRangeField, BigIntegerRangeField, DateRangeField
from inclusive_django_range_fields.forms import InclusiveIntegerRangeFormField, InclusiveDateRangeFormField
class BaseInclusiveRangeField(RangeField):
form_field = None
... |
11415550 | import FWCore.ParameterSet.Config as cms
CSCTFConfigOnline = cms.ESProducer("CSCTFConfigOnlineProd",
onlineAuthentication = cms.string('.'),
forceGeneration = cms.bool(False),
onlineDB = cms.string('oracle://CMS_OMDS_LB/CMS_TRG_R')
)
|
11415609 | from numpy.testing import *
import numpy
from algopy.tracer.tracer import *
from algopy.utpm import *
D,P,N = 4,1,100
A = UTPM(numpy.random.rand(D,P,N,N))
Q,R = UTPM.qr(A)
l = UTPM(numpy.random.rand(D,P,N))
L = UTPM.diag(l)
A = UTPM.dot(Q, UTPM.dot(L,Q.T))
l2,Q2 = UTPM.eigh(A)
print('error between true and reconst... |
11415627 | import sys
import socket
import getopt
import threading
import subprocess
#global var
listen = False
command = False
upload = False
execute = ""
target = ""
upload_destination = ""
port = 0
def run_command(cmd):
"""runs a command and return the output
"""
cmd = cmd.rstrip()
try:
output = subp... |
11415641 | from kivymd.theming import ThemableBehavior
from kivymd.uix.boxlayout import MDBoxLayout
from kivymd.uix.tab import MDTabsBase
class CraneFlyScreen(ThemableBehavior, MDBoxLayout, MDTabsBase):
pass
|
11415664 | import numpy as np
import pandas as pd
from shapely.geometry import Point
from mfsetup.fileio import check_source_files
from mfsetup.grid import get_ij
def read_observation_data(f=None, column_info=None,
column_mappings=None):
df = pd.read_csv(f)
df.columns = [s.lower() for s in df... |
11415714 | import warnings
BACKENDS = ("numpy", "jax")
BACKEND_MESSAGES = {"jax": "Kernels are compiled during first iteration, be patient"}
_init_done = set()
def init_jax_config():
if "jax" in _init_done:
return
import jax
from veros import runtime_settings, runtime_state
from veros.state import (
... |
11415759 | from moncli.routes import constants
from moncli.routes.requests import execute_get
def get_tag_by_id(api_key, tag_id):
resource_url = constants.TAGS_BY_ID.format(tag_id)
return execute_get(api_key, resource_url) |
11415769 | from decimal import Decimal
from datetime import datetime
from client.coinex_client import CoinExClient
from client.huobi_client import HuoBiClient
from db.mongo import TraceLog
class TradeSvr(CoinExClient, HuoBiClient):
def __init__(self, *args, **kwargs):
self.coinex = CoinExClient()
self.huo... |
11415776 | import importlib
import json
import numpy as np
import os
import sys
import time
import uuid
import copy
from hypergan.discriminators import *
from hypergan.distributions import *
from hypergan.generators import *
from hypergan.inputs import *
from hypergan.samplers import *
from hypergan.trainers import *
import hyp... |
11415829 | import pytest
import requests
LIMITED_ENDPOINTS = ["/api/v0/authenticate", "/api/v0/auth_extended"]
@pytest.mark.integration
@pytest.mark.nomock
def test_rate_limit(controller_url):
for endpoint in LIMITED_ENDPOINTS:
for i in range(30):
r = requests.post(
controller_url + end... |
11415831 | from distill.distill_util import DistillLoss, get_probs
from tasks.task import Task
import tensorflow as tf
import tensorflow_datasets as tfds
from tf2_models.metrics import ClassificationLoss
from tfds_data.aff_nist import AffNist
class Mnist(Task):
def __init__(self, task_params, name='mnist', data_dir='mnist_da... |
11415838 | import argparse
import json
import sys
import threading
import time
import boto3
import requests
from requests.exceptions import ConnectionError
class SqsReceiver(object):
def __init__(self, options):
self.options = options
self.debug = options.debug
def deliver_message(self, message):
... |
11415880 | import os
import time
import json
import glob
import torch
import torch.optim as optim
from torch.autograd import grad
import torchvision.transforms as transforms
from easydict import EasyDict
from PIL import Image
from torch.utils.data import DataLoader, WeightedRandomSampler
from torchvision.utils import save_image
... |
11415889 | from django.contrib.auth.models import User
from django.test import RequestFactory
from django_hats.context_processors import roles
from tests import RolesTestCase
from tests.roles import Scientist
class TemplateTageTestCases(RolesTestCase):
# Tests `django_hats.templatetags.roles.roles`
def test_roles_user... |
11415917 | import os
import os.path
import sys
import time
import requests
import biothings, config
biothings.config_for_app(config)
from config import DATA_ARCHIVE_ROOT
from biothings.hub.dataload.dumper import LastModifiedHTTPDumper
from biothings.utils.common import unzipall
class CGIDumper(LastModifiedHTTPDumper):
SRC... |
11415947 | import unittest
from vp import image_tools
class TestCalculateBorderSize(unittest.TestCase):
def test_no_border(self):
self.assertEqual(
image_tools._calculate_border_size(100, 100, [(0, 0), (100, 100)]),
(0, 0))
def test_no_points(self):
self.assertEqual(
... |
11415952 | import sys
import json
import pickle
import os
import numpy as np
import math
from random import shuffle
def load_description(descriptions_file_path):
with open(descriptions_file_path, 'r') as file_stream:
descriptions = json.load(file_stream)
return {
os.path.splitext(description['name'])[0... |
11415967 | import z5py
from heimdall import view_arrays
def example_2d(z=0):
path = '/home/pape/Work/data/cremi/example/sampleA.n5'
with z5py.File(path) as f:
ds = f['volumes/raw/s0']
ds.n_threads = 8
raw = ds[z]
ds = f['volumes/segmentation/groundtruth']
ds.n_threads = 8
... |
11415987 | import torch.utils.data as data
import numpy as np
import torch
import cv2
import config
import os
import glob
import sys
sys.path.append("../")
from utils.img import Crop
from util import Rnd, Flip, rot2Quaternion,angular_distance_np
import util
import warnings
from scipy.sparse import csc_matrix
from sklearn.neighbor... |
11415994 | from tests import TestCase
from src.masonite.middleware import Middleware
from src.masonite.routes import Route
class TestUpdateMiddleware(Middleware):
def before(self, request, response):
request.session.set("key", "value")
request.session.flash("flash_key", "flash_value")
return request
... |
11416030 | import os
from unittest import mock
from django.core.checks.async_checks import E001, check_async_unsafe
from django.test import SimpleTestCase
class AsyncCheckTests(SimpleTestCase):
@mock.patch.dict(os.environ, {'DJANGO_ALLOW_ASYNC_UNSAFE': ''})
def test_no_allowed_async_unsafe(self):
self.assertEqu... |
11416041 | import numpy as np
def calc_iou(box1, box2):
# box: left, top, right, bottom
w = min(box1[2], box2[2]) - max(box1[0], box2[0])
h = min(box1[3], box2[3]) - max(box1[1], box2[1])
if w <= 0 or h <= 0:
return 0
intersection = w * h
s1 = (box1[2] - box1[0]) * (box1[3] - box1[1])
s2 = (bo... |
11416052 | from .finder import Finder, TIME_LIMIT, MAX_RUNS
from pathfinding.core.util import backtrace
from pathfinding.core.diagonal_movement import DiagonalMovement
class BreadthFirstFinder(Finder):
def __init__(self, heuristic=None, weight=1,
diagonal_movement=DiagonalMovement.never,
ti... |
11416067 | import sys,os
src = sys.argv[1]
import vcs.testing.regression as regression
import vcs
import vcsaddons, numpy
import cdms2, cdutil, cdtime
x = regression.init()
f = cdms2.open(os.path.join(vcs.sample_data, "thermo.nc"))
temp = f('t')
levels = temp.getLevel()
time = temp.getTime()
# Break up temp by level
magnitudes ... |
11416077 | import py
from collections import namedtuple
import capnpy
# ============================================================
# Instance storage
# ============================================================
class Instance(object):
class MyStruct(object):
def __init__(self, padding, bool, int8, int16, int32,... |
11416079 | import unittest
from tests.lib.client import get_client
from tests.lib.card_products import CardProducts
from marqeta.errors import MarqetaError
class TestCardsSave(unittest.TestCase):
"""Tests for the cards.save endpoint."""
@classmethod
def setUpClass(cls):
"""Setup for all the tests in this c... |
11416100 | import os
import tempfile
from collections import Counter
from json import JSONDecodeError
import dill
import numpy as np
import pandas as pd
import pytest
from podium.datasets import ExampleFactory
from podium.datasets.dataset import Dataset
from podium.datasets.hierarhical_dataset import HierarchicalDataset
from po... |
11416121 | import os
from collections import OrderedDict
from mindware.components.feature_engineering.transformations.base_transformer import Transformer
from mindware.components.utils.class_loader import find_components, ThirdPartyComponents
"""
Load the buildin classifiers.
"""
balancer_directory = os.path.split(__file__)[0]
_... |
11416143 | import argparse
import os
import numpy as np
import faiss
import time
import ctypes
parser = argparse.ArgumentParser()
parser.add_argument('--dstore_keys', type=str, default='', help='memmap where keys and vals are stored')
parser.add_argument('--dstore_vals', type=str, default='', help='memmap where keys and vals ar... |
11416160 | from __future__ import print_function,absolute_import,division,unicode_literals
_A=False
import datetime,copy
if _A:from typing import Any,Dict,Optional,List
class TimeStamp(datetime.datetime):
def __init__(A,*B,**C):A._yaml=dict(t=_A,tz=None,delta=0)
def __new__(A,*B,**C):return datetime.datetime.__new__(A,*B,**C)
... |
11416195 | import pandas as pd
df = pd.DataFrame([[13,0,0,0], [0,0,18,0]])
print(df)
'''
0 1 2 3
0 13 0 0 0
1 0 0 18 0
'''
# "delete" the zero-columns
df2 = df.loc[:, (df != 0).any(axis=0)]
print(df2)
'''
0 2
0 13 0
1 0 18
'''
|
11416205 | import re
import sqlite3
import time
def get_database():
return SqliteDb()
class Database:
def insert(self, host, lines):
raise NotImplementedError
def search(self, query):
raise NotImplementedError
class SqliteDb(Database):
def __init__(self, filename='database.db'):
db ... |
11416210 | 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 FunctionAbsoluteTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
# connect to a DolphinDB server
... |
11416220 | from socket import socket, AF_INET, SOCK_DGRAM
from socket import error as sock_error
from ncrypt.rand import bytes as rand_bytes
from nitro.async import AsyncOp
from nitro.tcp import tcpListen
from cspace.dht.rpc import RPCSocket
from cspace.dht.firewalltest import FirewallTestServer
from cspace.dht.client impo... |
11416239 | from textractgeofinder.tword import TWord
import logging
logger = logging.getLogger(__name__)
def test_creation(caplog):
caplog.set_level(logging.DEBUG)
tword: TWord = TWord(text="test",
text_type="text_type",
confidence=99,
id="test-... |
11416249 | from django.conf import settings
from django.utils.datastructures import MultiValueDictKeyError
from django.core.exceptions import ObjectDoesNotExist
from django.contrib import messages
from django.contrib.auth import login, logout, authenticate, update_session_auth_hash
from django.contrib.auth.hashers import make_pas... |
11416289 | import bpy
from bpy.props import *
from ...nodes.BASE.node_base import RenderNodeBase
class RenderNodeGetObjectVisibility(RenderNodeBase):
bl_idname = 'RenderNodeGetObjectVisibility'
bl_label = 'Get Object Visibility'
def init(self, context):
self.create_input('RenderNodeSocketObject', 'object', ... |
11416294 | import eos
import numpy as np
from scipy.io import loadmat
# This script loads the Liverpool-York Head Model (LYHM, [1]) from one of their Matlab .mat files into the eos model
# format, and returns an eos.morphablemodel.MorphableModel.
#
# Note: The LYHM does not come with texture (uv-) coordinates. If you have textur... |
11416370 | import warnings
from .exceptions import AsdfDeprecationWarning
# This is not exhaustive, but represents the public API
from .versioning import join_tag_version, split_tag_version
from .types import (AsdfType, CustomType, format_tag, ExtensionTypeMeta)
__all__ = ["join_tag_version", "split_tag_version", "AsdfType", "C... |
11416377 | import torch.nn as nn
from utils import *
from torch.nn.utils.rnn import pad_packed_sequence
import Constants
try:
from apex import amp
APEX_AVAILABLE = True
except ModuleNotFoundError:
APEX_AVAILABLE = False
class Trainer(object):
def __init__(self, args, tgt_vocab, model, optimizer, device, disable... |
11416390 | from abc import ABC, abstractmethod
from typing import Callable, Optional, Sequence
import numpy as np
VectorizedBoundaryConditionFunction = \
Callable[[np.ndarray, Optional[float]], np.ndarray]
class BoundaryCondition(ABC):
"""
A base class for boundary conditions.
"""
@property
@abstractm... |
11416391 | from waterbutler import settings
config = settings.child('OSF_AUTH_CONFIG')
JWT_EXPIRATION = int(config.get('JWT_EXPIRATION', 15))
JWT_ALGORITHM = config.get('JWT_ALGORITHM', 'HS256')
API_URL = config.get('API_URL', 'http://localhost:5000/api/v1/files/auth/')
JWE_SALT = config.get('JWE_SALT')
JWE_SECRET = config.ge... |
11416401 | def event_handler(obj, event):
list_btn = lv.list.__cast__(obj)
if event == lv.EVENT.CLICKED:
print("Clicked: %s" % list_btn.get_btn_text())
# Create a list
list1 = lv.list(lv.scr_act())
list1.set_size(160, 200)
list1.align(None, lv.ALIGN.CENTER, 0, 0)
# Add buttons to the list
list_btn = list1.add_b... |
11416422 | import unittest
from unittest import mock
from sequoya.core.solution import MSASolution
from sequoya.operator.crossover import SPXMSA
from sequoya.problem import MSA
class GapSequenceSolutionSinglePointTestCases(unittest.TestCase):
def setUp(self):
self.problem = MSA(score_list=[])
self.problem.... |
11416440 | from pydip.map.territory import SeaTerritory
from pydip.player.helpers import (
unit_can_enter,
unit_can_support,
territory_is_convoy_compatible,
)
from pydip.player.unit import UnitTypes
class Command:
""" Player -- who is issuing command """
player = None
""" Unit -- unit being issued comma... |
11416456 | from .hopper_cql_default_config import hopper_cql_default_config
from .hopper_expert_cql_default_config import hopper_expert_cql_default_config
from .hopper_medium_cql_default_config import hopper_medium_cql_default_config
|
11416487 | import math
import random
from itertools import product
import numpy as np
import torch
from gym.spaces import Box, Discrete, Tuple
from sdriving.environments.intersection import (
MultiAgentRoadIntersectionBicycleKinematicsEnvironment,
)
from sdriving.tsim import (
BatchedVehicle,
FixedTrackAccelerationM... |
11416539 | from abc import ABC, abstractmethod
class RenderStrategy(ABC):
"""An interface to render things"""
def __init__(self, data):
self.set_data(data)
def set_data(self, data):
self.data = data
self.prepared = False
def plot(self, ax, *args, **kwargs):
if not self.prepared... |
11416614 | from django.apps import AppConfig
class ClassbasecrudConfig(AppConfig):
name = 'classBaseCrud'
|
11416624 | import numpy as np
import cv2
img = cv2.imread("chessboardPrinted.jpg")
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
cv2.imshow("Gray", gray)
# Find the chess board corners
ret, corners = cv2.findChessboardCorners(gray, (7,7),None)
# If found, add object points, image points (after refining them)
if ret == True:
... |
11416637 | from django.urls import path
from .views import show_dish, show_order, get_order
app_name = 'dish'
urlpatterns = [
path('dish/', show_dish),
path('order/', show_order, name='show_order'),
path('get_order/<slug:dish_id>', get_order, name='get_order'),
] |
11416660 | from staffjoy.resource import Resource
from staffjoy.resources.organization import Organization
from staffjoy.resources.cron import Cron
from staffjoy.resources.user import User
from staffjoy.resources.plan import Plan
from staffjoy.resources.chomp_task import ChompTask
from staffjoy.resources.mobius_task import Mobius... |
11416676 | import os
from typing import List, Tuple, Any
import pandas as pd
import tensorflow as tf
from tensorflow import feature_column as fc
# from algorithm.WideAndDeep.Wide_and_Deep import example_parser, train_input_fn, eval_input_fn, create_feature_columns, FLAGS
# 定义输入参数
flags = tf.app.flags
# 训练参数
flags.DEFINE_strin... |
11416698 | from setuptools import setup, Extension
from torch.utils import cpp_extension
setup(name='rel_to_abs_index_cuda',
ext_modules=[cpp_extension.CUDAExtension('rel_to_abs_index_cuda', ['rel_to_abs_index_cuda.cpp', 'rel_to_abs_index_cuda_kernel.cu'])],
cmdclass={'build_ext': cpp_extension.BuildExtension}... |
11416715 | import argparse
import cv2
import numpy as np
from pathlib import Path
from tqdm import tqdm
import json
from misc_utils import load_image, load_vflow, save_image
def downsample_images(args, downsample=2):
indir = Path(args.indir)
outdir = Path(args.outdir)
outdir.mkdir(exist_ok=True)
rgb_paths = lis... |
11416756 | import pandas as pds
from train_mortality_model import *
import pickle
ASSET_PATH = 'data/res/'
MODEL_STAGING_PATH = ''
with open(MODEL_STAGING_PATH + "adjutorium_mortality", "rb") as f:
death_model = pickle.load(f)
with open(MODEL_STAGING_PATH + "adjutorium_discharge", "rb") as f:
discharge_model = pickle.load... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.