id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
9875800 | from xml.dom.ext.reader.Sax import FromXmlFile
from xml.dom.NodeFilter import NodeFilter
root = FromXmlFile('problem1.xml')
walker = root.createTreeWalker(root.documentElement,
NodeFilter.SHOW_ELEMENT, None, 0)
while 1:
nodeName = walker.currentNode.nodeName
if nodeName == 'gam... |
9875844 | from rest_framework import status
from rest_framework.response import Response
from rest_framework.generics import GenericAPIView
from ..permissions import IsAuthenticated
from ..app_settings import (
CreateFileRepositoryRightSerializer,
UpdateFileRepositoryRightSerializer,
DeleteFileRepositoryRightSeriali... |
9875852 | from __future__ import absolute_import
from .PrawOAuth2Mini import PrawOAuth2Mini # noqa
from .PrawOAuth2Server import PrawOAuth2Server # noqa
|
9875865 | import os
import json
import numpy as np
import matplotlib.pyplot as plt
import sys
import h5py
vibe_dir = sys.argv[1] # folder containing the json files.
reqd_joints = [38, 43, 44, 45, 46, 47, 48, 40, 37, 33,32,31, 34,35,36, 41, 39, 27,26,25, 28,29,30, 22, 19]
idx = 0
files_order = []
joint_data_final = []
labels_fi... |
9875911 | import time
from funcx.sdk.client import FuncXClient
def hello_world() -> str:
return "Hello World"
def wait_for_task(fxc, task_id, walltime: int = 2):
import time
start = time.time()
while True:
if time.time() > start + walltime:
raise Exception("Timeout")
try:
... |
9875929 | from hustle import Table, insert
from hustle.core.settings import Settings, overrides
import ujson
IMPS = '__test_imps'
PIXELS = '__test_pixels'
PIXELS_HLL = '__test_pixels_hll'
IPS = '__test_ips'
def imp_process(data):
from disco.util import urlsplit
_, (host, _), _ = urlsplit(data['url'])
if host.sta... |
9875949 | import mock
def test_pytest_messenger_ding_failed(testdir):
"""Make sure that our pytest-messenger works."""
testdir.makepyfile(
"""
import pytest
def test_pass():
assert 1 == 1
def test_fail():
assert 1 == 2
@pytest.mark.skip()
def ... |
9875990 | import pyspark
import sagemaker_pyspark
from pyspark import SparkConf
from pyspark.sql import SparkSession, DataFrame
from datetime import datetime, timedelta
import argparse
import logging
import boto3
import botocore
import time
import os
from typing import Tuple
logger = logging.getLogger('__name__')
logger.setLev... |
9876034 | import pytest
from loan_calculator.grossup.service_fee import linear_service_fee
def test_linear_service_fee():
assert linear_service_fee(100.0, 0.01) == pytest.approx(1.0, rel=0.01)
|
9876035 | import collections
from functools import partial, reduce, lru_cache
import simplejson as json
import pandas as pd
import numpy as np
from .core import parallel, render_html, listify, add, CORD_CHALLENGE_PATH, BIORXIV_MEDRXIV, \
NONCOMM_USE_SUBSET, CUSTOM_LICENSE, COMM_USE_SUBSET, find_data_dir
from pathlib import P... |
9876037 | from .status import ORDER_FOUND, ORDER_NOT_FOUND, INVALID_AMOUNT
from django.conf import settings
class ClickUz:
ORDER_FOUND = ORDER_FOUND
ORDER_NOT_FOUND = ORDER_NOT_FOUND
INVALID_AMOUNT = INVALID_AMOUNT
def check_order(self, order_id: str, amount: str):
"""
:Need to check order
... |
9876062 | import FWCore.ParameterSet.Config as cms
caloStage1Raw = cms.EDProducer(
"L1TDigiToRaw",
Setup = cms.string("stage1::CaloSetup"),
InputLabel = cms.InputTag("simCaloStage1FinalDigis"),
TauInputLabel = cms.InputTag("simCaloStage1FinalDigis", "rlxTaus"),
IsoTauInputLabel = cms.InputTag("simCaloStage1F... |
9876070 | import abc
import io
import re
import json
import yaml
import requests
from collections import OrderedDict, defaultdict
from django.core import exceptions
from django.utils.module_loading import import_string
import tabulator
from .. import utils
from ..ingest_settings import UPLOAD_SETTINGS
#######################... |
9876097 | import numpy as np
import pytest
from scipy import sparse
from xugrid import connectivity
@pytest.fixture(scope="function")
def triangle_mesh():
fill_value = -1
# Two triangles
faces = np.array(
[
[0, 1, 2],
[1, 3, 2],
]
)
return faces, fill_value
@pytest... |
9876116 | l = list()
print l
l.append(1)
print l
d = dict()
print d
d["zap"] = 1
print d
# Make sure this still works
l2 = list(l)
print l2
l3 = list(d)
print l3
# It would be nice to make this work
# But that would be a separate issue
# d2 = dict(d.items())
# print d2
|
9876119 | import FWCore.ParameterSet.Config as cms
deadChannelTest = cms.EDAnalyzer("DTDeadChannelTest",
debug = cms.untracked.bool(False),
runningStandalone = cms.untracked.bool(True),
diagnosticPrescale = cms.untracked.int32(1),
folderRoot = cms.untracked.string(''),
#Names of the quality tests: they must ... |
9876131 | from abc import abstractmethod, ABC
from typing import Dict
class CallbackDataBase(ABC):
"""
Callback data factory
"""
def __init__(self, prefix, *parts, sep=':'):
if not isinstance(prefix, str):
raise TypeError(f'Prefix must be instance of str not {type(prefix).__name__}')
... |
9876132 | from rlkit.data_management.contextual_replay_buffer import (
ContextualRelabelingReplayBuffer,
)
from rlkit.envs.contextual import ContextualEnv, delete_info
from rlkit.envs.contextual.goal_conditioned import (
GoalDictDistributionFromMultitaskEnv,
ContextualRewardFnFromMultitaskEnv,
AddImageDistributi... |
9876134 | import os
import subprocess
import threading
import time
def write_data_in_chunks(total_size):
start_time = time.time()
filename = "/mnt/test_{}_{}.txt".format(total_size, start_time)
f = open(filename, "wb+")
chunk = b'\xff'*4048
for i in range(total_size / 4048):
f.write(chunk)
f.flush()
os.fsync(f... |
9876146 | import sys
from asyncio import CancelledError, create_task, sleep
from time import time
import pytest
from quattro import move_on_after
pytestmark = pytest.mark.skipif(
sys.version_info < (3, 9), reason="requires python3.9 or higher"
)
@pytest.mark.asyncio
async def test_move_on_after():
start = time()
... |
9876153 | import os
import json
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from SocketServer import BaseRequestHandler
from xfinity_control_web.xfinity_control import XfinityApiException
class XfinityControlServer(HTTPServer):
SERVER_ADDRESS = ""
SERVER_PORT = 8081
def __init__(self, xfinity_con... |
9876162 | data = (
# Code points u+007f and below are equivalent to ASCII and are handled by a
# special case in the code. Hence they are not present in this table.
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', '', '', '', '', '', '', '... |
9876166 | from .state_core import StateCore
def inline(state: StateCore) -> None:
"""Parse inlines"""
for token in state.tokens:
if token.type == "inline":
if token.children is None:
token.children = []
state.md.inline.parse(token.content, state.md, state.env, token.child... |
9876168 | from collections import defaultdict, OrderedDict, MutableMapping, Hashable
import os
import pdb
import sys
import random
import math
import csv
import tensorboardX
class TensorboardManager:
def __init__(self, path):
self.writer = tensorboardX.SummaryWriter(path)
def update(self, split, step, vals):
... |
9876210 | from pitop import Camera, DriveController, PanTiltController, Pitop
from pitop.labs import RoverWebController
from pitop.labs.web.blueprints.rover import drive_handler, pan_tilt_handler
rover = Pitop()
rover.add_component(DriveController())
rover.add_component(PanTiltController())
rover.add_component(Camera())
rover_... |
9876211 | from unittest.mock import Mock, patch
from django.http.request import QueryDict
from django.test import TestCase
from formation.forms import CombinableCountyFormSpec
from formation.combinable_base import FormSpecSelector
from formation import fields as F
from formation.form_base import Form
from intake.services import ... |
9876230 | import torch
from learnergy.models.gaussian import gaussian_conv_rbm
def test_gaussian_conv_rbm_hidden_sampling():
new_gaussian_conv_rbm = gaussian_conv_rbm.GaussianConvRBM()
v = torch.ones(5, 1, 7, 7)
probs, states = new_gaussian_conv_rbm.hidden_sampling(v)
assert probs.size(1) == 5
assert sta... |
9876263 | import os
from setuptools import setup, find_packages
from async_v20 import __version__
def read(f):
return open(os.path.join(os.path.dirname(__file__), f)).read().strip()
setup(name='async_v20',
version=__version__,
description="Asynchronous wrapper for OANDA's v20 REST API",
long_descriptio... |
9876270 | import re
from typing import Iterable
from firebase_admin import exceptions
from mapswipe_workers import auth
from mapswipe_workers.definitions import CustomError, logger
def chunks(data: list, size: int = 250) -> Iterable[list]:
"""Yield successive n-sized chunks from list."""
for i in range(0, len(data), ... |
9876276 | import unittest
import pandas as pd
from qiime2 import Artifact, CategoricalMetadataColumn
from qiime2.plugins import mmvec
import biom
import numpy as np
# these tests just make sure the visualizer runs; nuts + bolts are tested in
# the main package.
class TestHeatmap(unittest.TestCase):
def setUp(self):
... |
9876291 | LAYOUTS = {
"DEFAULT" : { # default layout
"width" : 800,
"height" : 600,
"history_size" : 7,
"root" : "#eeeeee",
"stage" : "#bbbbbb",
"toolbar" : "#dddddd",
"toolbar-width" : 30,
"toolbar-height" : 30,
"toolbar-padding" : 5,
"toolbar-column" : 1,
"button" : "#ffffff",
"button... |
9876299 | import bpy
import os
import xml.etree.ElementTree as ET
from mathutils import Vector, Quaternion
from bpy_extras.io_utils import ImportHelper
from bpy.props import StringProperty, BoolProperty, EnumProperty
from bpy.types import Operator
import time
import random
from .tools import cats as Cats
from .ydrimport import ... |
9876304 | import os
import re
import time
from collections import OrderedDict
from urllib.error import URLError, HTTPError
from urllib.parse import urljoin
from urllib.request import urlretrieve
import numpy as np
import pandas as pd
from .exceptions import DrmsExportError, DrmsOperationNotSupported, DrmsQueryError
from .json ... |
9876328 | import numpy as np
from probflow.parameters import ScaleParameter
def test_ScaleParameter():
"""Tests probflow.parameters.ScaleParameter"""
# Create the parameter
param = ScaleParameter()
# All samples should be > 0
assert np.all(param.posterior_sample(n=1000) > 0)
# 1D ScaleParameter
... |
9876355 | import os.path as op
import array
import pynodegl as ngl
from pynodegl_utils.misc import scene
def _load_model(fp):
index = 0
vertices = []
uvs = []
normals = []
vertex_indices = []
uv_indices = []
normal_indices = []
indexed_vertices = array.array('f')
indexed_uvs = array.array... |
9876403 | import os
from prodtest import ProduceTestCase
class ShellTest(ProduceTestCase):
"""
Tests using a Perl rather than a Bash recipe.
"""
def test_shell(self):
self.produce('hello.txt')
self.assertFileContents('hello.txt', 'Hello, world!\n')
|
9876406 | from ._manifold_helpers import rminus, rplus, rplus_jacobian_parameters_wrt_delta
__all__ = [
"rminus",
"rplus",
"rplus_jacobian_parameters_wrt_delta",
]
|
9876434 | import os
from dagster import DependencyDefinition, GraphDefinition, SolidInvocation, op
from dagster.utils.yaml_utils import load_yaml_from_path
@op
def add_one(num: int) -> int:
return num + 1
@op
def add_two(num: int) -> int:
return num + 2
@op
def subtract(left: int, right: int) -> int:
return le... |
9876443 | from typing import Any
from . import N52xx
class N5230C(N52xx.PNABase):
def __init__(self, name: str, address: str, **kwargs: Any):
super().__init__(name, address,
min_freq=300e3, max_freq=13.5e9,
min_power=-90, max_power=13,
nport... |
9876450 | import torch
import torch.nn.functional as F
from .evaluator import Evaluator
class SSTEvaluator(Evaluator):
def get_scores(self):
self.model.eval()
self.data_loader.init_epoch()
n_dev_correct = 0
total_loss = 0
for batch_idx, batch in enumerate(self.data_loader):
... |
9876494 | from ontobio.golr.golr_query import GolrSearchQuery
import pytest
import pysolr
"""
A group of integration tests that test integration
between a live solr instance and ontobio
Will fail if either monarch or go servers are down
"""
def test_search():
q = GolrSearchQuery("abnormal")
print("Q={}".format(q))
... |
9876506 | from __future__ import absolute_import
import numpy as np
from sklearn import datasets
from sklearn import metrics
from sklearn.model_selection import train_test_split
import os
os.chdir(r"F:\研究生\github项目\python半监督包\semisupervised")
import sys
sys.path.append(r"F:\研究生\github项目\python半监督包\semisupervised")
# normalizat... |
9876533 | def foo1(context):
context.write("this is foo1.")
return ""
def foo2(context, x):
context.write("this is foo2, x is " + x)
return ""
foo3 = "I'm not a callable"
|
9876542 | from .assets import *
from .base import *
from .builders import *
from .cacheable import *
from .channels import *
from .guild import *
from .interactions import *
from .message import *
from .snowflake import *
from .user import *
|
9876563 | def test_preflight_authenticate(app):
sanic_app, _ = app
_, response = sanic_app.test_client.options("/auth")
assert response.status == 204
assert not response.body
def test_preflight_retrieve_user(app):
sanic_app, _ = app
_, response = sanic_app.test_client.options("/auth/me")
assert re... |
9876583 | import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()
driver.get("https://github.com/login")
elem = driver.find_element_by_id("login_field")
elem.clear()
elem.send_keys("w<PASSWORD>")
elem = driver.find_element_by_id("password")
elem.clear()
elem.send... |
9876617 | from os.path import dirname, abspath, join
from flask.ext.sqlalchemy import SQLAlchemy
from single_mod_app import db
#for the config section
_cwd = dirname(abspath(__file__))
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + join(_cwd, 'flask_temp.db')
#need to run this just ONCE to create the database
db.create_all()
#note... |
9876666 | from alluxio import wire
from util import assert_json_decode, assert_json_encode, assert_string_subclass
from random_wire import random_worker_net_address, random_block_location, random_block_info, random_file_block_info, \
random_mode, random_file_info
def test_bits():
assert_string_subclass(wire.BITS_NONE,... |
9876675 | import json
import os
import sys
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from chat_parser import parse_logs
def load_dataset():
messages = []
responses = []
with open('data.json', 'r', encoding="utf8") as openfileobject:
... |
9876701 | import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
import torch
from torch.autograd import Function, Variable
import numpy as np
__all__ = ['ResNet', 'resnet50']
model_urls = {
'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
}
def conv3x3(in_planes, out_planes,... |
9876714 | import torch.utils.model_zoo
from .modelv1 import *
from .modelv2 import *
from .quantization.modelv1 import *
from .quantization.modelv2 import *
url_map = {
'hairmattenetv1': 'https://github.com/wonbeomjang/mobile-hair-segmentation-pytorch/releases/download/paramter/hairmattenet_v1.pth',
'hairmattenetv2': '... |
9876799 | import unittest
from minos.networks import (
BrokerMessageV1,
BrokerMessageV1Payload,
BrokerPublisher,
InMemoryBrokerPublisher,
)
class TestInMemoryBrokerPublisher(unittest.IsolatedAsyncioTestCase):
def test_is_subclass(self):
self.assertTrue(issubclass(InMemoryBrokerPublisher, BrokerPubl... |
9876833 | from torchvision.datasets import MNIST
from torch.utils.data import Subset
import torchvision.transforms.functional as TF
import torchvision.transforms as transforms
import torch
import numpy as np
import os
import nn_ood
class RotatedMNIST(Subset):
def __init__(self, split, N=None):
self.mean_rot = 0
... |
9876855 | import os
import tempfile
import unittest
import numpy as np
from keras_multi_head import MultiHeadAttention
from keras_layer_normalization.backend import keras
from keras_layer_normalization import LayerNormalization
class TestLayerNormalization(unittest.TestCase):
def test_sample(self):
input_layer = k... |
9876890 | from PyQt5.QtWidgets import QLineEdit, QDialog, QTreeWidget, QRadioButton, QMessageBox, QTreeWidgetItem, QTabWidget, QPushButton, QLabel, QComboBox, QWidget, QCheckBox
from os.path import basename
from PyQt5.QtGui import QIcon
from PyQt5.QtGui import QColor, QBrush
from PyQt5.QtCore import Qt
from PyQt5 import uic
impo... |
9876919 | import torch
import numpy as np
import os
import glob
class PseudoKittiDataset(torch.utils.data.Dataset):
def __init__(self, shuffle=True, input_name='asdf', load_seg=False, load_i=False):
dataset_location = './tcr_pseudo'
records = glob.glob('%s/*_%s_*.npz' % (dataset_location, input_name))
... |
9876937 | from future.builtins import object
from .context import get_current_config, connections, log
from bson import ObjectId
from collections import defaultdict
from .processes import ProcessPool, Process
class Supervisor(Process):
""" Manages several mrq-worker single processes """
def __init__(self, command, nu... |
9876941 | from typing import List, Optional, Type
from graphql.error import GraphQLError
from graphql.language import parse
from graphql.type import GraphQLSchema
from graphql.utilities import build_schema
from graphql.validation import ValidationRule, SDLValidationRule
from graphql.validation.validate import validate, validate... |
9876962 | from flask import Blueprint, render_template, redirect, request
from flask_login import (current_user, login_user, logout_user,
login_required)
from stravalib import Client
from monolith.database import db, User
from monolith.forms import LoginForm
auth = Blueprint('auth', __name__)
@auth.... |
9876974 | from secml.testing import CUnitTest
import numpy as np
from secml.utils import fm
from secml.array.c_dense import CDense
class TestCDense(CUnitTest):
"""Unit test for CDense."""
def test_save_load(self):
self.logger.info("UNITTEST - CDense - save/load matrix")
test_file = fm.join(fm.abspa... |
9876981 | from .backbones import *
from .blocks import *
from .heads import *
from .losses import *
from .necks import *
from .trackers import *
from .utils import *
from .builder import * |
9876985 | import os
import argparse
import time
import torch.multiprocessing as mp
from torch.multiprocessing import Process, Pipe
import log
from model_utils import load_model
from model_utils import print_args
from batch_train import worker
def main():
parser = argparse.ArgumentParser(description='The ultimate tester')
... |
9877038 | import os
from cpcli.utils.constants import DEFAULT_CONTEST_FILES_DIR
def readable_dir(path):
error = TypeError(f'readable_dir:{path} is not a valid dir')
if path == DEFAULT_CONTEST_FILES_DIR and not os.path.exists(path):
os.mkdir(DEFAULT_CONTEST_FILES_DIR)
if not os.path.isdir(path):
r... |
9877118 | import os
import sys
import time
import struct
import socket
import random
import Queue
import threading
class targetlib(object):
def __init__(self):
'''
self.tgt_q = Queue.Queue()
this is a Queue.Queue() and holds a random generated iplist via generate_random_ip()
to see the content of it:
size: print... |
9877126 | from enum import IntEnum
import logging
from typing import Mapping
import attr
from bs4 import BeautifulSoup
from .requester import Requester
# For RIH
class MontageModality(IntEnum):
XR = 95
CR = 100
CT = 4
XA = 66
def __str__(self):
return str(self.value)
# Max results to review for a ... |
9877184 | import yaml
import sys
import stringcase
def read_spec(filename):
with open(filename) as f:
return yaml.load(f)
SPECIAL = [ 'TLS', 'TCP', 'IPv4', 'IPv6' ]
def label_to_const_name(label):
s = stringcase.pascalcase(label.lower())
for spec in SPECIAL:
s = s.replace(spec.lower().title(), sp... |
9877190 | from sqlalchemy import Column, Integer, Boolean, ForeignKey, UniqueConstraint
from .database import Base
class ProjectVersionDependency(Base):
__tablename__ = "projectversiondependency"
__table_args__ = (UniqueConstraint("projectversion_id", "dependency_id", name="unique_projectversiondepedency"),
... |
9877215 | import socket
from collections import defaultdict
from time import sleep
from colors import color
fg = color.fg
style = color.style
class Group:
"""
Group class to manage group functions
"""
def __init__(
self, name: str, admin: str, conn: socket.socket, type: str, secret_key=None
) -> ... |
9877240 | import numpy as np
import pymorph
def test_sedisk():
se = pymorph.sedisk(4)
w,h = se.shape
assert w == h
X,Y = np.where(~se)
X -= w//2
Y -= h//2
assert np.all( X**2+Y**2 > (w//2)**2 )
|
9877306 | import environ
from django.test import TestCase
from django_sharding_library.settings_helpers import database_config, database_configs
class DatabaseConfigTestCase(TestCase):
databases = '__all__'
def setUp(self):
self.default_database_url = 'postgres://user:pass@localhost/test_db'
env = en... |
9877334 | from re import findall, match
from datetime import datetime
from datetime import timedelta
abs_due_regex = r'^[:<>](\d{0,2})(\d{0,2})(\d{2})?:?(\d{0,2})(\d{0,2})$'
rel_due_regex = r'^:(?:(\d+)y)?(?:(\d+)mo)?(?:(\d+)w)?(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?$'
secs_in_sec = 1
secs_in_min = 60
mins_in_hour = 60
hours_in... |
9877364 | import pandas as pd
from random import random
flow = (list(range(1,10,1)) + list(range(10,1,-1)))*1000
pdata = pd.DataFrame({"a":flow, "b":flow})
pdata.b = pdata.b.shift(9)
data = pdata.iloc[10:] * random() # some noise
import numpy as np
def _load_data(data, n_prev = 100):
"""
data should be pd... |
9877385 | from __future__ import annotations
from io import BytesIO
from typing import Any
import better_bencode
KRPCTypes = Any
KRPCList = Any
KRPCDict = Any
class BencoderError(Exception):
pass
def encode(obj: Any) -> bytes:
try:
return better_bencode.dumps(obj)
except Exception as e:
raise B... |
9877389 | import os
import unittest
import tempfile
import shutil
import cv2
from glob import glob
from faceutils import detect_faces, io, visualize, face_landmarks
class VisualizeTest(unittest.TestCase):
"""
Test methods in face visualizer
"""
def __init__(self, *args, **kwargs):
unittest.TestCase.__... |
9877394 | import json
import tqdm
from multiprocessing import cpu_count, Pool
from typing import Callable, Dict, List
from blinker import signal
send_progress = signal('progress')
def get_files_to_remove(duplicates: Dict[str, List]) -> List:
"""
Get a list of files to remove.
Args:
duplicates: A dictionary... |
9877424 | import random
import re
import xml.etree.ElementTree as ET
from collections import defaultdict
from itertools import accumulate
from pathlib import Path
import torch
from torch.utils.data.dataset import Dataset
from torchaudio.sox_effects import apply_effects_file, apply_effects_tensor
class QUESST14Trainset(Dataset... |
9877432 | from PIL import Image
import pyocr
import pyocr.builders
import sys
import re
import io
class OCRProxyResponse:
def __init__(self):
self.text = ''
self.success = False
self.message = ''
class OCRProxy:
def __init__(self):
self.ocr = None
self.lang = None
for to... |
9877438 | import os
import sys
import pysam
import random
from collections import Counter
from .step import StepChunk
from ..mlib import util
from ..mlib.fq_idx import FastqIndex
MIN_SEED_SIZE = 400
MIN_COV = 10.
class CheckReadsStep(StepChunk):
@staticmethod
def get_steps(options):
assert os.path.isfile(options.inpu... |
9877455 | import sys
class BinaryStdout:
buffer = 0
n = 0
@classmethod
def write_int(cls, x):
cls.write_byte((x >> 24) & 0xff)
cls.write_byte((x >> 16) & 0xff)
cls.write_byte((x >> 8) & 0xff)
cls.write_byte((x >> 0) & 0xff)
@classmethod
def write_bits(cls, x, r):
... |
9877480 | import requests
import urllib
from NASA_accounts import apps
app = apps["pyNASA"]
dataset = "y77d-th95"
url_basis = "https://data.nasa.gov/resource/%s.json?%s"
headers = {"X-App-Token": app["token"]}
query = {
"$limit" : 1000,
"$offset" : 0
}
qs = urllib.parse.urlencode(query)
url = url_basis % (dataset, qs)
req =... |
9877518 | import torch
import torch.nn as nn
class Conv_Block(nn.Module):
def __init__(self, in_channels, out_channels):
super().__init__()
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(out_channels)
self.conv2 = nn.Conv2d(o... |
9877558 | import os
import argparse
import hashlib
import json
from tqdm import tqdm
import nibabel
import numpy as np
import torch
from torch.nn.functional import interpolate
EXCLUDED_CASES = []#[23, 68, 125, 133, 15, 37]
MAX_ID = 210
MEAN_VAL = 101.0
STDDEV_VAL = 76.9
MIN_CLIP_VAL = -79.0
MAX_CLIP_VAL = 304.0
TARGET_SPACING... |
9877569 | from ..factory import Method
class getMessages(Method):
chat_id = None # type: "int53"
message_ids = None # type: "vector<int53>"
|
9877603 | import networkx as nx
import numpy as np
import torch
from torch_geometric import utils
from torch_geometric.data import Data, InMemoryDataset
NODE_PRIMITIVES = [
# 'none',
'input_0',
'input_1',
'inter_node',
'output'
]
OP_PRIMITIVES = [
'identity',
'max_pool_3x3',
'avg_pool_3x3',
... |
9877609 | import responses
from binance.error import ParameterTypeError, ParameterArgumentError
from tests.util import mock_http_response
from binance.spot import Spot as Client
from urllib.parse import urlencode
mock_item = {"key_1": "value_1", "key_2": "value_2"}
params = {"symbols": '["BTCUSDT", "ETHUSDT", "BNBUSDT"]'}
@m... |
9877646 | import time
import tkinter as tk
import tkinter.ttk as ttk
import typing
from fishy.libs.tkhtmlview import HTMLLabel
from fishy.web import web
from ..helper.config import config
if typing.TYPE_CHECKING:
from . import GUI
# noinspection PyProtectedMember
def discord_login(gui: 'GUI'):
if web.is_logged_in():... |
9877690 | import os
from os.path import exists, join
import logging
import numpy as np
import pandas as pd
from sklearn.datasets._base import _fetch_remote
from .dataset import Dataset
from ._utils import _mkdirp, RemoteFileMetadata, get_data_home
ARCHIVE = RemoteFileMetadata(
filename="amazon.csv",
url="https://www.... |
9877736 | import os.path
import logging
from utils import make_id, get_resource
from os.path import join
logger = logging.getLogger(__name__)
def apps_dir():
return os.path.dirname(os.path.abspath(__file__))
def load_app(app_def_file, app_id=None, parent_group="/"):
"""Loads an app definition from a json file and s... |
9877738 | import base64
import io
import math
from typing import Any
from PIL import Image
def to_image(obj: Any) -> Image.Image:
"""Convert `obj` to instance of Pillow's Image class."""
if obj is None or isinstance(obj, Image.Image):
return obj
return Image.open(obj)
def image_to_base64(image: Image.Ima... |
9877776 | from torch.utils.data import Dataset
from torchvision import transforms
import numpy as np
import math
import os
import cv2
from PIL import Image
from datasets.data_io import *
# the DTU dataset preprocessed by <NAME> (only for training)
class MVSDataset(Dataset):
def __init__(self, datapath, listfile, mode, nvie... |
9877783 | import pomdp_py
from pomdp_problems.tag.domain.action import *
class TagRewardModel(pomdp_py.RewardModel):
def __init__(self, small=1, big=10):
self.small = small
self.big = big
def probability(self, reward, state, action, next_state, normalized=False, **kwargs):
if reward == self._re... |
9877790 | import os
from imbDRL.agents.ddqn import TrainDDQN
from imbDRL.data import get_train_test_val, load_csv
from imbDRL.utils import rounded_dict
from tensorflow.keras.layers import Dense, Dropout
os.environ["CUDA_VISIBLE_DEVICES"] = "-1" # CPU is faster than GPU on structured data
episodes = 100_000 # Total number of... |
9877813 | import torchquantum as tq
import torchquantum.functional as tqf
import torch
import torch.nn.functional as F
import numpy as np
import os
from torchquantum.encoding import encoder_op_list_name_dict
from torchpack.utils.logging import logger
from examples.core.tools.generate_ansatz_observables import (
molecule_nam... |
9877817 | from sklearn.datasets import make_blobs
# Creating a sample dataset with 4 clusters
X, y = make_blobs(n_samples=800, n_features=3, centers=4) |
9877838 | from OpenMatch.modules.encoders.cnn_encoder import Conv1DEncoder
from OpenMatch.modules.encoders.feed_forward_encoder import FeedForwardEncoder
from OpenMatch.modules.encoders.positional_encoder import PositionalEncoder
from OpenMatch.modules.encoders.transformer_encoder import TransformerEncoder
|
9877859 | from collections import defaultdict
import lldb
import json
from intelpt_testcase import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
from lldbsuite.test.decorators import *
import os
class TestTraceExport(TraceIntelPTTestCaseBase):
mydir = TestBase.compute_mydir(__file__)
def ... |
9877899 | from django.db.models.query import QuerySet
__all__ = ('ShardQuerySet', )
class ShardQuerySet(QuerySet):
def __init__(self, model, *args, **kwargs):
super().__init__(model=model, *args, **kwargs)
self._instance = None
@property
def db(self):
if self._db:
return self._... |
9877911 | import torch
import torch.utils.data
import torchvision
from tqdm import tqdm
import numpy as np
import random
def IRLbl(labels):
# imbalance ratio per label
# Args:
# labels is a 2d numpy array, each row is one instance, each column is one class; the array contains (0, 1) only
N, C = labels.shape
pos_nums_per_la... |
9877921 | import numpy as np
import pandas as pd
from hdfe import Groupby
import pytest
@pytest.fixture
def df() -> pd.DataFrame:
np.random.seed(0)
n_obs = 100
n_categories = 10
return pd.DataFrame(
{
"first category": np.random.choice(n_categories, n_obs),
"y": np.random.normal(... |
9877951 | def normalize_pretag(pretag):
if pretag == "S":
return "B"
elif pretag == "E":
return "I"
return pretag
def preprocess_labels(label_sents):
data = []
for sent in label_sents:
for label in sent:
tokens = label.split("-")
if len(tokens) == 2:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.