id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
453271 | from __future__ import print_function
from math import ceil
try:
xrange # Python 2
except NameError:
xrange = range # Python 3
def diagonal_sum(n):
total = 1
for i in xrange(1, int(ceil(n / 2.0))):
odd = 2 * i + 1
even = 2 * i
total = total + 4 * odd ** 2 - 6 * even
re... |
453313 | from pathlib import Path # pylint: disable=unused-import
from os.path import expanduser # pylint: disable=unused-import
import pytest
from .context import load_tweet_sentiment_train, CLASS_VALUES
@pytest.mark.skipif('not Path(expanduser("~/.sadedegel_data/tweet_sentiment")).exists()')
def test_data_load():
da... |
453348 | self.description = 'download a remote package with -U'
self.require_capability("curl")
url = self.add_simple_http_server({})
self.args = '-Uw {url}/foo.pkg'.format(url=url)
self.addrule('!PACMAN_RETCODE=0')
self.addrule('!CACHE_FEXISTS=foo.pkg')
self.addrule('!CACHE_FEXISTS=foo.pkg.sig')
|
453351 | from datetime import datetime
from couchdbkit.ext.django.schema import Document, StringProperty, \
DateTimeProperty
class Post(Document):
author = StringProperty()
title = StringProperty()
content = StringProperty()
date = DateTimeProperty(default=datetime.utcnow)
class Comment(Document):
au... |
453381 | import doctest
import sys
if sys.version_info >= (3,):
def load_tests(loader, tests, ignore):
return doctest.DocFileSuite('../README.rst')
|
453401 | from dolfin import *
from xii import *
from block import block_bc
def setup_problem(radius, mesh_gen):
'''
This is 3d-1d system inspired by https://arxiv.org/abs/1803.04896
There is a Robin forcing f on the entire 3d bdry and g 1d bdry.
No multiplier.
'''
# FIXME: Dirichlet bcs
mesh3... |
453420 | import ocean
for dtype in [ocean.int16, ocean.float, ocean.chalf] :
a = ocean.tensor([],dtype,ocean.gpu[0])
a.fill(24)
print(a)
a.fill(36)
print(a)
|
453424 | import requests
import json
#Archive-It creds
aitAccount = ""
aitUser = ""
aitPassword = ""
#setup Archive-It auth session
aitSession = requests.Session()
if len(aitUser) > 0 and len(aitUser) > 0 and len(aitUser) > 0:
aitSession.auth = (str(aitUser), str(aitPassword))
# URL to request
requestURL = "https://partner... |
453442 | import collections
import numpy as np
import tensorflow as tf
import tensorflow_federated as tff
from federated.utils.rfa import create_rfa_averaging
class RFATest(tf.test.TestCase):
"""Class for testing RFA."""
def get_test_data(self) -> tf.data.Dataset:
"""Creates data for RFA tests.
Retu... |
453474 | import pandas as pd
import matplotlib.pyplot as plt
from patsy import dmatrices
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
# part 1
print("part 1")
fname = "https://archive.ics.uci.edu/ml/machine-learning-databases/abalone/abalone.data"
fname = "../abalone.da... |
453480 | import os
import sys
import requests
import logging
from splunklib.modularinput import *
def do_work(input_name, ew, path):
filepath = os.path.join(os.environ['SPLUNK_HOME'], 'etc', 'apps', 'SplunkForPCAP', 'bin', 'InputHistory.log')
directory = os.path.dirname(filepath)
if not os.path.exists(directory):... |
453495 | import os
import sys
import functools
import operator
import weakref
import inspect
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
if PY3:
string_types = (str,)
else:
string_types = (basestring,)
def with_metaclass(meta, *bases):
"""Create a base class with a metaclass."""
return meta... |
453506 | from __future__ import absolute_import, division, print_function, unicode_literals
import six
import logging
import os
import stat
from subprocess import Popen, PIPE
import io
import numpy as np
import shutil
from contextlib import contextmanager
import gzip
logger = logging.getLogger(__name__)
initialized = False
... |
453549 | import unittest
from config import Config as cfg
import requests
namespace = '/camera'
class Camera(unittest.TestCase):
routeUrl = cfg.serverUrl + "/camera"
camerasList = [1, 2, 3]
def getAllImagesFromCamera(self):
for camera in self.camerasList:
r = requests.get(f'{camera}/images')... |
453584 | import os
import sys
import ast
import random
import argparse
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.distributed as dist
from torch.utils.data import DataLoader
from torch.utils.data.distributed import DistributedSampler
from tens... |
453591 | from collections import namedtuple
from typing import Any, Text, Iterable, List, Dict
from onnx import AttributeProto, numpy_helper
import numpy as np
__author__ = "<NAME>, <NAME> (University of Tuebingen, Chair for Embedded Systems)"
def _convertAttributeProto(onnx_arg):
"""
Convert an ONNX AttributeProto i... |
453615 | def simple_linear_regression_traditional(x, y):
"Traditional linear regression with B0 intercept, B1 slope"
import numpy as np
x = np.array(x); y = np.array(y)
mean_x = np.mean(x)
mean_y = np.mean(y)
err_x = x - mean_x
err_y = y - mean_y
err_mult = err_x * err_y
numerator = np.sum(err_mult)
err_x_sq... |
453627 | import pytest
from model_mommy import mommy
from rest_framework import status
@pytest.fixture
def awards_transaction_data(db):
mommy.make(
"awards.Award",
id=1,
generated_unique_award_id="CONT_AWD_zzz_whatever",
piid="zzz",
fain="abc123",
type="B",
total_obl... |
453643 | import contextlib
from typing import Optional
import click
from click import Context
from valohai_yaml.objs import Config, Pipeline
from valohai_cli.api import request
from valohai_cli.commands.pipeline.run.utils import build_edges, build_nodes, match_pipeline
from valohai_cli.ctx import get_project
from valohai_cli.... |
453644 | import numpy as np
def linear(t):
return t
def in_quad(t):
return t * t
def out_quad(t):
return -t * (t - 2)
def in_out_quad(t):
u = 2 * t - 1
a = 2 * t * t
b = -0.5 * (u * (u - 2) - 1)
return np.where(t < 0.5, a, b)
def in_cubic(t):
return t * t * t
def out_cubic(t):
u = t - 1... |
453653 | class Eigenstates:
def __init__(self, energies, array, extent, N, type):
"""Info about the eigenstates"""
self.energies = energies
self.array = array
self.number = len(array)
self.extent = extent
self.N = N
self.type = type
|
453672 | from django.db import models
class OpenBasketManager(models.Manager):
"""For searching/creating OPEN baskets only."""
status_filter = "Open"
def get_queryset(self):
return super().get_queryset().filter(
status=self.status_filter)
def get_or_create(self, **kwargs):
return ... |
453715 | from .fhirbase import fhirbase
class ClaimResponse(fhirbase):
"""
This resource provides the adjudication details from the processing of
a Claim resource.
Args:
resourceType: This is a ClaimResponse resource
identifier: The Response business identifier.
status: The status of t... |
453745 | import asyncio
import enum
import random
import time
import idom
class GameState(enum.Enum):
init = 0
lost = 1
won = 2
play = 3
@idom.component
def GameView():
game_state, set_game_state = idom.hooks.use_state(GameState.init)
if game_state == GameState.play:
return GameLoop(grid_si... |
453766 | from quom.tokenizer.iterator import RawIterator, LineWrapIterator, Span
def check_iterator(it, res):
crr = '\0'
for c in res:
prv = crr
crr = c
assert it.prev == prv
assert it.curr == crr
it.next()
assert it.next() is False
def test_raw_iterator():
it = Ra... |
453784 | import glob
import numpy as np
import os
import scipy.io as scio
import torch
from torch.utils.data import Dataset
class trainset_loader(Dataset):
def __init__(self, root, dose):
self.file_path = 'input_' + dose
self.files_A = sorted(glob.glob(os.path.join(root, 'train', self.file_path, 'data') + '... |
453827 | import inspect
from typing import List, Set, Mapping, Dict
import pytest
from guniflask.data_model.typing import parse_json, analyze_arg_type, inspect_args
class Person:
name: str
age: int
class Teacher(Person):
classes: Set
class Student(Person):
secret: str
mentor: Teacher
parents: Lis... |
453917 | import os.path as osp
import sys
import numpy as np
import torch
from torch.autograd import gradcheck
sys.path.append(osp.abspath(osp.join(__file__, '../../')))
from roi_align import RoIAlign # noqa: E402, isort:skip
feat_size = 15
spatial_scale = 1.0 / 8
img_size = feat_size / spatial_scale
num_imgs = 2
num_rois =... |
453983 | from aiohttp_requests import requests
from aioresponses import aioresponses
async def test_aiohttp_requests():
test_url = 'http://dummy-url'
test_payload = {'hello': 'world'}
with aioresponses() as mocked:
mocked.get(test_url, payload=test_payload)
response = await requests.get(test_url)... |
453995 | from __future__ import absolute_import
from ._filters import *
import numpy
import scipy.ndimage.filters
import skimage.filters
import skimage.morphology
__all__ = []
for key in _filters.__dict__.keys():
__all__.append(key)
def gaussianSmoothing(image, sigma, nSpatialDimensions=2):
image = numpy.require(i... |
454050 | import warnings
from io import StringIO
import numpy
from sklearn.base import TransformerMixin
from sklearn.utils import column_or_1d
from sklearn.utils.validation import check_is_fitted
try:
from scipy.io import arff
HAS_ARFF = True
except:
HAS_ARFF = False
try:
from sklearn.utils.estimator_checks i... |
454060 | import redis
import connection
from twisted.internet.threads import deferToThread
from scrapy.utils.serialize import ScrapyJSONEncoder
class RedisPipeline(object):
"""将serialized item数据push进一个redis list/queue中"""
def __init__(self, server):
self.server = server
self.encoder = ScrapyJSONEncod... |
454071 | import os
import os.path as osp
import numpy as np
import torch
from PIL import Image
from torch.utils.data import Dataset
from torchvision import transforms
class CUB200(Dataset):
def __init__(self, root='./', train=True,
index_path=None, index=None, base_sess=None):
self.root = os.pat... |
454204 | import click
@click.command()
def cli():
click.echo("Hello, World!")
if __name__ == '__main__':
cli()
|
454214 | from collections import namedtuple
from gooey.gui.widgets import components
is_required = lambda widget: widget['required']
is_checkbox = lambda widget: isinstance(widget, components.CheckBox)
ComponentList = namedtuple('ComponentList', 'required_args optional_args')
def build_components(widget_list):
'''
:para... |
454238 | from django.views.generic import TemplateView
from .constants import SCENES
class SceneView(TemplateView):
template_name = 'scenes/scene.html'
def get_context_data(self, **kwargs):
context = super(SceneView, self).get_context_data(**kwargs)
context['scenes'] = SCENES
return context
|
454249 | import pytest
from bayesian.factor_graph import *
def pytest_funcarg__x1(request):
x1 = VariableNode('x1')
return x1
def pytest_funcarg__x2(request):
x2 = VariableNode('x2')
return x2
def pytest_funcarg__fA_node(request):
def fA(x1):
return 0.5
fA_node = FactorNode('fA', fA)
... |
454281 | import unittest
import json
from aiohttp import web
from aiohttp_auth import auth, auth_middleware
from aiohttp_auth import acl, acl_middleware
from aiohttp_auth.permissions import Group, Permission
from aiohttp_session import session_middleware, SimpleCookieStorage
from .util import asyncio
from .util.aiohttp.test imp... |
454295 | from __future__ import division, print_function
import sys
from numpy import zeros, ones, int32, hstack, newaxis, log, sqrt, arange,\
all, abs, where
from numpy.random import uniform, normal, seed, randint, choice, exponential
class HOSet(object):
"""
nstates - number of HO states to sample
max_... |
454334 | import logging
logger = logging.getLogger(__name__)
TORRENT_CLIENTS = {}
try:
from .rtorrent import RTorrentClient
TORRENT_CLIENTS[RTorrentClient.identifier] = RTorrentClient
logger.debug('Enabled client %s' % RTorrentClient.identifier)
except ImportError:
logger.debug('Failed to enable client rtorr... |
454351 | import camoco as co
class Analysis(object):
"""
Perform an analysis based on CLI arguments:
set up, event loop, tear down
"""
def __init__(self):
# Init needs to just store args and other analysis level data
self.args = args
self.tag = "Analysis"
def __call__(... |
454371 | import numpy as np
from scipy.sparse import csr_matrix
import warnings
from xclib.utils.sparse import csr_from_arrays, retain_topk
def topk(values, indices=None, k=10, sorted=False):
"""
Return topk values from a np.ndarray with support for optional
second array
Arguments:
---------
values: n... |
454411 | class Iterator(object):
"""Base class of all dataset iterators.
Iterator iterates over the dataset, yielding a minibatch at each
iteration. Minibatch is a list of examples. Each implementation should
implement an iterator protocol (e.g., the :meth:`__next__` method).
Note that, even if the iterat... |
454482 | from setuptools import setup
from os import path
here = path.abspath(path.dirname(__file__))
setup(
name="mlagents_envs",
version="0.10.1",
description="Unity Machine Learning Agents Interface",
url="https://github.com/Unity-Technologies/ml-agents",
author="<NAME>",
author_email="<EMAIL>",
... |
454487 | from __future__ import unicode_literals
import pytest # noqa
import os
import os.path
from pytest import raises
from textx import (get_location, metamodel_from_str,
metamodel_for_language,
register_language, clear_language_registrations)
import textx.scoping.providers as scoping_p... |
454518 | from __future__ import print_function
import lldb
from lldbsuite.test.lldbtest import *
from lldbsuite.test.decorators import *
from gdbclientutils import *
# This test case is testing three things:
#
# 1. three register values will be provided in the ? stop packet (T11) -
# registers 0 ("rax"), 1 ("rbx"), and 3... |
454620 | import re
class Parser(object):
# json data with job parameters
__json_data = {}
def __init__(self, json_data):
self.__json_data = json_data
def get_repository_namespace(self):
repository_name = ''
if "repository" in self.__json_data and "homepage" in self.__json_data["reposi... |
454624 | import sys
import json
import os
from os import path, environ
from .printing import *
from .compatibility import *
from .utils import safe_mkdir, strip_home
from .constants import ProjInfo
def get_xdg_config_path() -> str:
"""Returns path to $XDG_CONFIG_HOME, or ~/.config, if it doesn't exist."""
return environ.get... |
454638 | import bge
def main():
cont = bge.logic.getCurrentController()
own = cont.owner
sens = cont.sensors['mySensor']
actu = cont.actuators['myActuator']
if sens.positive:
cont.activate(actu)
else:
cont.deactivate(actu)
main()
|
454640 | from .trace_helper import *
from .parser import *
from .node_transformer import *
from .script_helper import *
|
454649 | from lego.apps.permissions.constants import LIST, VIEW
from lego.apps.permissions.permissions import PermissionHandler
class EmojiPermissionHandler(PermissionHandler):
authentication_map = {LIST: False, VIEW: False}
|
454667 | from torchvision.transforms.functional import normalize
import torch.nn as nn
import numpy as np
def denormalize(tensor, mean, std):
mean = np.array(mean)
std = np.array(std)
_mean = -mean/std
_std = 1/std
return normalize(tensor, _mean, _std)
class Denormalize(object):
def __init__(self, ... |
454672 | import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import interactive, style
import numpy as np
import random
import serial
# Initialize serial port
ser = serial.Serial()
ser.port = 'dev/cu.SLAB_USBtoUART' # Conected serial port
ser.baudrate = 115200
ser.timeout = 50
ser.open()
i... |
454691 | SECRET_KEY = "12345"
DATABASES = {"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}}
INSTALLED_APPS = [
"django.contrib.auth",
"django.contrib.contenttypes",
"wagtail.users",
"wagtail.admin",
"wagtail.images",
"wagtail.core",
"tests.my_app",
]
AUTH_PASSWORD_VALIDATOR... |
454706 | import csv
data = []
with open('output_edited.csv', 'rb') as csvfile:
reader = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in reader:
data.append(row)
filteredData = []
firstRow = True
for row in data:
rowData = row[0].split(',')
if firstRow:
filteredData.append(row)
... |
454736 | from migrate import *
def upgrade(migrate_engine):
migrate_engine.execute('''
BEGIN;
CREATE INDEX idx_revision_author ON "revision" (author);
CREATE INDEX idx_openid ON "user" (openid);
CREATE INDEX "idx_user_name_index" on "user"((CASE WHEN ("user".fullname IS NULL OR "user".fullname = '') THEN "u... |
454738 | import json
import os
import swapi
edge_lookup = {
"films": "Film",
"homeworld": "Planet",
"species": "Species",
"starships": "Starship",
"vehicles": "Vehicle",
"residents": "Character",
"characters": "Character",
"planets": "Planet",
"species": "Species",
"people": "Character"... |
454748 | import logging
from typing import Union
from discord import User, Member, Guild
from discord.ext import commands
log = logging.getLogger(__name__)
class MemberUpdates(commands.Cog):
def __init__(self, bot: commands.Bot):
self.bot = bot
@commands.Cog.listener()
async def on_member_ban(self, gu... |
454756 | import os.path
import sys
import argparse
import logging
from . import doc, blog, analysis, model
def main():
parser = argparse.ArgumentParser(
description = "Renders a Countershape documentation tree."
)
parser.add_argument(
"-o", "--option", type=str,
action="append", dest="opt... |
454758 | import unittest, random, sys, time, json
sys.path.extend(['.','..','../..','py'])
import h2o, h2o_cmd, h2o_kmeans, h2o_import as h2i, h2o_util
def define_create_frame_params(SEED):
paramDict = {
# minimum of 5 rows to cover the 5 cluster case
'rows': [5, 100, 1000],
'cols': [10, 100], # Num... |
454768 | from typing import Dict, Optional
from requests_html import HTML, HTMLSession
from nitter_scraper.schema import Profile # noqa: I100, I202
def username_cleaner(username: str) -> str:
"""Strips @ symbol from a username.
Example:
@dgnsrekt -> dgnsrekt
Args:
username: username with @ sym... |
454772 | from .tool.func import *
def login_login_2(conn):
curs = conn.cursor()
ip = ip_check()
if ip_or_user(ip) == 0:
return redirect('/user')
if ban_check(None, 'login') == 1:
return re_error('/ban')
if flask.request.method == 'POST':
if captcha_post(flask.request.form.get('g-r... |
454796 | from test.integration.base import DBTIntegrationTest, use_profile
import yaml
class TestAlterColumnTypes(DBTIntegrationTest):
@property
def schema(self):
return '056_alter_column_types'
def run_and_alter_and_test(self, alter_column_type_args):
self.assertEqual(len(self.run_dbt(['run'])), ... |
454803 | from .optimizer import Optimizer
from .entmoot_minimize import entmoot_minimize
from .entmootopti import EntmootOpti
__all__ = [
"Optimizer","entmoot_minimize"
]
|
454807 | import sys
import click
@click.command('me', short_help='Update current user')
@click.option('--name', help='Name of user')
@click.option('--email', help='Email address (login username)')
@click.option('--password', help='Password')
@click.option('--status', help='Status eg. active, inactive')
@click.option('--text'... |
454825 | import subprocess
import unittest
import sys
import httplib
import os
import sys
import itertools
import time
from urlparse import urljoin
exe = os.environ['EXECUTABLE']
class BlackboxTestCase(unittest.TestCase):
"""Test suite that runs every test case on a single
instance of server
"""
@classmethod
... |
454924 | import os
import sys
sys.path.append("..")
sys.path.append(".")
import json
import csv
import numpy as np
import tensorflow as tf
from model.checkpoint_loader import build_model_from_config
from utils.Adam_mult import AdamWarmup, calc_train_steps
import unittest
class Test_PowerBERTModels(unittest.TestCase):
de... |
454940 | from sqlalchemy.exc import IntegrityError
from grouper.fe.forms import PermissionCreateForm
from grouper.fe.util import GrouperHandler, test_reserved_names
from grouper.models.audit_log import AuditLog
from grouper.permissions import create_permission
from grouper.user_permissions import user_creatable_permissions
fro... |
454964 | import struct
from typing import List
from bitcoin_client.hwi.serialization import CTransaction, hash256, ser_string
def bip143_digest(tx: CTransaction,
amount: int,
input_index: int,
sig_hash: int = 0x01) -> bytes:
hash_prev_outs: bytes = b"".join([
... |
454965 | import os
from typing import List, Dict, Tuple, Optional
import yaml
from app.clients.jenkins_client import JenkinsInstanceConfig
class TriggearConfig:
def __init__(self) -> None:
self.__jenkins_instances: Dict[str, JenkinsInstanceConfig] = {}
self.__github_token: Optional[str] = None
se... |
454977 | import numpy as np
import os
multivariate_dims = [2, 4, 8]
N_BY_CLUS = 10
BASE_PATH = os.path.join("resources", "benchmarks", "datasets")
BASE_CHAIN_PATH = os.path.join("resources", "benchmarks", "chains")
if __name__ == '__main__':
os.makedirs(BASE_PATH, exist_ok=True)
os.makedirs(BASE_CHAIN_PATH, exist_ok=T... |
455030 | import datetime
import json
import os
from scripts.artifact_report import ArtifactHtmlReport
from scripts.ilapfuncs import logfunc, tsv, timeline, is_platform_windows, get_next_unused_name
def get_browser_name(file_name):
if 'microsoft' in file_name.lower():
return 'Edge'
elif 'chrome' in file_name.l... |
455047 | def solver_function(L1: list, L2: list, C1: list, C2: list,
C_max: int) -> QuantumCircuit:
# the number of qubits representing answers
index_qubits = len(L1)
# the maximum possible total cost
max_c = sum([max(l0, l1) for l0, l1 in zip(C1, C2)])
min_c = sum([min(l0, l1) for l0, ... |
455055 | from __future__ import print_function
import sys
import pyexcel as pe
book = pe.get_book(file_name=sys.argv[1])
bfh = open('samocha.benign.vcf', 'w')
pfh = open('samocha.pathogenic.vcf', 'w')
header = """##fileformat=VCFv4.1
##source=pathoscore
##reference=GRCh37
##INFO=<ID=MPC,Number=1,Type=Float,Description="MPC s... |
455105 | import hy
# For the side-effect of allowing import of Hy programs.
import pytest
def pytest_collect_file(parent, path):
if path.basename.startswith('test_') and path.ext == ".hy":
return pytest.Module.from_parent(parent, fspath=path)
|
455123 | from django.urls import path
from .views import GoogleSocialAuthView
urlpatterns = [
path('google/', GoogleSocialAuthView.as_view()),
] |
455131 | import time
import re
from threading import Lock, Thread
from src.utility.exceptions import OperationError
class Connection:
def __init__(self, terminal=None):
self._terminal = terminal
self._reader_running = False
self._auto_read_enabled = True
self._auto_reader_lock = Lock()
... |
455137 | import torch
from pinot import Net
from pinot.regressors import (
ExactGaussianProcessRegressor,
NeuralNetworkRegressor,
)
class MultiOutputNet(Net):
""" An object that combines the representation and parameter
learning, puts into a predicted distribution and calculates the
corresponding divergenc... |
455151 | from django.http import HttpRequest
from django.http import HttpResponse
from django.shortcuts import render
def lab_open_source(request: HttpRequest) -> HttpResponse:
return render(
request,
'about/lab-open-source.html',
{
'title': 'Open Source in our Computer Lab',
},... |
455154 | import os
from mfr import settings
config = settings.child('UNOCONV_EXTENSION_CONFIG')
UNOCONV_BIN = config.get('UNOCONV_BIN', '/usr/local/bin/unoconv')
UNOCONV_TIMEOUT = int(config.get('UNOCONV_TIMEOUT', 60))
ADDRESS = config.get('SERVER', os.environ.get('UNOCONV_PORT_2002_TCP_ADDR', '127.0.0.1'))
PORT = config.g... |
455166 | import FWCore.ParameterSet.Config as cms
ecal2006TBWeightUncalibRecHit = cms.EDProducer("EcalTBWeightUncalibRecHitProducer",
use2004OffsetConvention = cms.untracked.bool(False),
EBdigiCollection = cms.InputTag('ecalTBunpack',''),
EEdigiCollection = cms.InputTag('',''), ... |
455167 | from typing import Set, List, Tuple, Optional, Dict
import numpy as np
from algorithms.algorithm import Algorithm
from algorithms.basic_testing import BasicTesting
from algorithms.configuration.entities.goal import Goal
from algorithms.configuration.maps.map import Map
from algorithms.configuration.maps.ros_map impor... |
455259 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import shutil
import sys
import tempfile
from observations.r.cracker import cracker
def test_cracker():
"""Test module cracker.py by downloading
cracker.csv and testing shape of
extracted data has 32... |
455288 | import os, sys
import glob
from sh import tar
import numpy as np
def main():
tar_files = sys.argv[1]
sample_ratio = float(sys.argv[2])
np.random.seed(1234)
tar_files = glob.glob(tar_files)
print(tar_files)
work_dir = os.path.dirname(tar_files[0])
os.system(f'mkdir -p {work_dir}/binary_f... |
455311 | S=int(input('Enter the Size: '))
TSUM=int(input('Enter Target Sum: '))
a=[]
for i in range(S):
a.append(int(input('Enter the array ElementS: ')))
def Quadruple(a,TSUM):
a.sort()
for i in range(S-3):
for j in range(i+1,S-2):
k=TSUM-(a[i]+a[j])
l=j+1
h=S-1
... |
455346 | import json
class CustomError(Exception):
pass
def lambda_handler(event, context):
num_of_winners = event['input']
# Trigger the Failed process
if 'exception' in event:
raise CustomError("An error occurred!!")
return {
"body": {
"num_of_winners": num_of_winner... |
455347 | import itertools
import threading
import unittest
from luigi.contrib.hdfs import get_autoconfig_client
class HdfsClientTest(unittest.TestCase):
def test_get_autoconfig_client_cached(self):
original_client = get_autoconfig_client()
for _ in range(100):
self.assertIs(original_client, ge... |
455350 | import copy
import confu.schema
import vaping
import vaping.config
import vaping.io
from vaping.plugins import PluginConfigSchema
try:
import vodka
import vodka.data
except ImportError:
pass
try:
import graphsrv
import graphsrv.group
except ImportError:
graphsrv = None
def probe_to_graphsr... |
455351 | from ..broker import Broker
class DeviceGroupMemberBroker(Broker):
controller = "device_group_members"
def show(self, **kwargs):
"""Shows the details for the specified device group member.
**Inputs**
| ``api version min:`` None
| ``api version max:`` None
... |
455372 | import os
import json
import argparse
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
parser = argparse.ArgumentParser(description='The script to generate data for harbor v1.4.0')
parser.add_argument('--endpoint... |
455382 | import base64, os
from io import BytesIO
from PIL import ImageFont, ImageDraw, Image
from .. import static
path = os.path.join(static, 'high_eq_image.png')
fontpath = os.path.join(static, 'msyh.ttc')
def draw_text(img_pil: Image.Image, text: str, offset_x: float):
draw = ImageDraw.Draw(img_pil)
font = ImageF... |
455506 | import ST7735
from PIL import Image, ImageDraw
from enviroplus.noise import Noise
print("""noise-amps-at-freqs.py - Measure amplitude from specific frequency bins
This example retrieves the median amplitude from 3 user-specified frequency ranges and plots them in Blue, Green and Red on the Enviro+ display.
As you pl... |
455507 | from __future__ import absolute_import
import re
import bisect
import sys
from graphite.tags.base import BaseTagDB, TaggedSeries
class RedisTagDB(BaseTagDB):
"""
Stores tag information in a Redis database.
Keys used are:
.. code-block:: none
series # Set of all paths
... |
455536 | from django.apps import AppConfig
class GithubIntegrationConfig(AppConfig):
name = 'integrations.github'
def ready(self):
import integrations.github.handlers
|
455549 | import json
from pantomime.types import JSON
from opensanctions.core import Context
from opensanctions import helpers as h
def format_number(value):
if value is not None:
return "%.2f" % float(value)
def crawl(context: Context):
path = context.fetch_resource("source.json", context.dataset.data.url)... |
455550 | import functools
import math
import random
from dataclasses import dataclass
from typing import Dict, List, Tuple
import geometry_msgs.msg
import rospy
import std_msgs
from simulation_brain_link.msg import State as StateEstimationMsg
from simulation_groundtruth.srv import LaneSrv, SectionSrv
from tf2_msgs.msg import T... |
455569 | from .data_structures import Dependency
from .layer_topology import LayerTopology
from .topology_manager import TopologyManager
from ..layers import GatherLayer
class GatherTopology(LayerTopology):
"""docstring for PaddingTopology"""
def __init__(self, layer):
super(GatherTopology, self).__init__(lay... |
455583 | import MDAnalysis as mda
import numpy as np
from swarmcg import config
def get_AA_bonds_distrib(ns, beads_ids, grp_type, grp_nb):
"""Calculate bonds distribution from AA trajectory.
ns requires:
aa2cg_universe
mda_backend
bw_constraints
bw_bonds
bonds_scaling
... |
455588 | from ..remote import RemoteModel
class ScriptModuleRemote(RemoteModel):
"""
Script module library information.
| ``id:`` The internal NetMRI identifier of the Script Module.
| ``attribute type:`` number
| ``name:`` The unique name of the Script Module.
| ``attribute type:`` string
... |
455610 | class SelectedCellsChangedEventArgs(EventArgs):
"""
Provides data for the System.Windows.Controls.DataGrid.SelectedCellsChanged event.
SelectedCellsChangedEventArgs(addedCells: List[DataGridCellInfo],removedCells: List[DataGridCellInfo])
SelectedCellsChangedEventArgs(addedCells: ReadOnlyCollection[Data... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.