id
stringlengths
3
8
content
stringlengths
100
981k
11507780
from distutils.core import setup setup( name='permission', version='0.4.1', author='<NAME>', author_email='<EMAIL>', url='https://github.com/hustlzp/permission', packages=['permission'], license='MIT', description='Simple and flexible permission control for Flask app.', long_descrip...
11507796
import os import sys import argparse import binascii try: import re except ImportError: import ure as re import socket try: import socketserver except ImportError: try: import SocketServer as socketserver except ImportError: import upy.socketserver as socketserver import errno import rpcBind, rpcRequest from ...
11507812
from datetime import datetime import os.path from freezegun import freeze_time from notesdir.models import FileQuery, FileInfoReq, LinkInfo, FileQuerySort, FileQuerySortField, FileInfo def test_referent_skips_invalid_urls(): assert LinkInfo('foo', 'file://no[').referent() is None def test_referent_skips_non_fi...
11507852
import os import django import pytest from django.db import transaction from django.test import runner # Setup at the module level because django settings need to be # initialized before importing other django code. # This file is only imported by pytest when running tests. os.environ['DJANGO_SETTINGS_MODULE'] = 'ya...
11507901
import asyncio import math from PIL import Image import deeppyer async def main(): print('[tests] Generating gradient image...') img = Image.new('RGB', (100, 100)) for y in range(100): for x in range(100): distanceToCenter = math.sqrt((x - 100 / 2) ** 2 + (y - 100 / 2) ** 2) ...
11507916
from functools import partial from fastmri_recon.evaluate.metrics.tf_metrics import * from fastmri_recon.models.training.compile import compound_l1_mssim_loss from fastmri_recon.models.subclassed_models.vnet import Conv mssim = partial(compound_l1_mssim_loss, alpha=0.9999) mssim.__name__ = "mssim" CUSTOM_TF_OBJECTS =...
11507919
from abc import ABC, abstractmethod from logging import getLogger from typing import Generic, Iterable, Iterator, List, Optional, Tuple, Type, TypeVar, Union from intervaltree import Interval, IntervalTree from tqdm import tqdm from .cfg import DAG from .tracing import BasicBlockEntry, FunctionInvocation, ProgramTrac...
11507963
class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: visitedRooms, queue, N = set(), deque([0]), len(rooms) while queue: currentRoom = queue.popleft() if currentRoom not in visitedRooms: for neighbour in rooms[currentRoom]: ...
11507977
ClearReadout=0 Reset =1 Configure =2 Unconfigure =3 BeginRun =4 EndRun =5 BeginStep =6 EndStep =7 Enable =8 Disable =9 SlowUpdate =10 Unused_11 =11 L1Accept =12 NumberOf =13
11508072
import pytest from botx import File pytestmark = pytest.mark.asyncio async def test_sending_command_result(bot, client, message): await bot.send_message( "some text", message.credentials, ) assert client.notifications[0] async def test_sending_notification_using_send_message(bot, clie...
11508075
import pytest from services.data.db_utils import DBResponse, DBPagination import json from aiohttp.test_utils import make_mocked_request from services.ui_backend_service.api.utils import ( format_response, format_response_list, pagination_query, builtin_conditions_query, custom_conditions_query, r...
11508133
from .basic import BasicAPIv2Connector from .standard import APIv2Connector from .model import ModelAPIv2Connector
11508172
import dash_bootstrap_components as dbc from dash import html pagination = html.Div( [ html.Div("Small"), dbc.Pagination(max_value=5, size="sm"), html.Div("Default"), dbc.Pagination(max_value=5), html.Div("Large"), dbc.Pagination(max_value=5, size="lg"), ] )
11508182
from eth_account import ( Account, ) from eth_utils import ( apply_to_return_value, is_checksum_address, is_string, to_checksum_address, ) from hexbytes import ( HexBytes, ) from web3s.contract import ( Contract, ) from web3s.iban import ( Iban, ) from web3s.module import ( Module, ...
11508190
from django.contrib.auth.models import Group from rest_framework import viewsets from vocgui.models import TrainingSet from vocgui.serializers import GroupSerializer from vocgui.permissions import VerifyGroupKey from vocgui.models import GroupAPIKey from vocgui.utils import get_key from django.core.exceptions import Pe...
11508220
import sys import json from ..verifier import Proof from .utils import g2_to_sol, g1_to_sol def main(vk_filename, name='_getStaticProof'): """Outputs the solidity code necessary to instansiate a ProofWithInput variable""" with open(vk_filename, 'r') as handle: proof = Proof.from_dict(json.load(handl...
11508236
import asyncio import psutil import logging as log import time from typing import Dict, Iterable from dataclasses import dataclass from collections import defaultdict @dataclass class WatchedApp: id: str dir: str is_game: bool = True def __eq__(self, other): if isinstance(other, WatchedApp): ...
11508245
from .loggers import logger import random from sc2 import run_game, Race, maps, Difficulty from sc2.player import Bot, Computer class GameLauncher: def __init__(self, bot, use_model, model_path, map_name, realtime): logger.debug(f'Game Launcher inited in Map {map_name}') self.map = map_name ...
11508247
import albumentations as albu def get_tr_augmentation(img_size): augmentations = [ albu.HorizontalFlip(p=0.5), albu.ShiftScaleRotate(scale_limit=0.5, rotate_limit=0, shift_limit=0.1, p=1, border_mode=0), albu.PadIfNeeded(min_height=img_size[0], min_width=img_size[1], always_apply=True, ...
11508258
import logging from xia2.Driver.DriverFactory import DriverFactory logger = logging.getLogger("xia2.Wrappers.Dials.ExportXDS") def ExportXDS(DriverType=None): """A factory for ExportXDSWrapper classes.""" DriverInstance = DriverFactory.Driver(DriverType) class ExportXDSWrapper(DriverInstance.__class__...
11508304
from . import datasets from . import domain_term from . import domain_thesaurus from . import phrase_detection from . import semantic_related_word from . import utils from . import word_discrimination
11508329
import framework from framework import TestOptions import os import shutil import cl_bindgen.mangler as mangler from cl_bindgen.processfile import ProcessOptions, process_file import cl_bindgen.util as util def make_default_options(): u_mangler = mangler.UnderscoreMangler() k_mangler = mangler.KeywordMangl...
11508351
import arrow from test import get_user_session, cassette def test_should_get_groups(): session = get_user_session() with cassette('fixtures/resources/groups/list_groups/list_groups.yaml'): page = session.groups.list() assert len(page.items) == 2 assert page.count == 2 assert...
11508369
from typing import List, Tuple, Union import unrealsdk from .. import bl2tools def set_materials(ai_pawn: unrealsdk.UObject, materials: List[unrealsdk.UObject]) -> None: if materials is None: return ai_pawn.Mesh.Materials = materials def set_scale(ai_pawn: unrealsdk.UObject, scale: float) -> None:...
11508396
import numpy as np import torch.nn as nn import torch from torch.autograd import Variable import torch.nn.functional as F from modulate_conv import ModulateConv from fused_bias_activation import FusedBiasActivation from base_layer import BaseLayer from conv2d_layer import Conv2dLayer from fused_bias_activation import F...
11508490
from yamtbx.dataproc.XIO import XIO from collections import OrderedDict sp_params_strs = OrderedDict(((("BL32XU", "EIGER9M", None, None), """\ distl { detector_tiles = 1 peripheral_margin = 0 minimum_spot_area = 2 minimum_signal_height = 4. minimum_spot_height = None } xds { strong_pixel = 4 minimum_num...
11508495
import torch from torch.autograd import Variable import torch.nn as nn import math import torch.nn.functional as F from .core import * import copy def acoustic_builder(aco_type, opts): if aco_type == 'rnn': model = acoustic_rnn(num_inputs=opts.num_inputs, emb_size=opts.emb_si...
11508518
from pytest import approx import math from my_source import euclid def test_euclid(): a = [0, 0, 0] b = [4, 4, 4] dist = euclid(a, b) assert(math.sqrt(48.) == approx(dist))
11508536
import prodigy from multiprocessing import Process from time import sleep from prodigy.recipes.ner import batch_train import atexit from pathlib import Path import datetime as dt from prodigy.components import printers from prodigy.components.loaders import get_stream from prodigy.core import recipe, recipe_args from ...
11508546
import json import re import textwrap from functools import partial import pytest import pytestqt.exceptions from _pytest.compat import nullcontext from PyQt5.QtCore import QByteArray from PyQt5.QtCore import QDataStream from PyQt5.QtCore import QIODevice from PyQt5.QtCore import QMimeData from PyQt5.QtCore import QPo...
11508552
import numpy as np import matplotlib.pyplot as plt import matplotlib import scipy.io from IPython.core.display import display, HTML from ipywidgets import interact, widgets, fixed import sys sys.path.append('helper_functions/') def plotf2(r, img, ttl, sz): #fig = plt.figure(figsize=(2, 2)); #plt.figur...
11508554
import os import json def get_event(): with open(os.getenv("GITHUB_EVENT_PATH"), "r") as event_data: event = json.loads(event_data.read()) return event
11508600
from core.helpers import catch_errors from plugin.core.constants import PLUGIN_PREFIX from plugin.managers.account import AccountManager from plugin.models import Account import logging import requests log = logging.getLogger(__name__) @route(PLUGIN_PREFIX + '/resources/cover') @catch_errors def Cover(account_id, r...
11508607
from __future__ import print_function, division from builtins import range import numpy as np """ This file defines layer types that are commonly used for recurrent neural networks. """ def rnn_step_forward(x, prev_h, Wx, Wh, b): """ Run the forward pass for a single timestep of a vanilla RNN that uses a ta...
11508624
from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from leaderboard.models import Comment class AddCommentForm(forms.ModelForm): class Meta: model = Comment fields = ('racer', 'comment_type', 'text') labels = { 'racer': ('Identify who...
11508647
def blah(range): print "in blah()" def foo(range): return "foo100 foo99 foo101 foo102 foo103".split() + range def functions_provided(): return "blah foo".split()
11508653
from pgctl import configsearch class DescribeGlob: def it_globs_files(self, tmpdir): tmpdir.ensure('a/file.1') tmpdir.ensure('d/file.4') with tmpdir.as_cwd(): assert list(configsearch.glob('*/file.*')) == ['a/file.1', 'd/file.4']
11508701
import networkx import sys from collections import defaultdict import stream inp = sys.argv[1] out = sys.argv[2] outf = open(out, 'w') #This class represents a directed graph # using adjacency list representation class Graph: def __init__(self,vertices): #No. of vertices self.V= vertices ...
11508731
import time import caproto as ca def test_timestamp_now(): # There's more built into this than it seems: # 1. time.time() -> EPICS timestamp # 2. EPICS timestamp -> POSIX timestamp # 3. And a relaxed check that we're within 1 second of `time.time()` # on the way out now = ca.TimeStamp.now(...
11508747
import os import pypact as pp from tests.testerbase import Tester, REFERENCE_DIR class PrintLib5UnitTest(Tester): def setUp(self): self.filename = os.path.join(os.path.join(REFERENCE_DIR), "printlib4.out") def tearDown(self): pass def test_default(self): pl = pp.PrintLib...
11508774
import json import logging import os import spacy import torch from PIL import Image from torch.utils.data import Dataset log = logging.getLogger(__name__) nlp = spacy.load('en') def get_tags(sentence): return [w.text for w in nlp(sentence.strip())] def get_index_from_annotation(image_id_2_index, annotation): ...
11508809
from django.contrib.gis import admin from ... import models from wazimap_ng.general.services import permissions from wazimap_ng.general.admin.admin_base import BaseAdminModel, HistoryAdmin from wazimap_ng.general.admin import filters from wazimap_ng.general.admin.forms import HistoryAdminForm @admin.register(models.L...
11508904
import sys from flask import render_template, send_from_directory import orangeshare from orangeshare import Config from orangeshare.updater import Updater def favicon(): return send_from_directory("logo", "white.ico") def index(): updater = Updater.get_updater() return render_template("index.html", v...
11508949
import pytest from django.contrib import auth from vmprofile.models import RuntimeData, CPUProfile @pytest.mark.django_db def test_log_get_user(client): username = 'username' password = '<PASSWORD>' user = auth.models.User.objects.create_user( username, '<EMAIL>', password )...
11508976
import sys from flask.globals import request from flask.views import View from toga import platform class TogaView(View): def __init__(self, app_module): super().__init__() self.app_module = app_module def dispatch_request(self, state): # Make the Python __main__ context identify as...
11509029
from __future__ import unicode_literals import contextlib from .green import GreenPool from .utils import get_logger __all__ = ['ServerPool'] class ServerPool(object): def __init__(self): self.pool = GreenPool() self.servers = {} self.logger = get_logger().getChild('pool') @conte...
11509061
import fileinput import sys import re import os sf=os.environ.get('SF') query=os.environ.get('QUERY') for line in fileinput.input(): re_embeddings = re.search(r'^#Embeddings: (\d+)$', line) if re_embeddings: tuples = re_embeddings.group(1) re_runtime = re.search(r'Query time \(seconds\): (.+)$', ...
11509085
import logging import sys import numpy as np from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor from .feature_extractor import FeatureExtractor logging.basicConfig( stream=sys.stdout, format='%(asctime)s %(name)s-%(levelname)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S') logger = ...
11509087
from utils.tail_call_optimized import tail_call_optimized @tail_call_optimized def fib_tail_recur(n, res, temp): if n == 0: return res return fib_tail_recur(n - 1, temp, res + temp) if __name__ == "__main__": print(fib_tail_recur(1000, 0, 1))
11509128
import os import sys import copy import numpy as np import scipy.io as sio def sparse_nmf_matlab(V, params, verbose=True, useGPU=True, gpuIndex=1, save_H=True): """ Uses sparse_nmf.m to learn the parameters of a well-done sparse NMF model for the nonnegative input data V. Automatically chunks V ...
11509174
from nitorch.core import cli from nitorch.core.cli import ParseError class View(cli.ParsedStructure): """Structure that holds parameters of the `denoise_mri` command""" files: list = [] help = r"""[nitorch] Interactive viewer for volumetric images. usage: nitorch view *FILES """ def p...
11509188
import matplotlib.pyplot as plt from hyperion.model import ModelOutput from hyperion.util.constants import pc m = ModelOutput('class2_sed.rtout') fig = plt.figure() ax = fig.add_subplot(1, 1, 1) # Total SED sed = m.get_sed(inclination=0, aperture=-1, distance=300 * pc) ax.loglog(sed.wav, sed.val, color='black', lw=...
11509192
from . import BaseTestClass try: from urllib import urlencode from urlparse import parse_qsl, urlparse except ImportError: from urllib.parse import parse_qsl, urlencode, urlparse import responses from instamojo_wrapper import Instamojo from tests.payloads import payment_requests_payload class TestPaymen...
11509220
from django.views.generic import ListView, DetailView from .models import Post class PostListView(ListView): model = Post paginate_by = 10 class PostDetailView(DetailView): model = Post
11509241
import abc import contextlib import os import random import shelve import river.base import river.metrics import river.stats import river.utils import dill import flask try: import redis except ImportError: pass from . import exceptions from . import flavors class StorageBackend(abc.ABC): """Abstract st...
11509296
import cv2 import numpy as np from depthai_sdk import toTensorResult, Previews def decode(nnManager, packet): data = np.squeeze(toTensorResult(packet)["Output/Transpose"]) classColors = [[0,0,0], [0,255,0]] classColors = np.asarray(classColors, dtype=np.uint8) outputColors = np.take(classColors, da...
11509328
import subprocess import sys import os def command_exists(command): proc = subprocess.Popen(["hash", command], stdout=subprocess.PIPE, stderr=subprocess.PIPE) return proc.stderr.read() == b'' if not command_exists("node"): if len(sys.argv) < 2: print("Run as python3 Make.py <package manager>") ...
11509335
description = 'Tensile machine' group = 'optional' devices = dict( teload = device('nicos.devices.generic.VirtualMotor', description = 'load value of the tensile machine', abslimits = (-50000, 50000), unit = 'N', fmtstr = '%.2f', ), # tepos = device('nicos.devices.generic.V...
11509349
import collections import dateutil.parser import datetime import logging from . import funcs from .common import CoordType import json InitialData = collections.namedtuple("InitialData", ["header", "firstrows", "rowcount", "filename"]) class ParseSettings(): """A "model-like" object which stores all the settings...
11509385
import unittest class TestCase(unittest.TestCase): longMessage = True def assertPointEqual(self, p1, p2): self.assertNamedTupleAlmostEqual(p1, p2) def assertNamedTupleAlmostEqual(self, t1, t2): for field in t1._fields: msg = 'Field {} is different'.format(field) sel...
11509396
import boto3 client = boto3.client('cloudwatch') def lambda_handler(event, context): t = event["reading_time"] v = float(event["reading_value"]) print "New temperature reading: Time: %s, Temp: %.2f" % (t, v) client.put_metric_data( Namespace = 'Temperature Monitoring Database App', MetricData ...
11509408
def _ocamlrun(ctx): executable = ctx.actions.declare_file(ctx.attr.name) bytecode = ctx.file.src ocamlrun = ctx.file._ocamlrun template = ctx.file._runscript ctx.actions.expand_template( template=template, output=executable, substitutions={ "{ocamlrun}": ocamlru...
11509440
import re from typing import List from securify.analyses.patterns.abstract_pattern import Severity, PatternMatch, MatchComment from securify.analyses.patterns.ast.abstract_ast_pattern import AbstractAstPattern from securify.analyses.patterns.ast.declaration_utils import DeclarationUtils class SolidityNamingConventio...
11509532
from django.urls import path from . import views urlpatterns = [ path('products/', views.ProductList.as_view()), path('reviews/', views.ReviewRatingList.as_view()), path('orders-products/', views.OrderProductList.as_view()), ]
11509559
from .utils import get_linter_errors_list from sitefab.utils import objdict def test_no_meta(sitefab, empty_post): empty_post.meta = None results = sitefab.linter.lint(empty_post, "", sitefab) error_list = get_linter_errors_list(results) assert isinstance(error_list, list) def test_meta_no_toc(sitef...
11509567
import numpy as np def graycomatrixext(im_input, im_roi_mask=None, offsets=None, num_levels=None, gray_limits=None, symmetric=False, normed=False, exclude_boundary=False): """Computes gray-level co-occurence matrix (GLCM) within a region of interest (ROI) of an image. G...
11509616
import boto3 ec2 = boto3.client('ec2') response = ec2.describe_instances() for item in response['Reservations']: for eachinstance in item['Instances']: print (eachinstance['InstanceId'],eachinstance['PrivateIpAddress'])
11509623
from django.views import generic from django.apps import apps class PageView(generic.DetailView): model = apps.get_model('cc_cms', 'Page') def get_template_names(self): return [f'pages/{self.object.slug}.html', 'cc_cms/page.html']
11509629
from argparse import ArgumentParser from sys import argv from importnb import Notebook from .tangle import Tangle from .weave import Weave parser = ArgumentParser() parser.add_argument("file") def main(): from .loader import Literate ns = parser.parse_args(argv[1:]) module = Literate.load(ns.file) ...
11509665
from waldur_core.logging.loggers import EventLogger, event_logger from .models import Comment, Issue def get_issue_scopes(issue): project = issue.project.project result = {project, project.customer} if issue.resource: result.add(issue.resource) return result class IssueEventLogger(EventLogg...
11509671
import sys import argparse from pyvideoai import config import dataset_configs from pyvideoai.dataloaders.utils import retry_load_images import os from PIL import Image import numpy as np def get_parser(): parser = argparse.ArgumentParser(description="Visualise success and failures. For now, only support EPIC", ...
11509685
import os from parse import parse from hatch.create import create_package from hatch.files.setup import TEMPLATE from hatch.files.vc.git import get_email, get_user from hatch.settings import copy_default_settings from hatch.utils import temp_chdir from .utils import read_file def test_name(): with temp_chdir() ...
11509691
class Solution: def maxProduct(self, nums: List[int]) -> int: if not nums: return 0 f = g = result = nums[0] for n in nums[1:]: if n < 0: f, g = g, f f, g = max(f * n, n), min(g * n, n) result = max(result, f) return result
11509693
import os import sys import shutil import pytest import cv2 import numpy as np import tensorflow as tf from fixtures import test_asset_dir, model_dir sys.path.append(os.path.join(os.path.dirname(__file__), "..")) from confignet import FaceImageNormalizer, ConfigNet, LatentGAN def get_normalized_test...
11509704
import os import numpy as np def conf_prep(mu,beta,D,w): file = open("conf.txt","w") file.writelines("w = %d\nb = %d\nD = %d\nmu = %f" % (w,beta,D,mu)) file.close() # Update this with the path to msgsteiner msgpath = "./msgsteiner" # The interval stop value is not included in the range mu_range = np.aran...
11509708
import unittest from biothings_explorer.user_query_dispatcher import SingleEdgeQueryDispatcher from .utils import get_apis class TestSingleHopQuery(unittest.TestCase): def test_variant2gene(self): # test <gene, enableMF, mf> seqd = SingleEdgeQueryDispatcher(input_cls='SequenceVariant', ...
11509712
import os import argparse import json import datetime import sys from PyQt5 import QtGui, QtWidgets, uic from google.cloud import pubsub_v1 qtUiFile = "gcp_qt.ui" class Ui(QtWidgets.QMainWindow): """Basic Message Visualizer gui""" def __init__(self, project_id, subscription_id): super(Ui, self).__init...
11509713
import urllib.request import xarray as xr import xstac import pandas as pd import pathlib import pystac import json url = "http://berkeleyearth.lbl.gov/auto/Global/Gridded/Complete_TMAX_EqualArea.nc" file = "Complete_TMAX_EqualArea.nc" if __name__ == "__main__": if not pathlib.Path(file).exists(): urllib....
11509814
import sys from PyQt5.QtWidgets import QDialog, QFileDialog, QApplication, QMessageBox from PyQt5.QtGui import QIcon from PyQt5.uic import loadUi import os import cv2 class CtwoD(QDialog): def __init__(self): super().__init__() path = os.getcwd() os.chdir(path+'/twoD') loadUi('twoD...
11509848
from target import TargetType import os import re import cv2 import time import subprocess import numpy as np TARGET_DIR = './assets/' TMP_DIR = './tmp/' SIMILAR = { '1': ['i', 'I', 'l', '|', ':', '!', '/', '\\'], '2': ['z', 'Z'], '3': [], '4': [], '5': ['s', 'S'], '6': [], '7': [], '8...
11509856
import random import time class Cat: def __init__(self): self.cat_lives = 9 def begin_cats_life(self): while True: if self.cat_is_fed() and not self.lost_a_life(): print ('The Cat is doing well.') else: print ('The Cat is not doing so g...
11509871
import zlib from . import register_test # Detect blacklisted files based on their extension. blacklisted_extensions = ("dll", "exe", "dylib", "so", "sh", "class") blacklisted_magic_numbers = ( (0x4d, 0x5a), # EXE/DLL (0x5a, 0x4d), # Alternative for EXE/DLL (0x7f, 0x45, 0x4c, 0x46), # UNIX ...
11509883
from floto.api import SwfType class WorkflowType(SwfType): """ Attributes ---------- default_child_policy : Optional[str] Specify the default policy to use for the child workflow executions when a workflow execution of this type is terminated. Valid values: TERMINATE | REQUEST_...
11509971
from functools import wraps from typing import Any, Callable, Optional, TypeVar import grpc import grpc.aio class RequestException(Exception): """An exception was raised when communicating with the service.""" def __init__(self, delegate: grpc.aio.AioRpcError): self._delegate = delegate grpc.ai...
11510025
from toee import * import char_editor def CheckPrereq(attachee, classLevelled, abilityScoreRaised): #Sneak Attack Check if not char_editor.has_feat(feat_sneak_attack): return 0 if char_editor.stat_level_get(stat_level_paladin) > 1: #workaround until I figure out how to check for immunity to fear retu...
11510036
from argparse import ArgumentParser, RawTextHelpFormatter, SUPPRESS from swarmcg.shared import styling from swarmcg.io.job_args import defaults def get_analyze_args(): print(styling.header_package("Module: Optimization run analysis\n")) formatter = lambda prog: RawTextHelpFormatter(prog, width=135, max_help...
11510074
from dbnd import dbnd_cmd class TestShowCmds(object): def test_show_tasks(self): dbnd_cmd("show-tasks", []) def test_show_configs(self): dbnd_cmd("show-configs", [])
11510137
from os.path import join def translate(config): result = { 'deployment_implementation': _deployment_implementation(), 'redis_url': config.get('redis_url', 'redis://localhost:6379'), 'worker_container_overrides': config.get('worker', {}), # 'job_store_root': config['job_store_root'],...
11510166
from __future__ import absolute_import import docker import pytest from docker import utils as docker_utils @pytest.fixture(scope='session') def docker_client(): client_cfg = docker_utils.kwargs_from_env() return docker.APIClient(version='1.21', **client_cfg) @pytest.yield_fixture(scope='session') def regi...
11510184
import requests import json from string import Template import framework.server.common.codes as codes class InvalidResponse(): text = {'server_error': ''} REQUEST_TEMPLATE = Template("http://$HOST:$PORT/request") CONTAINER_PORT = 8081 def HandleRequest(payload, host, framework): resp = "" clientUrl = REQUES...
11510213
import pytest from wq.core.task import CompositeTaskId tags_supply = [[], [''], ['a', 'b'], ['a', 'b', 'c']] @pytest.mark.parametrize('tags', tags_supply) def test_uniqueness(tags): id1 = CompositeTaskId(*tags) id2 = CompositeTaskId(*tags) assert len(id1.id_seq()) == len(tags) + 1 assert len(id2.id...
11510219
import bpy # ORIGINAL MIXAMO RENAME CODE FETCHED FROM BLENDER ANSWERS (I THINK), IF YOU ARE THE AUTHOR OF THIS # CODE, PLEASE LET ME KNOW SO THAT I CAN CREDIT YOU HERE. print('Running Mixamo Armature Renaming Script.') bpy.ops.object.mode_set(mode = 'OBJECT') if not bpy.ops.object: print('Please select the armat...
11510235
from garbagedog.constants import GCEventType def test_from_gc_line(): log_line = "2015-05-26T14:45:37.987-0200: 151.126: [GC (Allocation Failure) 151.126: [DefNew: " \ "629119K->69888K(629120K), 0.0584157 secs] 1619346K->1273247K(2027264K), 0.0585007 secs] " \ "[Times: user=0.06 sys=...
11510255
import unittest from datetime import datetime from pyjo import Model, DatetimeField from pyjo.exceptions import FieldTypeError class DatetimeFieldTest(unittest.TestCase): def test_datetimefield(self): class A(Model): date = DatetimeField() time = 1478390400 dt = datetime.ut...
11510297
from typing import Any, List, Union import numpy as np from xarray import DataArray import weldx.transformations as tf from weldx.time import Time from weldx.transformations import WXRotation def check_coordinate_system_orientation( orientation: DataArray, orientation_expected: np.ndarray, positive_orie...
11510301
from torch.utils.data import Dataset, DataLoader, Subset from torch.utils.data.dataloader import default_collate from torch.utils.data.sampler import Sampler import torch import torch.nn as nn import torch.nn.functional as F from base import BaseDataLoader import pickle import numpy as np import json import os from tqd...
11510308
class Solution: def multiply(self, A, B): return [[sum(a * b for a, b in zip(A[i], [B[k][j] for k in range(len(B))])) for j in range(len(B[0]))] for i in range(len(A))]
11510316
from __future__ import absolute_import from __future__ import division from __future__ import print_function from .gltf import GLTF from .gltf_content import GLTFContent from .gltf_exporter import GLTFExporter from .gltf_mesh import GLTFMesh from .gltf_parser import GLTFParser from .gltf_reader import GLTFReader __al...
11510318
import re import os import ruamel.yaml as yaml from markdown import markdown, Markdown from .base import Command from io import StringIO def unmark_element(element, stream=None): """Markdown renderer that ignores markup and outputs only plain text. """ if stream is None: stream = StringIO() if ...
11510346
from pyhf.parameters.paramsets import ( paramset, unconstrained, constrained_by_normal, constrained_by_poisson, ) from pyhf.parameters.utils import reduce_paramsets_requirements from pyhf.parameters.paramview import ParamViewer __all__ = [ 'paramset', 'unconstrained', 'constrained_by_normal...