id
stringlengths
3
8
content
stringlengths
100
981k
1759605
from __future__ import print_function import os import sys import json import time import uuid import pstool tcf_stdout = sys.stdout tcf_stderr = sys.stderr _GLOBAL_START_TIME = time.time() _GLOBAL_SOCK = -1 _GLOBAL_STAGE = 0 _GLOBAL_REQUEST_ID = str(uuid.uuid4()) _GLOBAL_FUNCTION_NAME = os.environ.get('SCF_FUNCTION...
1759615
import json from collections import defaultdict from pathlib import Path import argparse from vist_tokenizer import VistTokenizer def parse_args(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-n', '--name', default='test_results.json', type=str) parser.add_argument('-l', '-...
1759670
from rest_framework import serializers from testapp.models import RoomBookingText, RoomBookingQ class RoomBookingTextSerializer(serializers.ModelSerializer): """Always fails with ImproperlyConfigured error, because mixin cannot be used with text-based conditions.""" class Meta: model = RoomBookingTex...
1759680
import copy import torch import torch_fidelity import torch.nn.functional as F from tqdm import tqdm from .data_utils import get_data_loaders, BigDataset, NoClassDataset, get_datasets from .log_utils import load_model, load_stats, log, save_images def normalize(in_channels): return torch.nn.GroupNorm(num_groups=3...
1759690
import pytest import uvicore from uvicore.support.dumper import dump # DB ORM @pytest.mark.asyncio async def test_single(app1): # Single where from app1.models.post import Post posts = await Post.query().where('creator_id', 2).get() assert [3, 4, 5] == [x.id for x in posts] @pytest.mark.asyncio asyn...
1759699
import json, os, inspect, shutil from phi.fluidformat import * class ControlScene: def __init__(self, path, mode="r", index=None): self.path = path self.index = index if mode.lower() == "r": with open(os.path.join(path, "description.json"), "r") as file: self.i...
1759717
from django.conf.urls.defaults import * from django.conf import settings urlpatterns = patterns('rpg.views', ('^$', 'main'), ('^a/message/new$', 'message_new'), ('^a/room/updates$', 'room_updates'), ('^a/player/new$', 'player_new'), ('^a/player/update_position$', 'player_update_position'), ('^a...
1759722
from immudb.grpc import schema_pb2 from pprint import pformat def py_to_sqlvalue(value): sqlValue = None typ = type(value) if value is None: sqlValue = schema_pb2.SQLValue(null=True) elif typ is int: sqlValue = schema_pb2.SQLValue(n=value) elif typ is bool: sqlValue = schem...
1759733
import datetime from mooquant import plotter, strategy from mooquant.feed import csvfeed from mooquant.tools import quandl class MyStrategy(strategy.BacktestingStrategy): def __init__(self, feed, quandlFeed, instrument): strategy.BacktestingStrategy.__init__(self, feed) self.setUseAdjustedValues(...
1759804
import numpy as np import scipy as sp import scipy.spatial import scipy.signal import numexpr as ne import warnings import os from ...misc.basic_functions import rowsum, differentiation_matrix, differentiate from ...kernels.high_level.laplace import Laplace_Layer_Form, Laplace_Layer_Apply from ...kernels.high_level.ca...
1759807
from downloader import Downloader cookie = """ ADD YOUR COOKIE HERE """ dl = Downloader(cookie=cookie) # download by class URL: dl.download_course_by_url('https://www.skillshare.com/classes/Art-Fundamentals-in-One-Hour/189505397') # or by class ID: # dl.download_course_by_class_id(189505397)
1759809
import math import numpy as np import basis.robot_math as rm import modeling.mesh_tools as mt if __name__ == '__main__': ''' author: weiwei date: 20201207osaka ''' mt.convert_to_stl("block.stl", "block.stl", scale_ratio=np.ones(3)*.001)
1759814
import keras.backend as K import numpy as np from keras.engine.topology import InputSpec, Layer from keras.layers import (Activation, Concatenate, Conv2D, Flatten, Input, Reshape) from keras.models import Model from nets.mobilenet import mobilenet def SSD300(input_shape, num_classes...
1759833
from django.shortcuts import render from django.http import HttpResponse from .models import Student, Log from django.shortcuts import redirect import datetime global stat stat = '' # Create your views here. global selected selected = None def index1(request): logf = [] logs = Log.objects.all() for log in logs: ...
1759854
import _plotly_utils.basevalidators class MeanlineValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__(self, plotly_name="meanline", parent_name="violin", **kwargs): super(MeanlineValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, ...
1759877
import pandas as pd COUNTRIES = { "belgium": "B", "england": "E", "france": "F", "germany": "D", "greece": "G", "italy": "I", "portugal": "P", "scotland": "SC", "spain": "SP", "turkey": "T", } def list_countries(): """ Lists all the countries currently available ""...
1759885
import pytest import nltk nltk.download("wordnet") from nltk.corpus import wordnet as wn from lucid.modelzoo.wordnet import ( id_from_synset, synset_from_id, imagenet_synset_ids, imagenet_synsets, imagenet_synset_from_description, ) @pytest.fixture() def synset(): return wn.synset("great_wh...
1759901
import unittest # function spelling mistake is from CodeWars from katas.beta.binary_pyramid_101 import binary_piramid class BinaryPyramidTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(binary_piramid(1, 4), '1111010') def test_equals_2(self): self.assertEqual(binary_pira...
1759967
from features.git_commit_features import GitCommitFeatures from copy import deepcopy from git_analysis.analyze_git_logs import retrieve_git_logs from object.features import HistoryFeatures as HistoryFeaturesObj class HistoryFeatures(GitCommitFeatures): def __init__(self, rgcm): super(HistoryFeatures, self...
1759979
from setuptools import setup, find_packages from setuptools.command.install import install import os from lyrics import __version__, CONFIG_PATH this_directory = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(this_directory, 'README.md'), encoding='utf-8') as f: long_description = f.read() c...
1760006
from os.path import dirname from pathlib import Path import pandas as pd from pandas_datareader import DataReader from ._utils import fill_and_cut module_path = Path(dirname(__file__)) def fetch_usstocks( begin_date="2000-01-01", end_date="2019-12-31", n_assets=10, column="Adj Close", verbose=T...
1760007
from django.apps import AppConfig class FishingEquipmentConfig(AppConfig): name = 'lee_fishing.fishing_equipment' verbose_name = 'Fishing Equipment'
1760008
from prometheus_client.parser import text_string_to_metric_families for family in text_string_to_metric_families(u"counter_total 1.0\n"): for sample in family.samples: print("Name: {0} Labels: {1} Value: {2}".format(*sample))
1760036
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import math from functools import partial import time __all__ = ['ResNeXt', 'resnet50', 'resnet101'] def conv3x3x3(in_planes, out_planes, stride=1): # 3x3x3 convolution with padding return nn.Conv3d( ...
1760056
import base64 import os from pathlib import PurePath from typing import Union from django.core.files import File from esteid.types import PredictableDict class DataFile: """ Interface for file objects that are added to signed containers. Constructor accepts a path to file (a string or a pathlib *Path) ...
1760077
from copy import deepcopy from multiprocessing import cpu_count from typing import List, NamedTuple from mcp.config.dataloader import DataLoaderConfig from mcp.config.dataloader import parse as parse_dataloader from mcp.config.dataset import DatasetConfig from mcp.config.dataset import parse as parse_dataset from mcp....
1760078
from typing import Any from typing import Dict from typing import List from typing import Tuple from typing import Union import numpy as np import pandas as pd from sid.config import DTYPE_VIRUS_STRAIN def prepare_virus_strain_factors( virus_strains: Dict[str, List[str]], params: pd.DataFrame ) -> Dict[str, Unio...
1760095
from typing import List from topyn.commands import run_command, get_config, get_topyn_excludes def _extra_args(fix: bool, module: str) -> List[str]: excludes = "|".join( [ exclude if exclude[0] != "." else f"\\{exclude}" for exclude in get_topyn_excludes() ] ) conf...
1760134
from __future__ import print_function import logging import os import random import numpy as np from tqdm import tqdm, trange from transformers_config import * import torch from torch.utils.data import DataLoader, RandomSampler ## Optimization from transformers import ( WEIGHTS_NAME, AdamW, get_linear_s...
1760142
import pytest from pathlib import Path from pythonfmu.csvbuilder import CsvFmuBuilder EPS = 1e-7 def test_csvslave(tmp_path): fmpy = pytest.importorskip( "fmpy", reason="fmpy is not available for testing the produced FMU" ) csv_file = Path(__file__).parent / "data/csvdemo.csv" fmu = CsvFmu...
1760143
from xmind.tests import logging_configuration as lc from xmind.core.position import PositionElement from xmind.tests import base from unittest.mock import patch from xmind.core.const import TAG_POSITION, ATTR_X, ATTR_Y class TestPositionElement(base.Base): """Test class for PositionElement class""" def getLo...
1760155
import math import argparse import time from pathlib import Path from distutils.util import strtobool import numpy as np import pandas as pd pd.set_option("display.max_colwidth", 200) pd.set_option("display.max_columns", 1000) pd.set_option("display.width", 1000) from tqdm import tqdm from pyquaternion import Quatern...
1760160
import random from smd import config import numpy as np def block_mixing_audio(audio1, audio2, overlap=None): n1 = len(audio1) n2 = len(audio2) b1 = int(config.BLOCK_MIXING_MIN * min(n1, n2)) b2 = int(config.BLOCK_MIXING_MAX * min(n1, n2)) if overlap is None: overlap = random.randint(b1,...
1760161
from __future__ import absolute_import import numpy as np import itertools import operator import random import sys import copy from benchmark.plotting.eval_range_search import compute_AP from benchmark.sensors.power_capture import power_capture def compute_recall_without_distance_ties(true_ids, run_ids, count): ...
1760162
import asyncio import pathlib import aiohttpdemo_polls.db as db import psycopg2 from faker import Factory from aiohttpdemo_polls.utils import init_postgres from sqlalchemy.schema import CreateTable, DropTable PROJ_ROOT = pathlib.Path(__file__).parent.parent conf = {"host": "127.0.0.1", "port": 8080, ...
1760167
from .dialogs import ( button_dialog, checkboxlist_dialog, input_dialog, message_dialog, progress_dialog, radiolist_dialog, yes_no_dialog, ) from .progress_bar import ProgressBar from .prompt import ( CompleteStyle, PromptSession, confirm, create_confirm_session, prompt, ...
1760237
from torch.utils.data import Dataset import numpy as np import io from PIL import Image import os import json import random from image_synthesis.utils.misc import instantiate_from_config def load_img(filepath): img = Image.open(filepath).convert('RGB') return img class CocoDataset(Dataset): def __init__(s...
1760262
from gym.envs.registration import register register( id='DartCartPole-v0', entry_point='gym_dart.envs:DartCartPoleEnv', ) register( id='DartParticle-v0', entry_point='gym_dart.envs:DartParticleEnv', ) register( id='DartReacher-v0', entry_point='gym_dart.envs:DartReacherEnv', )
1760263
from pandac.PandaModules import * from direct.interval.IntervalGlobal import * from direct.particles import ParticleEffect from direct.particles import Particles from EffectController import EffectController from PooledEffect import PooledEffect from otp.otpbase import OTPRender from pirates.audio import SoundGlobals f...
1760274
import argparse from relex.evaluation import semeval2010_task8_evaluation from relex.evaluation import tacred_evaluation def _get_parser(): parser = argparse.ArgumentParser(description="Run evaluation") parser.add_argument( "--model-dir", type=str, required=True, help="directo...
1760333
import concurrent.futures import urllib.request import time def benchmark_url(url): begin = time.time() with urllib.request.urlopen(url) as conn: conn.read() return (time.time() - begin, url) class UrlsBenchmarker(object): def __init__(self, urls): self._urls = urls def run(self, ...
1760364
import sys from math import sqrt import numpy as np import pandas as pd from sklearn.preprocessing import LabelEncoder, OneHotEncoder from sklearn.cross_validation import KFold from sklearn import ensemble from sklearn import linear_model as lm from sklearn.metrics import mean_squared_error as mse import xgboost as xgb...
1760430
import os import sys # add project dir to path BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(BASE_DIR) from absl import flags from absl import app import numpy as np from pprint import pprint from meta_learn.util import get_logger from experiments.util import * from experiment...
1760435
import sys from typing import List import math from delphi.translators.for2py.format import * from delphi.translators.for2py.arrays import * from dataclasses import dataclass from delphi.translators.for2py.types_ext import Float32 import delphi.translators.for2py.math_ext as math from numbers import Real def do_while...
1760466
import onnx from onnx import helper from onnx import AttributeProto, TensorProto, GraphProto, OperatorSetIdProto from onnx import numpy_helper import numpy as np vocab_size=256 #30258 X = helper.make_tensor_value_info('input', TensorProto.FLOAT, ["batch", "seqlen", 128]) unsqueezed_masked_lm_positions = helper.make_t...
1760484
class Solution: def validMountainArray(self, A: List[int]) -> bool: flag = False i, n = 1, len(A) while i < n - 1 and A[i - 1] < A[i] < A[i + 1]: i += 1 if i < n - 1 and A[i - 1] < A[i] > A[i + 1]: i += 1 flag = True while i < n - 1 and A[i...
1760493
import json import os import time import rabbitpy from channelpy.exceptions import ChannelTimeoutException from codes import BUSY, ERROR, SPAWNER_SETUP, PULLING_IMAGE, CREATING_CONTAINER, UPDATING_STORE, READY, \ REQUESTED, SHUTDOWN_REQUESTED, SHUTTING_DOWN from config import Config from docker_utils import Dock...
1760524
import logging import common import argparse import uuid import emission.core.wrapper.user as ecwu if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) parser = argparse.ArgumentParser(prog="purge_user") group = parser.add_mutually_exclusive_group(required=True) group.add_argument("-e",...
1760533
import enum import numpy import scipy import time from AIToolbox import MDP, POMDP from matplotlib import pyplot as plt from matplotlib.lines import Line2D from sklearn.metrics import roc_curve, auc class Action(enum.Enum): ANALIZE = 0 BLOCK = 1 PASS = 2 class Observe(enum.Enum): OK = 0 ...
1760551
from microbit import display, button_a import time NUMBERS = list(range(9, 0, -1)) def countdown(): for i in NUMBERS: display.show(i) time.sleep(1) display.clear() while True: if button_a.is_pressed(): countdown()
1760563
import cdutil import warnings import vtk from vtk.util import numpy_support as VN import vcs from . import vcs2vtk import numpy import math import os import traceback import sys import cdms2 import cdtime import inspect import json import subprocess import tempfile import shutil from . import VTKAnimate from . import v...
1760583
import cv2, threading, queue class ThreadingClass: # initiate threading class def __init__(self, name): self.cap = cv2.VideoCapture(name) # define an empty queue and thread self.q = queue.Queue() t = threading.Thread(target=self._reader) t.daemon = True t.start() # read the frames as soon a...
1760619
from typing import Generator import pytest from sqlalchemy.engine import Engine from sqlalchemy.orm import sessionmaker, Session from sqlalchemy.ext.declarative import DeclarativeMeta, declarative_base @pytest.fixture() def sa_base() -> DeclarativeMeta: return declarative_base() @pytest.fixture() def session(s...
1760647
from django.contrib.gis.geos import Point from data_importers.management.commands import BaseXpressDemocracyClubCsvImporter class Command(BaseXpressDemocracyClubCsvImporter): council_id = "DAL" addresses_name = "2021-03-19T13:08:53.439791/darlington.gov.uk-1616156390000-.tsv" stations_name = "2021-03-19T1...
1760688
import os from setuptools import setup, find_packages import config setup( name="scroller", version=config.version, author="<NAME>", author_email="<EMAIL>", description=config.description, license="MIT", py_modules=["scroller", "config"], keywords="animation utility scrolling text term...
1760695
import os import numpy as np from .base_data import Dataset, Sequence from ..utils import read_file from ..builder import BENCHMARKS @BENCHMARKS.register_module class VOT(Dataset): def __init__(self, name='vot', vot_root='data/benchmark/vot17/', zip_mode=False)...
1760712
from KratosDEMApplication import * from KratosMultiphysics import _ImportApplication application = KratosDEMApplication() application_name = "KratosDEMApplication" _ImportApplication(application, application_name)
1760762
from unittest import TestCase import numpy as np from keras_bert.backend import keras from keras_bert.layers import MaskedGlobalMaxPool1D class TestPooling(TestCase): def test_masked_global_max_pool_1d_predict(self): input_layer = keras.layers.Input(shape=(None,)) embed_layer = keras.layers.Embed...
1760809
from setuptools import setup, find_packages install_requires = [ 'torch>=1.9.0', 'torchvision>=0.10.0', 'tqdm' ] setup( name='anatome', version='0.0.3', description='Ἀνατομή is a PyTorch library to analyze representation of neural networks', author='<NAME>', author_email='<EMAIL>', ...
1760819
from __future__ import annotations from typing import List import numpy as np from nncg.allocation import Allocation from nncg.nodes.expressions import Variable from nncg.nodes.misc import Node from nncg.writer import Writer class CHeaderNode(Node): """ Class for writing everything in a C file that is above t...
1760849
import pdb import torch import numpy as np import torch.optim as optim class Optimizer(object): def __init__(self, model, optim_dict): self.optim_dict = optim_dict if self.optim_dict["optimizer"] == 'SGD': self.optimizer = optim.SGD( model, lr=self.optim...
1760887
from __future__ import print_function from __future__ import unicode_literals from __future__ import absolute_import from __future__ import division from random import normalvariate from random import shuffle from random import uniform from random import seed import matplotlib.pyplot as plt import matplotlib.patches a...
1760914
from PyPDF2 import PdfFileWriter, PdfFileReader import io import os from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import letter from reportlab.pdfbase.ttfonts import TTFont from reportlab.pdfbase import pdfmetrics from server.utils.misctools import get_pardir path = get_pardir(os.path.abspath(__file...
1760935
import unittest from reamber.algorithms.generate.sv.generators.svNormalizeBpm import sv_normalize_bpm from reamber.base.lists.BpmList import BpmList, Bpm class TestNormalize(unittest.TestCase): def testNormalize(self): seq = sv_normalize_bpm(BpmList([Bpm(0, 200), Bpm(100, 50), Bpm(300, 100)]), 100) ...
1760936
from discord.ext import commands import inspect class source(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command() async def source(self, ctx, *, command: str): """shows source code of a command Parameters • command - the name of the command ""...
1761006
import sys sys.path.append('src') import numpy as np from objmodel import * from ParticleGenerator import * def printUsageInstructions(): print "\n\nUsage: gen_initial_conditions.py filepath static" print "\tfilepath: the path to a triangulated obj model, whose vertices all lie within a 1.0 width cube centered at ...
1761048
import time from typing import List, Optional from quarkchain.cluster.shard_db_operator import ShardDbOperator from quarkchain.core import Address, Log, MinorBlock, MinorBlockHeader from quarkchain.evm.bloom import bloom from quarkchain.utils import Logger class LogFilter: """ Filter class for logs, blocks, ...
1761050
class Solution: def sequenceReconstruction(self, org, seqs): order, orders, graph, seen = collections.defaultdict(int), set(), collections.defaultdict(set), set() for seq in seqs: for i in range(len(seq)): if i > 0: if seq[i] == seq[i - 1]: return Fals...
1761062
from testplan.testing.multitest import testsuite, testcase # Need to import from project root so that dependency # is discoverable from interactive code reloader. from my_tests.dependency import VALUE @testsuite class BasicSuite(object): @testcase(parameters=range(2)) def basic_case(self, env, result, arg): ...
1761063
import pytest from stock_indicators import indicators class TestAlligator: def test_standard(self, quotes): results = indicators.get_alligator(quotes) # proper quantities # should always be the same number of results as there is quotes assert 502 == len(results) assert 482 ...
1761080
import unittest from setup.settings import * from numpy.testing import * import numpy as np import dolphindb_numpy as dnp import pandas as pd import orca class ArrayAttributesTest(unittest.TestCase): @classmethod def setUpClass(cls): # connect to a DolphinDB server orca.connect(HOST, PORT, "a...
1761085
import torch import random from deepspeed.runtime.csr_tensor import CSRTensor def test_csr_addition_self(): row_count = 10 random.seed(1234) x = torch.ones(1, 5) for i in range(row_count - 1): if random.random() > 0.75: x = torch.cat([x, torch.ones(1, 5)]) else: ...
1761091
import allel from collections import Counter, OrderedDict import matplotlib.pyplot as plt from matplotlib.pyplot import figure import numpy as np from operator import itemgetter import os import pandas as pd import random import sys from Admixture.utils import * from Admixture.simulation import simulate def read_samp...
1761100
import logging import os import sys import numpy as np import argparse from tempfile import TemporaryDirectory import matplotlib.pyplot as plt import matplotlib # matplotlib.use("TkAgg") # use in pycharm to avoid scientific mode plot? from tqdm import tqdm from v2e import desktop from v2e.emulator import EventEmulato...
1761148
import datetime as dt import os import sys import subprocess from argparse import ArgumentParser from timeflow import stats as statistics from timeflow import utils def log(args): utils.write_to_log_file(args.message) def _call_editor(editor, filename): editor = editor.split() subprocess.call(editor +...
1761169
import fwsynthesizer from fwsynthesizer.parsers import parse_pf frontend = fwsynthesizer.Frontend( name="PF", diagram="diagrams/pf.diagram", language_converter=fwsynthesizer.converter( parser=parse_pf.conf_file.parse_strict, converter=parse_pf.convert_rules ), query_configuration=fw...
1761177
import glob import json import logging import os import re import sys from datetime import datetime, timezone from os.path import basename as pbase from os.path import join as pjoin from os.path import splitext as psplit import pytz import requests from discord_webhook import DiscordEmbed, DiscordWebhook """ A tools ...
1761255
from tests.util import match_object_snapshot from tests.analyzer.util import analyze input = """ fieldset: entry = value entry = value entry = value entry = value entry = value entry = value """.strip() def test_field_analysis(): analysis = analyze(input) assert match_object_snapshot(...
1761273
from .DM import * class DMConstant(DM): def __init__(self, constant_size, constant_read, constant_write): super().__init__() self.constant_size = constant_size self.constant_read = constant_read self.constant_write = constant_write def disk(self): return self.constant_size, self.constant_read, self.consta...
1761284
SENSOR_IDS = '../METRLA/metr_ids.txt' DISTANCES = '../METRLA/distances_la_2012.csv' WEEK = 2 DAY = 1 HOUR = 2
1761377
from unittest.mock import patch from django.test import TestCase from ..forms import NewJobForm from libya_elections.constants import CENTER_ID_LENGTH class NewJobFormTestCase(TestCase): def test_simple_case_ok(self): """test simple positive case of form submission""" data = { 'name'...
1761396
from django_filters.filterset import FilterSet from ..search.filter import SearchFilter from .models import DocumentType, Letter, ReferenceNumber from .searchset import DocumentTypeSearchSet, LetterSearchSet, ReferenceNumberSearchSet class DocumentTypeFilterSet(FilterSet): query = SearchFilter(searchset=Document...
1761440
from datetime import datetime import pytest from hypothesis import assume, given from hypothesis_jsonschema import from_schema from jigu.core.sdk.timestamp import Timestamp from testtools import assert_serdes_consistent, assert_serdes_exact @pytest.mark.sdk class TestTimestampSerdes: # TODO: write better regex...
1761451
import numpy as np import os from skimage.io import imread from skimage.transform import resize from skimage import color from cyvlfeat.hog import hog from non_max_supr_bbox import non_max_supr_bbox def run_detector(test_scn_path, model, feature_params, threshold=0.5, step_size=3, downsample=0.9): """ FUNC: T...
1761453
from veripy.parser.syntax import * from veripy.typecheck.types import * from veripy.built_ins import FUNCTIONS from veripy.log import log def type_check_stmt(sigma : dict, func_sigma : dict, stmt : Stmt): if isinstance(stmt, Skip): return sigma if isinstance(stmt, Seq): return type_che...
1761464
import os import os.path as osp from tqdm import tqdm from pathlib import Path from collections import defaultdict import numpy as np from pyquaternion import Quaternion from scipy.spatial.transform import Rotation as R from nuscenes.nuscenes import NuScenes from nuscenes.utils import splits from nuscenes.utils.geome...
1761486
from rsqueakvm.model.base import W_AbstractObjectWithIdentityHash from rsqueakvm.model.compiled_methods import ( W_PreSpurCompiledMethod, W_SpurCompiledMethod) from rsqueakvm.model.pointers import W_PointersObject from rsqueakvm.primitives.constants import EXTERNAL_CALL from rsqueakvm.storage_classes import Abstrac...
1761517
import FWCore.ParameterSet.Config as cms from DQMServices.Core.DQMEDHarvester import DQMEDHarvester segmentTest = DQMEDHarvester("DTSegmentAnalysisTest", detailedAnalysis = cms.untracked.bool(False), #Perform basic diagnostic in endLumi/EndRun ...
1761546
import ROOT as r f = r.TFile("tree_cycles_hist.root", "recreate") t = r.TTree("Events", "") obj = r.vector("float")() t.Branch("Jet_pt", obj) rows = [[], [27.324586868286133, 24.88954734802246, 20.853023529052734], [], [20.330659866333008], [], []] for i,row in enumerate(rows): obj.clear() for x in row: ...
1761582
from typing import List, Union import pandas from pandas.core.series import Series from ..model.node_classification_model import NCModel from ..pipeline.classification_training_pipeline import ClassificationTrainingPipeline from ..query_runner.query_runner import QueryRunner class NCTrainingPipeline(ClassificationT...
1761606
def count_occurence(list, key): count = 0 for item in list: if item == key: count = count + 1 return count my_list = [8, 88, -6, 21, 10, 36, 12, 88, 0, 88] sorted_list = sorted(my_list) number_of_occurences = count_occurence(sorted_list, 88) print("88 occurs in " + str(sorted_list) + ":...
1761631
from runners.python import Submission from collections import defaultdict import pprint class AyoubSubmission(Submission): def run(self, s): lines = s.split('\n') actions = {} pause = int(lines[1].split()[5]) for i in range(2, len(lines), 10): desc = lines[i:i+10] ...
1761648
import time import mxnet as mx import numpy as np import mobula from mobula.testing import assert_almost_equal, gradcheck import unittest mobula.op.load('Softmax') T = np.float32 atol = 2e-3 rtol = 2e-3 def test_softmax1d(): N = 20 data = mx.random.uniform(0, 1, shape=(N, )) out = mobula.op.Softmax(data...
1761663
from ned_base import NEDBase import re import os.path TOPOBATHY_PATTERN = re.compile('^ned19_' \ '([ns])([0-9]{2})x([0257][05])_' \ '([ew])([0-9]{3})x([0257][05])_' \ '[a-z]{2}_[a-z]+_topobathy_20[0-9]{2}.' \ ...
1761673
import platform import socket import struct from tornado import gen from microproxy.layer.base import ProxyLayer class TransparentLayer(ProxyLayer): SO_ORIGINAL_DST = 80 def __init__(self, context, dest_addr_resolver=None, **kwargs): super(TransparentLayer, self).__init__(context, **kwargs) ...
1761695
from __future__ import print_function import sys import numpy as np def main(argv): np.random.seed(2) numPoints = 1001 xs = np.linspace(-5, 5, numPoints) probs = generateData(numPoints) convProbs = convolveProbs(probs) print(np.sum(convProbs)) plt.imshow(convProbs, interpolation = 'none') plt.sh...
1761696
from .abc import ABCLabeler from .base import BaseLabeler from .bot import BotLabeler from .user import UserLabeler __all__ = ("ABCLabeler", "BaseLabeler", "BotLabeler", "UserLabeler")
1761705
from tests.integration import int_test example = """ from __future__ import annotations from typing import List x: List """ expected = """ from __future__ import annotations x: list """ def test_no_duplicate_futures_annotations(): """ Originally forgot to check for existing futures imports before adding ...
1761736
import sys from kubernetes import watch # This function returns the kubernetes secret object present in a given namespace def get_kubernetes_secret(api_instance, namespace, secret_name): try: return api_instance.read_namespaced_secret(secret_name, namespace) except Exception as e: sys.exit("E...
1761776
import argparse # Parameters parser = argparse.ArgumentParser(description='Catcher') parser.add_argument('--grid', dest='grid', type=int, default=11, help='Game grid size.') parser.add_argument('--hidden', dest='hidden', type=int, default=100, help='Number of neuron in the hidden layer.') parser.add_argument('--memory...