id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
4851826 | from kaishi.image.file_group import ImageFileGroup
def test_to_grayscale():
test = ImageFileGroup("tests/data/image", recursive=True)
test.configure_pipeline(["TransformToGrayscale"])
test.load_all()
test_ind = 0
while repr(test.files[test_ind]) != "sample.jpg":
test_ind += 1
assert te... |
4851912 | import datetime
from django.db.models import Q
from rest_framework.views import APIView
from movie.models import MovieRatings, MovieLikes, \
MovieComments, CollectMovieDB
from api import user_api, movie_api, api, delay_work
from api.response import JsonError, JsonResponse
Movie = movie_api.Movie()
emoution = Mo... |
4851945 | import viola
import pandas as pd
from io import StringIO
import os
HERE = os.path.abspath(os.path.dirname(__file__))
class TestReadBedpe:
data = """chrom1\tstart1\tend1\tchrom2\tstart2\tend2\tname\tscore\tstrand1\tstrand2
chr1\t10\t13\tchr2\t20\t30\ttest1\t10\t+\t+
chr3\t100\t130\tchr3\t210\t230\ttest2\t30\t-\t+
""... |
4851952 | import glob
import os
import random
import time
import numpy as np
import keras_vgg_buddy
from keras import backend as K
from keras.callbacks import LearningRateScheduler
def generate_training_batches(args, input_generator):
'''Prepare a batch of input data from input_generator to be used as training data.
E... |
4851990 | from itertools import count
from typing import List, Sequence, Tuple, Type, Union
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils.rnn import PackedSequence
from laia.common.types import Param2d, ParamNd
from laia.data import PaddedTensor
from laia.models.htr import ConvBlock
fro... |
4852012 | def sort(arr):
for i in range(len(arr)-1):
for j in range(len(arr)-1-i):
if( arr[j] > arr[j+1] ):
arr[j],arr[j+1] = arr[j+1],arr[j]
return arr
arr = list(map(int,input("Enter Numbers: ").split()))
print(sort(arr))
|
4852042 | from itertools import chain
from . import tool
from .common import SimpleCommand
from ..iterutils import iterate
@tool('rm')
class Rm(SimpleCommand):
def __init__(self, env):
default = ['rm -f']
if env.host_platform.family == 'windows':
default.append('cmd /c del')
super().__i... |
4852052 | import argparse
import torch.nn.functional as F
import numpy as np
from data import *
from mir import *
from utils import get_logger, get_temp_logger, logging_per_task
from buffer import Buffer
from copy import deepcopy
from pydoc import locate
from model import ResNet18, MLP
# Arguments
# ----------------... |
4852069 | import numpy as np
import jax
from momentum.hmc.hmc_within_gibbs import hmc_within_gibbs
from momentum.potential.correlated_topic_models import (
generate_correlated_topic_models_potential,
)
from momentum.utils import jax_prng_key
def draw_samples_hmc_within_gibbs(n_samples, w, mu, Sigma, beta, epsilon, L, mode... |
4852088 | from __future__ import print_function
import pybilt.bilayer_analyzer.bilayer_analyzer as ba
def test_com_frame_sub_selection():
analyzer = ba.BilayerAnalyzer(structure='../pybilt/sample_bilayer/sample_bilayer.psf',
trajectory='../pybilt/sample_bilayer/sample_bilayer_10frames.dcd',
... |
4852105 | from pylayers.antprop.rays import *
from pylayers.gis.layout import *
from pylayers.antprop.signature import *
import pylayers.signal.bsignal as bs
import pylayers.signal.waveform as wvf
import matplotlib.pyplot as plt
from pylayers.antprop.antenna import *
from pylayers.antprop.channel import *
import copy
import t... |
4852253 | import skimage.io as io
import skimage.transform as skt
import numpy as np
from PIL import Image
from src.models.class_patcher import patcher
from src.utils.imgproc import *
from scipy.interpolate import interp1d
class patcher(patcher):
def __init__(self, body='./body/body_uketsukejo.png', **options):
sup... |
4852343 | from orbit.estimators.pyro_estimator import PyroEstimatorSVI
def test_pyro_estimator_vi(stan_estimator_lgt_model_input):
stan_model_name, model_param_names, data_input = stan_estimator_lgt_model_input
# create estimator
vi_estimator = PyroEstimatorSVI(num_steps=50)
# extract posterior samples
po... |
4852357 | input = """
1 2 1 1 3
1 3 1 1 2
1 4 1 1 5
1 5 1 1 4
1 6 1 1 7
1 7 1 1 6
1 8 1 1 9
1 9 1 1 8
1 10 1 1 11
1 11 1 1 10
1 12 1 1 13
1 13 1 1 12
1 1 2 0 2 4
1 1 2 1 4 2
1 1 2 1 2 4
1 1 2 2 2 4
1 1 2 0 2 6
1 1 2 1 6 2
1 1 2 1 2 6
1 1 2 2 2 6
1 1 2 0 10 12
1 1 2 1 12 10
1 1 2 1 10 12
1 1 2 2 10 12
0
8 d
6 c
11 ne
5 nb
12 f
2 ... |
4852408 | import asyncio
import uuid
class BaseChaincode:
def __init__(self, cc_name):
self.evts = {}
self._name = cc_name
def create_onCcEvent(self, _uuid, tx_id):
class CCEvent(object):
def __init__(self, _uuid, evts, evt_tx_id):
self.uuid = _uuid
s... |
4852435 | import os
import unittest
from openql import openql as ql
from utils import file_compare
curdir = os.path.dirname(os.path.realpath(__file__))
output_dir = os.path.join(curdir, 'test_output')
class Test_instruction_decomposition(unittest.TestCase):
@classmethod
def setUp(self):
ql.initialize()
... |
4852500 | from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import ConversationHandler
from botlistbot import util
from botlistbot.const import CallbackActions
def manage_subscription(bot, update):
chat_id = update.effective_chat.id
user_id = update.effective_user.id
if util.is_gro... |
4852553 | from recordthresher.record_maker import CrossrefRecordMaker
from recordthresher.util import parseland_parse
class SsrnRecordMaker(CrossrefRecordMaker):
@staticmethod
def _is_specialized_record_maker(pub):
return pub.doi.startswith('10.2139/ssrn.')
@classmethod
def _make_source_specific_record... |
4852566 | from typing import List
class Solution:
def countQuadruplets(self, nums: List[int]) -> int:
cnt = 0
for i, a in enumerate(nums):
for j, b in enumerate(nums[i + 1 :]):
for k, c in enumerate(nums[i + j + 2 :]):
for d in nums[i + j + k + 3 :]:
... |
4852607 | import logging
from collections import OrderedDict
from datetime import datetime
from extractionSteps.JobStepBase import JobStepBase
from util.stdlib_utils import get_recursively
class DashboardsAPM(JobStepBase):
def __init__(self):
super().__init__("apm")
async def extract(self, controllerData):
... |
4852618 | import os
from base64 import b64decode, b64encode
from enum import Enum
from ..core.Simple import Simple
from ... import helper
class TmplType(Enum):
table = "0"
base64 = "1"
html = "3"
text = "4"
scheme = "6"
extension = "9"
# todo добавить остальные типы макетов и их сериализацию
clas... |
4852654 | import pytest
import os
from snapshottest import snapshot
from lmsrvlabbook.tests.fixtures import fixture_working_dir
import flask
class TestUserIdentityQueries(object):
def test_logged_in_user(self, fixture_working_dir, snapshot):
query = """
{
userIdentity{
... |
4852760 | import bisect
import random
import torch
import torch.utils.data as data
from .h36m_smpl import H36mSMPL
from .hp3d import HP3D
from .mscoco import Mscoco
s_mpii_2_smpl_jt = [
6, 3, 2,
-1, 4, 1,
-1, 5, 0,
-1, -1, -1,
8, -1, -1,
-1,
13, 12,
14, 11,
15, 10,
-1, -1
]
s_3dhp_2_smp... |
4852769 | from datetime import datetime
import dateutil.parser
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
import pytz
utc = pytz.UTC
class FieldNotFound(Exception):
pass
def get_duration_html():
try:
incident_id = demisto.incident().get('id', {})
conte... |
4852801 | import logging
from django.core.management.base import BaseCommand
import openkamer.parliament
logger = logging.getLogger(__name__)
class Command(BaseCommand):
def handle(self, *args, **options):
openkamer.parliament.create_parliament_and_government(all_members=False)
|
4852822 | import FWCore.ParameterSet.Config as cms
#
# module to make the mvaComputer
#
findTtSemiLepJetCombMVA = cms.EDProducer("TtSemiLepJetCombMVAComputer",
#-------------------------------------------------
# sources (leptons, jets, MET)
#-------------------------------------------------
leps = cms.InputTag(... |
4852860 | from NewLoadBalancerRule import NewLoadBalancerRule
class Rules(list):
def __init__(self, *args, **kwargs):
super(Rules, self).__init__(*args, **kwargs)
def __setitem__(self, key, value):
assert isinstance(value, NewLoadBalancerRule), Exception(
'Expected NewLoadBalancerRule, got:... |
4852863 | from preprocessing.preprocessing import *
from staffremoval.staffremoval import *
from classifiers.digitsClassifier import *
from classifiers.accedintalsClassifier import *
from inout.generateOutput import *
from features.checkScanned import *
from features.extractfeatures import *
from deskewing.deskewing import *
fro... |
4852881 | import hetu as ht
from hetu import onnx as hx
import onnxruntime as rt
import numpy as np
import tensorflow.compat.v1 as tf
# tf.disable_v2_behavior()
import tf2onnx
import argparse
import six.moves.cPickle as pickle
import gzip
import os
import pdb
import ctypes
import time
# ctx=ht.gpu(0)
ctx = ht.cpu(0)
bat... |
4852885 | import plotly.plotly as py
import plotly.graph_objs as go
from plotly.tools import FigureFactory as FF
#plotly.tools.set_credentials_file(username='rezacsedu', api_key='<KEY>')
import numpy as np
import pandas as pd
import scipy
matrix1 = np.matrix(
[[1, 5],
[6, 2]]
)
matrix2 = np.matrix(
[[-1, 4],
... |
4852936 | import json
import unittest
import responses
import pyyoutube
class ApiVideoAbuseReason(unittest.TestCase):
BASE_PATH = "testdata/apidata/abuse_reasons/"
BASE_URL = "https://www.googleapis.com/youtube/v3/videoAbuseReportReasons"
with open(BASE_PATH + "abuse_reason.json", "rb") as f:
ABUSE_REASON... |
4852966 | from textwrap import dedent
from typing import Optional, Union
import strawberry
def test_union_as_field():
@strawberry.type
class A:
a: int
@strawberry.type
class B:
b: int
@strawberry.type
class Query:
ab: Union[A, B] = A(a=5)
schema = strawberry.Schema(query=... |
4853013 | import os
import sys
from time import sleep
import requests
from django.core.management import BaseCommand, call_command
from django.db.migrations.recorder import MigrationRecorder
class Command(BaseCommand):
help = (
"Runs the deployment in our CI/CD pipeline such that a call to perform a "
"one... |
4853020 | update_post_description = """
UPDATE
posts
SET
description = "The weather has become pleasant now"
WHERE
id = 2
"""
execute_query(connection, update_post_description)
|
4853029 | import frappe
def execute():
frappe.reload_doc('website', 'doctype', 'web_page_view', force=True)
site_url = frappe.utils.get_site_url(frappe.local.site)
frappe.db.sql("""UPDATE `tabWeb Page View` set is_unique=1 where referrer LIKE '%{0}%'""".format(site_url))
|
4853038 | def check(cmd, mf):
m = mf.findNode("re")
if m:
return {"expected_missing_imports": {"sys.getwindowsversion"}}
|
4853049 | from django.test import TestCase, override_settings
from mock import Mock
from garnett import utils
class TestUtils(TestCase):
def test_get_language_from_request(self):
request = Mock()
request.GET = {"glang": "en"}
request.COOKIES = {"GARNETT_LANGUAGE_CODE": "de"}
request.META = ... |
4853051 | import itertools
from collections import namedtuple
import numpy as np
from scipy.stats import ks_2samp
from sklearn.model_selection import train_test_split
import sklearn.utils
import matplotlib as mpl
import matplotlib.colors
import seaborn as sns
from collections import defaultdict
import xgboost as xgb
impo... |
4853055 | import logging,os
from app.config import APP_ENV
class Log:
'''
日志工具类,使用示例:
from flask import current_app
current_app.logger.info('yyyy')
'''
def __init__(self):
# 创建日志目录
log_path = APP_ENV.LOGPATH
log_name = APP_ENV.LOGNAME + '.log'
log_path = os.path.abspath(os... |
4853059 | from mypy.stubgen import (StubGenerator, find_self_initializers, FUNC, EMPTY, METHODS_WITH_RETURN_VALUE,)
import sys
from typing import (List, Dict, Optional)
from mypy.nodes import (
# Expression, IntExpr, UnaryExpr, StrExpr, BytesExpr, NameExpr, FloatExpr, MemberExpr,
# TupleExpr, ListExpr, ComparisonExpr, C... |
4853066 | from trailscraper.iam import all_known_iam_permissions, Action, known_iam_actions
def test_all_iam_permissions():
permissions = all_known_iam_permissions()
assert permissions != []
assert "ec2:DescribeInstances" in permissions
assert len(permissions) == len(set(permissions)), "expected no duplicates"... |
4853081 | import FWCore.ParameterSet.Config as cms
PythiaMSSMmhmax = cms.vstring(
'RMSS(2)= 200. ! SU(2) gaugino mass ',
'RMSS(3)= 800. ! SU(3) (gluino) mass ',
'RMSS(4)= 200. ! higgsino mass parameter',
'RMSS(6)= 1000. ! left slepton mass',
'RMSS(7)= 1000. ... |
4853106 | import os
import requests
import sys
def get_key(platform):
if platform == "TI73": return 0x02
if platform == "TI83p" or platform == "TI83pSE": return 0x04
if platform == "TI84p" or platform == "TI84pSE": return 0x0A
if platform == "TI84pCSE": return 0x0F
def get_upgrade_ext(platform):
if platform... |
4853136 | import pickle
from abc import ABC, abstractmethod
from component.features import MentionFeatureExtractor
from constants import SubsystemTypes
from util import Timer
from util.loadutils import *
from util.logutils import *
class ExperimentSystem(ABC):
def __init__(self, iteration_num=1, use_test_params=True):
... |
4853148 | import subprocess
import pytest
HAVE_ROS = subprocess.call("type roslaunch", shell=True) == 0
def pytest_runtest_setup(item):
markers = [mark.name for mark in item.iter_markers()]
if "ros" in markers and not HAVE_ROS:
pytest.skip("ROS is not installed.")
|
4853179 | from .base import IamportResponse, BaseApi
class Certifications(BaseApi):
NAMESPACE = "certifications"
class Cards(BaseApi):
NAMESPACE = "cards"
class Banks(BaseApi):
NAMESPACE = "banks"
class Escrows(BaseApi):
NAMESPACE = "escrows"
class Naver(BaseApi):
NAMESPACE = "naver"
class Payco(B... |
4853182 | import shutil
from pathlib import Path
import pytest
import numpy as np
import probeinterface as pi
from spikeinterface.core import ChannelSliceRecording, BinaryRecordingExtractor
def _clean_all():
cache_folder = './my_cache_folder'
if Path(cache_folder).exists():
shutil.rmtree(cache_folder)
def ... |
4853203 | import os
from nvhtop.htop import Htop
from nvhtop.nvidia_smi import NvidiaSmi
from nvhtop.ps import ProcessStatus
from nvhtop.tests import NvHtopTestCase
class TestHtop(NvHtopTestCase):
def setUp(self):
# set environmental variable "FAKE_STDIN_PATH"
os.environ["FAKE_STDIN_PATH"] = str(self.FIXT... |
4853249 | from typing import Any
from boa3.builtin import public
from boa3.builtin.interop.oracle import Oracle
@public
def oracle_call(url: str, request_filter: str, callback: str, user_data: Any):
Oracle.request(url, request_filter, callback, user_data, 'invalid_gas')
|
4853307 | from __future__ import print_function,division
from builtins import range
from six import iteritems
from .controlspace import *
from .interpolators import *
from .objective import ObjectiveFunction
class CostControlSpace(ControlSpace):
"""Adapts a ControlSpace to a state+cost space. Appends accumulated
cost... |
4853385 | from pos_parameters import filename_parameter, value_parameter, \
string_parameter, list_parameter,\
vector_parameter
import pos_wrappers
class preprocess_slice_volume(pos_wrappers.generic_wrapper):
_template = """pos_slice_volume \
-i {input_image... |
4853391 | from __future__ import absolute_import
import zmq
import json
import signal
import sys
from . import applicationclient
def create_socket(port):
"""
Create zmq sub socket.
"""
context = zmq.Context()
socket = context.socket(zmq.SUB)
try:
socket.bind("tcp://*:%s" % port)
except zmq.... |
4853409 | import asyncio
from . import commands, utils
from .connection import Connection
from .messages import build_message, make_privmsgs
class Client(utils.RequiredAttributesMixin):
"""Handle events from Connection and offer methods for sending data."""
connection_class = Connection
required_attributes = ('han... |
4853421 | import numpy as np
a = np.arange(16).reshape(4, 4)
print(a)
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]
# [12 13 14 15]]
print(np.tril(a))
# [[ 0 0 0 0]
# [ 4 5 0 0]
# [ 8 9 10 0]
# [12 13 14 15]]
print(np.tril(a, k=2))
# [[ 0 1 2 0]
# [ 4 5 6 7]
# [ 8 9 10 11]
# [12 13 14 15]]
print(np... |
4853433 | from django.contrib.auth import get_user_model
from django.test import TestCase, Client
from django.urls import reverse
from accounts.models import User
class AccountsViewsTests(TestCase):
def setUp(self):
self.client = Client()
User = get_user_model()
self.user = User.objects.create_user... |
4853439 | import Data.evaluate_Network_on_realData as eN
eN.eval_trainlogfile(logfilepath="./trainphase.log", plot=True)
|
4853457 | import copy
import torch
from torch import nn
from torchdrug import core, layers
from torchdrug.core import Registry as R
@R.register("models.InfoGraph")
class InfoGraph(nn.Module, core.Configurable):
"""
InfoGraph proposed in
`InfoGraph: Unsupervised and Semi-supervised Graph-Level Representation Learn... |
4853505 | import torch.nn as nn
from mmcv.cnn import constant_init, normal_init
from mmdet.models.registry import BACKBONES
from .derive_blocks import derive_blocks
from .operations import Conv1_1, conv_dw
from tools.apis.param_remap import remap_for_paramadapt
@BACKBONES.register_module
class FNA_SSDLite(nn.Module):
ext... |
4853523 | from setuptools import find_packages, setup
from twcli.utils import VERSION
f = open('README.md', 'r')
LONG_DESCRIPTION = f.read()
f.close()
setup(
name='tastyworks-cli',
version=VERSION,
description='An easy-to-use command line interface for Tastyworks!',
long_description=LONG_DESCRIPTION,
long... |
4853548 | import torch.nn as nn
from math import floor
__all__ = ['mobilenet_cifar', 'mobilenet_025_cifar', 'mobilenet_050_cifar', 'mobilenet_075_cifar']
class MobileNet_Cifar(nn.Module):
def __init__(self, channel_multiplier=1.0, min_channels=8):
super(MobileNet_Cifar, self).__init__()
if channel_multipli... |
4853562 | import importlib
import pytest
packages = [
# these are problem libraries that don't always seem to import, mostly due
# to dependencies outside the python world
'netCDF4', 'h5py', 'rasterio', 'geopandas', 'cartopy', 'geoviews',
# these are things we can't live without, just to be safe
'gcsfs', 's... |
4853563 | import torch
from torchvision import utils
import sys
from stylegan2.model import Generator,Discriminator
from tqdm import tqdm
from torch.nn import functional as F
from hparams import hparams as hp
class infer_face():
def __init__(self,weight_path):
self.device = "cuda"
self.weight... |
4853586 | import unittest
from mock import patch
from xsvm.parser import parse_line, load_into_memory
from xsvm.vm import Processor
import xsvm.instructions
class ProcessorTestCase(unittest.TestCase):
def setUp(self):
self.cpu = Processor()
def test_fetch_valid_instruction(self):
load_into_memory(self.... |
4853592 | import os
import re
import tempfile
import json
import abc
from subprocess import Popen, PIPE
from pygments import highlight
from pygments.lexers import CLexer
from pygments.formatters import HtmlFormatter
from pygments.styles.native import NativeStyle
from binaryninja import log
from binaryninja.plugin import Plugin... |
4853610 | import json
from django.http import HttpResponse, HttpResponseForbidden
from django.template.loader import render_to_string
from pattern_library.utils import (
get_pattern_context_var_name,
mark_context_strings_safe,
)
from rest_framework.views import APIView
class RenderPatternView(APIView):
http_metho... |
4853627 | from leapp.actors import Actor
from leapp.models import InstalledRedHatSignedRPM
from leapp.tags import IPUWorkflowTag, ChecksPhaseTag
from leapp.reporting import Report
from leapp.libraries.actor import checkinstalleddebugkernels
class CheckInstalledDebugKernels(Actor):
"""
Inhibit IPU (in-place upgrade) whe... |
4853661 | import logging
from rest_framework import serializers
from helium.planner.models import Course, CourseGroup
from helium.planner.serializers.coursescheduleserializer import CourseScheduleSerializer
__author__ = "<NAME>"
__copyright__ = "Copyright 2019, Helium Edu"
__version__ = "1.4.38"
logger = logging.getLogger(__... |
4853698 | class CorrelationIdNotProvidedException(Exception):
pass
class DjangoStompImproperlyConfigured(Exception):
pass
class DjangoStompIncorrectUse(Exception):
"""
Raised when Django stomp has been invoked in a wrong manner such as
less arguments than it needs, etc.
"""
pass
|
4853706 | import asyncio
import inspect
import json
from dataclasses import dataclass
from typing import Any, AsyncIterator, Awaitable, Dict, Sequence
from gql.subscription import PROTOCOL, MessageType, OperationMessage
from graphql import ExecutionResult, GraphQLError, GraphQLSchema, format_error, parse, subscribe
from starlet... |
4853708 | import os
import pandas as pd
import numpy as np
import time
from torch.utils.data import DataLoader
from pytorch_lightning.callbacks import ModelCheckpoint
from pytorch_lightning import Trainer, seed_everything
from torch_explain.models.explainer import Explainer
from torch_explain.logic.metrics import formula_consis... |
4853723 | from aws_cdk import (
core,
aws_s3 as s3,
aws_s3_deployment as s3deploy,
aws_iam as iam,
aws_ssm as ssm,
aws_lambda as _lambda,
aws_events as events,
aws_events_targets as targets
)
import boto3
import json
import os... |
4853731 | from django.http import HttpResponse
from django.urls import path
from django.views import View
class EmptyCBV(View):
pass
class EmptyCallableView:
def __call__(self, request, *args, **kwargs):
return HttpResponse()
urlpatterns = [
path('missing_as_view', EmptyCBV),
path('has_as_view', Emp... |
4853739 | def Morgan2D(smi,radius=2,nb=1024):
"""
A function to create Morgan ECFP
:param smi: smiles (str)
:param radius: test set split fraction (float)
:param nb: number of bits(int)
Return type: ecfp (binary list)
"""
from rdkit import Chem
from rdkit.Chem import AllChem
mol = Chem.M... |
4853774 | import pandas as pd
import bokeh.plotting as bp
from bokeh.models import HoverTool, ColumnDataSource, Legend
"""
Adapted from
https://stackoverflow.com/a/40231779
"""
tableau20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120),
(44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, ... |
4853810 | class LossHessianStrategy:
EXACT = "exact"
SAMPLING = "sampling"
SUM = "sum"
CHOICES = [
EXACT,
SAMPLING,
SUM,
]
@classmethod
def check_exists(cls, strategy):
if strategy not in cls.CHOICES:
raise AttributeError(
"Unknown loss Hes... |
4853848 | from datetime import timedelta
import numpy as np
from pandas import DatetimeIndex, date_range
import pandas._testing as tm
class TestDatetimeIndexReindex:
def test_reindex_preserves_tz_if_target_is_empty_list_or_array(self):
# GH#7774
index = date_range("2013-01-01", periods=3, tz="US/Eastern")... |
4853855 | import random
from typing import Optional
import numpy as np
import torch
import torch.distributed as dist
from torch import Tensor
def sync_param(input, reduction='mean'):
if isinstance(input, np.ndarray):
sync_input = torch.from_numpy(input).cuda()
elif isinstance(input, torch.Tensor):
sync_... |
4853879 | import numpy as np
import tensorflow as tf
from tensorflow.keras import Model
from tensorflow.keras.layers import Dense
from Key import Key
from machine_learning.PrimitiveDictionaryLayer import PrimitiveDictionaryLayer
from machine_learning.StressToEncodedLayer import StressToEncodedLayer
from machine_learning.loss_... |
4853942 | import re
import pandas as pd
import numpy as np
from datasets.constants import signal_types
from datasets.sources.source_base import SourceBase
import logging
logger = logging.getLogger(__name__)
class EverionSource(SourceBase):
FILES = {
'signals': r'^CsvData_signals_EV-[A-Z0-9-]{14}\.csv$',
'... |
4854035 | CHUNKSIZE = 1 << 26
GETDIR_FLAG_WITHATTR = 0x01
GETDIR_FLAG_ADDTOCACHE = 0x02
# type for readdir command
TYPE_FILE = 'f'
TYPE_SYMLINK = 'l'
TYPE_DIRECTORY = 'd'
TYPE_FIFO = 'q'
TYPE_BLOCKDEV = 'b'
TYPE_CHARDEV = 'c'
TYPE_SOCKET = 's'
TYPE_TRASH = 't'
TYPE_SUSTAINED = 'r'
TYPE_UNKNOWN = '?'
ERROR_MAX = 38
ERROR_LOCKE... |
4854060 | import numpy as np
from PIL import Image, ImageDraw, ImageFont, ImageMath
from pyray.shapes.solid.polyhedron import *
from pyray.axes import *
from pyray.rotation import *
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
##########################################################################... |
4854061 | class NumArray:
def __init__(self, nums: List[int]):
self.size = len(nums)
self.nums = nums
self.sumArray = [0]
for num in nums:
self.sumArray.append(self.sumArray[-1] + num)
def update(self, i: int, val: int) -> None:
oldValue = self.nums[i]
self.nu... |
4854077 | from .matern_kernel import MaternKernel
from .rbf_kernel import RBFKernel
__all__ = ["MaternKernel", "RBFKernel"]
|
4854091 | import cv2
import numpy as np
from procgen import ProcgenEnv
from .utils import ImgProcessor
from .base import BaseEnv
class _Procgen(BaseEnv):
"""Procgen environment.
Args:
name (str): name of environment in Procgen games.
render (bool): parameter that determine whether to render.
g... |
4854120 | from . import input_helpers, matcher, preprocess, siamese_network, syllable_tokenizer
import os
import tarfile
# extract model tarball into directory if doesnt exist
models = ['latin']
for model in models:
model_dir = os.path.join(os.path.dirname(__file__), "models", model)
if not os.path.exists(model_... |
4854132 | import os
import pickle
import time
from typing import Any
import CONSTANT
nesting_level = 0
is_start = None
class Timer:
def __init__(self):
self.start = time.time()
self.history = [self.start]
def check(self, info):
current = time.time()
log(f"[{info}] spend {current - self... |
4854181 | import matplotlib.pyplot as plt
import numpy as np
import sys
if len(sys.argv) < 2:
print("Usage: ")
print(" python {} <log file>".format(sys.argv[0]))
sys.exit()
logfile = sys.argv[1]
steps = []
loss_d = []
loss_g = []
with open(logfile, 'r') as flog:
for line in flog:
line = line.strip(... |
4854188 | from flask_wtf.csrf import CSRFError
from . import app
from flask import render_template
from .search.forms import SearchForm
@app.errorhandler(CSRFError)
def handle_csrf_error(e):
search_form = SearchForm()
return render_template('error.html', title="Session expired", code="401", description="Form session ex... |
4854216 | import typing
import orjson
from django.conf import settings
class PWAManifest:
__slots__ = ('manifest_data',)
default_pwa_manifest = {
"name": settings.PROJECT_GUI_NAME.capitalize(),
"short_name": settings.VST_PROJECT.capitalize(),
"theme_color": "rgb(236,240,245)",
"backgrou... |
4854282 | expected_output = {
"number_of_aggregators": 5,
"interfaces": {
"Port-channel1": {
"name": "Port-channel1",
"bundle_id": 1,
"flags": "SD",
"oper_status": "down"
},
"Port-channel2": {
"name": "Port-channel2",
"bundle_id": 2,
"flags": "SD",
"oper_status": "d... |
4854290 | import itertools
try:
import matplotlib.cm as cm
MATPLOTLIB_AVAILABLE = True
except:
MATPLOTLIB_AVAILABLE = False
def colors_cycle(lightness_factor=1.0, color_shift=0):
"""Returns an iterator over a range of colors"""
if MATPLOTLIB_AVAILABLE:
cycle = itertools.cycle(
[cm.Pair... |
4854323 | def enum(**enums):
"""Enable use of enums by utilizing types"""
return type('Enum', (), enums)
|
4854330 | from submission import Submission
class DavidSubmission(Submission):
def run(self, s):
# :param s: input in string format
# :return: solution flag
# your solution code goes here
distrib = [int(x) for x in s.split()]
n = len(distrib)
seen_distribs = dict()
counter = 0
while tuple(distrib) not in s... |
4854369 | import typing
import mesh_tensorflow as mtf
import tensorflow as tf
from .frontend import block_part_fn
from ..mtf_wrapper import add
from ..utils_core import random_name
from ..utils_mtf import gradient_iterator
tf1 = tf.compat.v1
class RevGradOp(mtf.Operation):
"""Operation to implement custom gradients.
... |
4854405 | class Solution:
def bestCoordinate(self, towers: List[List[int]], radius: int) -> List[int]:
def getNetworkQuality(pointX, pointY):
quality = 0
for x, y, q in towers:
distance = math.dist((x, y), (pointX, pointY))
if distance <= radius:
... |
4854426 | import os
import sys
import numpy as np
import tqdm
from bs4 import BeautifulSoup
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
from Parser_.parser import make_pair_parser
import voc12_class
# standard output format
SPACE = 35
# tqdm parameter
UNIT_SCALE = True
BAR_FORMAT = '{}{}{}'.format('{l_... |
4854431 | from ANN_simulation import *
import datetime, os, argparse
from simtk.openmm.app import *
from simtk.openmm import *
from simtk.unit import *
from sys import stdout
import ast
from config import *
############################ PARAMETERS BEGIN ###############################################################
parser = ar... |
4854459 | import numpy as np
import pyximport
pyximport.install(setup_args={"include_dirs":np.get_include()},build_dir="build", build_in_temp=False)
from align_fill import cython_fill_table
import sys
import torch
sys.path.append("../../../espnet")
from espnet.asr.asr_utils import get_model_conf
import os
from pathlib impo... |
4854485 | from pyradioconfig.calculator_model_framework.interfaces.icalculator import ICalculator
from pycalcmodel.core.variable import ModelVariableFormat, CreateModelVariableEnum
from enum import Enum
class calc_softmodem_sol(ICalculator):
def buildVariables(self, model):
self._addModelVariable(model, 'softmodem_... |
4854490 | from src.data.dataset_readers import * # noqa: F401,F403
from src.data.batchify import data_producer
from src.data.tasks import contextualizer_dir, task_dict
from src.data.utils import learn_vocab
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.