text
string
size
int64
token_count
int64
from util import * from arclib import bz2 from bz2 import compress, decompress def test_incremental_compress(): basic_test_c(bz2.Compressor(), decompress) def test_incremental_decompress(): basic_test_d(bz2.Decompressor(), compress)
243
85
from train.train_agent import train_agent from train.train_agents import train_agents
86
25
import argparse import json import logging import multiprocessing as mp import os import time from typing import List from detectron2.structures import BoxMode from detectron2 import model_zoo from detectron2.data import MetadataCatalog, DatasetCatalog from detectron2.structures import BoxMode from detectron2.utils.vi...
8,104
2,495
from typing import Any, Callable, Dict, List, Tuple try: from typing_extensions import Protocol except ImportError: from typing import Protocol # type: ignore StrHeaderListType = List[Tuple[str, str]] RawHeaderListType = List[Tuple[bytes, bytes]] HeaderDictType = Dict[str, Any] ParamDictType = Dict[str, str]...
679
211
from dataclasses import dataclass from typing import Union NoneType = type(None) @dataclass class UserDiffStats: def __init__(self, data): self.easy=data["easy"] self.expert=data["expert"] self.expertPlus=data["expertPlus"] self.hard=data["hard"] self.normal=data["normal"]...
1,660
535
import math from typing import Sequence, Tuple import torch from torch import nn from torch.nn import functional as F from tensorfn.config import config_model from pydantic import StrictInt, StrictFloat from .layer import DropPath, tuple2, PositionwiseFeedForward LayerNorm = lambda x: nn.LayerNorm(x, eps=...
11,599
4,133
import tensorflow as tf if tf.__version__.startswith('1.'): tf.enable_eager_execution()
93
30
import json def search_records(): cleaned_data = open('lifetech_cleandata.json') data = json.load(cleaned_data) my_dic={} for record in data: number = record.get("number") cnic = record.get("cnic") my_dic=record my_dic= basic_info_merger(my_dic) result01 = s...
12,340
4,046
# from django import forms # from .models import ExcelUpload # # # class ExcelUploadForm(forms.ModelForm): # class Meta: # model = ExcelUpload # fields = ('document', )
189
53
from .loading import * from .utils_dict_list import * from .get_logger import get_neptune_logger, get_tensorboard_logger from .map_dict import Map,DotDict
154
49
import gzip from pathlib import Path import numpy as np data_path = Path(__file__).parent / '..' / 'data' train_images_file = data_path / 'train-images-idx3-ubyte.gz' train_labels_file = data_path / 'train-labels-idx1-ubyte.gz' test_images_file = data_path / 't10k-images-idx3-ubyte.gz' test_labels_file = data_path /...
2,676
1,004
from __future__ import absolute_import from __future__ import print_function import os.path import numpy # from nipype.interfaces.base import ( # TraitedSpec, traits, File, isdefined, # CommandLineInputSpec, CommandLine) from nipype.interfaces.base import ( TraitedSpec, traits, BaseInterface, File, isdefine...
5,063
1,622
from Bio import SeqIO import sys with open("phase0.fasta", 'w') as phase0, open("phase1.fasta", 'w') as phase1: for record in SeqIO.parse(sys.argv[1], "fasta"): if record.id.endswith('0'): phase0.write(record.format("fasta")) elif record.id.endswith('1'): phase1.write(record...
381
128
import time from tests.integration.integration_test_case import IntegrationTestCase from app.settings import RESPONDENT_ACCOUNT_URL class TestSession(IntegrationTestCase): def test_session_expired(self): self.get('/session-expired') self.assertInPage('Your session has expired') def test_sess...
1,245
392
import os from gym.envs.mujoco import reacher3dof from rllab.envs.gym_env import GymEnv os.environ['MKL_SERVICE_FORCE_INTEL'] = '1' os.environ['MUJOCO_GL'] = 'egl' env = GymEnv("Reacher3DOF-v1", mode='oracle', force_reset=True) time_step = env.reset() print(time_step) while True: env.render() time_step = en...
557
220
import spacy from spacy.lang.de.examples import sentences #from collections import OrderedDict #import numpy as np nlp = spacy.load('de_core_news_sm') doc = nlp("Weil die Sonne scheint, ist es warm, nachdem ich ein Eis, das sehr lecker war, gegessen habe.") print(doc.text) #for token in doc: # print(token.text, to...
2,773
962
from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls import url urlpatterns = [ url(r'^api-auth/', include('rest_framework.urls')), path('', include('lobby.urls')), path('', include('connectquatro.urls')), path('admin/', admin.si...
332
105
# -*- coding: utf-8 -*- ''' Some common, generic utilities ''' from __future__ import absolute_import from base64 import urlsafe_b64encode, urlsafe_b64decode def urlsafe_nopadding_b64encode(data): '''URL safe Base64 encode without padding (=)''' return urlsafe_b64encode(data).rstrip('=') def urlsafe_nopa...
805
284
# ---------------------------------------------------------------------------- # Copyright (c) 2016-2018, QIIME 2 development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # ------------------------------------------------...
1,655
473
# -*- coding: utf-8 -*- """Main module.""" from pyspark.sql import DataFrame from pyspark.sql.functions import lit, col, to_timestamp def standardize_parking_bay(parkingbay_sdf: DataFrame, load_id, loaded_on): t_parkingbay_sdf = ( parkingbay_sdf .withColumn("last_edit", to_timestamp...
1,304
462
from avalon import harmony class CreateTemplate(harmony.Creator): """Composite node for publishing to templates.""" name = "templateDefault" label = "Template" family = "harmony.template" def __init__(self, *args, **kwargs): super(CreateTemplate, self).__init__(*args, **kwargs)
311
94
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
6,702
1,957
from fixture.utils import equal_list, equal_dict from ezcode.graph import NegativeCycleExist from ezcode.graph.directed import DirectedGraph from ezcode.graph.undirected import UndirectedGraph def test_undirected_graph(): """ A ------ C | /|\ | / | \ | / | \ | / | E ...
10,697
4,686
from .abc_coffee import AbcCoffeeProgram from .ingredients import Milk, Coffee from .programs import (Cappuccino, Doppio, Espresso, Latte, Lungo, Macchiato)
157
61
#coding=utf8 import time, sys, Queue import MySQLdb from MySQLdb import cursors from multiprocessing.managers import BaseManager from multiprocessing.sharedctypes import RawArray from multiprocessing import Process, freeze_support, Array reload(sys) sys.setdefaultencoding('utf8') def work(server_addr): # 数据库连接 ...
1,384
469
from invoke.exceptions import UnexpectedExit from utils import execute_command, is_file_exists import logging ''' is_genkey_unique ''' def is_genkey_unique(config): is_unique = True duplicates = [] tmp = {} for conf in config["masternodes"] : if "private_key" in conf : if tmp.get(...
3,474
1,013
# -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incor...
4,330
1,093
#! /usr/bin/env python import logging from tornado.ioloop import IOLoop from stormed import Connection, Message msg = Message('Hello World!') def on_connect(): ch = conn.channel() ch.queue_declare(queue='hello') ch.publish(msg, exchange='', routing_key='hello') conn.close(callback=done) def done(): ...
504
167
from abc import ABCMeta, abstractmethod class IOperator(metaclass=ABCMeta): @abstractmethod def operator(self): pass class Component(IOperator): def operator(self): return 10.0 class Wrapper(IOperator): def __init__(self, obj): self.obj = obj def operator(self): ...
420
136
from .metadata_parser import parse_metadata from nmfamv2.metadata import Metadata def read_metafile(metafile_path): parsed_metadata = parse_metadata(metafile_path) # Validator and object creation are combined Metadata(parsed_metadata) # Parser # Validator # Object
281
86
"""Daily clean up of DB tables.""" import logging from helpers.report_helper import ReportHelper logger = logging.getLogger(__file__) def main(): """Regular clean up of database tables.""" r = ReportHelper() try: r.cleanup_db_tables() except Exception as e: logger.exception("Excepti...
428
125
""" Copyright 2017-2018 Fizyr (https://fizyr.com) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in w...
13,356
4,918
import PySimpleGUI as pg import time import sys from pygame import mixer # Section Popup def win2m(): lay2 = [[pg.T(f'', key='T')], [pg.OK()]] win2 = pg.Window('Popup', lay2, location=(250 ,0), no_titlebar=True) return win2 def sound(): mixer.init() mixer.music.load("notification.mp...
3,093
1,033
class Data(object): def __init__(self, attributes): self._keys = list(attributes.keys()) for key in attributes: setattr(self, key, attributes[key]) def __str__(self): return "Data({0})".format(", ".join( "{0}={1!r}".format(key, getattr(self, key)) for...
449
138
import bpy from .main import ToolPanel from ..operators import retargeting, detector from ..core.icon_manager import Icons from ..core.retargeting import get_target_armature from bpy.types import PropertyGroup, UIList from bpy.props import StringProperty # Retargeting panel class RetargetingPanel(ToolPanel, bpy.typ...
4,703
1,558
from no_imports import *
25
9
import os import pytest from leapp.libraries.stdlib import api, CalledProcessError, run from leapp.models import SELinuxModule, SELinuxModules from leapp.reporting import Report from leapp.snactor.fixture import current_actor_context TEST_MODULES = [ ['400', 'mock1'], ['99', 'mock1'], ['300', 'mock1'], ...
4,128
1,422
#!/usr/bin/env python3 from __future__ import absolute_import, division, print_function, unicode_literals import argparse import os import subprocess from glob import glob import pandas as pd import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as plt import base64 import json import numpy as np impor...
20,919
6,964
from app import app from flask import render_template, request, flash from .form import * from automlk.monitor import get_heart_beeps from automlk.context import get_config, set_config @app.route('/monitor', methods=['GET']) def monitor(): # monitor workers return render_template('monitor.html', controller=ge...
1,547
423
import errand_boy from errand_boy import run from errand_boy.transports import unixsocket from .base import mock, BaseTestCase class MainTestCase(BaseTestCase): def test_client(self): argv = ['/srv/errand-boy/errand_boy/run.py', 'ls', '-al'] cmd = ' '.join(argv[1:]) with self.UNIXSocketT...
2,471
829
import socket from contextlib import suppress from os import SEEK_END, stat from pathlib import Path from re import search, split, findall from sys import exc_info from threading import Thread from time import sleep from traceback import format_exc from colorama import Fore, Style from discord import Webhook, Requests...
14,591
3,841
#!/usr/bin/python3.7 """ Set all playlist descriptions. Example result: Resident Advisor Archive www.residentarchive.com @residentarchive """ import boto3 import spotipy from pprint import pprint dynamodb = boto3.resource("dynamodb", region_name='eu-west-1') ra_playlists = dynamodb.Table('ra_playlists') scope = '...
745
261
import pandas as pd pd.set_option('display.width', 1000) pd.set_option('display.max_rows', 10000) pd.set_option('display.max_columns', 10000) def round_value(value, binary=False): divisor = 1024. if binary else 1000. if value // divisor**4 > 0: return str(round(value / divisor**4, 2)) + 'T' eli...
1,428
532
class Region(object): def __init__(self, cells): self.cells = cells def print(self): print(self.cells) def get_missing_numbers(self): missing_numbers = [] for i in range(1, 10): if i in self.get_cell_values(): continue missing_numbe...
513
151
try: from ipware.ip import get_client_ip except ImportError: from ipware.ip2 import get_client_ip
106
36
from setuptools import setup, find_packages # See: # https://packaging.python.org/guids/distruting-packages-using-setuptools setup( name="cigarbox", version="0.1.0", description="utility libraries", long_description="utility libraries", long_description_content_type="text/plain", url="https://...
736
237
# -*- coding: utf-8 -*- import types from crossover import Client from crossover import _Requester def test_client_attributes(): client = Client("redis://localhost:6379/0") assert isinstance(client, Client) assert isinstance(client.test, _Requester) assert isinstance(client.call_task, types.MethodType...
322
104
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (c) 2020 tecnovert # Distributed under the MIT software license, see the accompanying # file LICENSE.txt or http://www.opensource.org/licenses/mit-license.php. import os import sys import time import signal import logging import subprocess from io import Str...
9,707
3,816
from random import randint def sort(lista): print('SORTEANDO OS VALORES DA LISTA: ', end='') for n in range(0, 5): v = randint(1, 10) lista.append(v) print(f'Os valores são {numeros}.') print('Pronto!') def somapar(lista): s = 0 for v in lista: if v % 2 == 0: ...
440
177
if isinstance(other, float): other = Measurement(other, 0)
71
23
# -*- coding: utf-8 -*- # Copyright 2016 Open Permissions Platform Coalition # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by appl...
6,412
1,829
import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation DT = 0.01 FRAMERATE = 60 N_ROWS = 64 SECONDS = 10 def read_field_file(file_path, type): if type != 'scalar' and type != 'vector': raise ValueError('type must be scalar or vector') file_str = open(file_path, 'r...
2,802
990
RTS2_FITS_LUTs = {} RTS2_FITS_LUTs['BNL'] = { 0: { # 'MJD' : 'JD', # 'MONDIODE' : 'AMP0.CURRENT.MIN', 'MONOWL': 'MONOCH.WAVELENG', 'FILTER': 'MONOCH.FILT_1', 'CONTROLL': 'INSTRUME', 'CCDTEMP': 'CRYO.C.TEMP', 'IMGTYPE': 'TESTTYPE', ...
9,519
5,280
""" Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself """ def isSubTree(self, s, t): from ...
850
287
from argparse import ArgumentParser from contextlib import redirect_stderr from io import StringIO from re import escape as re_escape from unittest import TestCase from argparse_utils import python_literal_action class TestPythonLiteralAction(TestCase): def test_basic_python_literal_action(self): parser ...
2,039
587
import logging from joblib import Parallel, delayed from typing import Iterable from emissor.persistence import ScenarioStorage from emissor.processing.api import DataPreprocessor, ScenarioInitializer, SignalProcessor from emissor.representation.scenario import Modality logger = logging.getLogger(__name__) class Da...
3,911
1,082
from django import template from powers.models import Power register = template.Library() @register.simple_tag def player_can_edit_power(power, player): return power.parent_power.player_can_edit(player) @register.inclusion_tag('powers/power_badge_snippet.html') def power_badge(power_full): lat...
466
155
import numpy as np from matplotlib import pyplot as plt from pylab import rcParams def plot_buoyancy(cwd=''): """ Plotting routine for the cross section of the buoyancy Args: cwd (string): current working directory """ xx = np.load(cwd + 'data/xaxis.npy') uend = np.load(cwd + 'data/s...
2,298
993
#Requires the modules SpeechRecognition and pyaudio import speech_recognition as sr import sys sys.path.insert(1, "..") from camera.camera import Camera from widefind.widefindScript import WidefindTracker def recognizeSpeech(recognizer, microphone): #Check that recognizer and microphone arguments are appropriate t...
3,297
860
import os import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import load_digits from sklearn.model_selection import learning_curve class BlockingTimeSeriesSplit: def __init__(self, n_splits): self.n_splits = n_splits def get_n_splits(self, X, y, groups): ...
6,432
2,101
import glob import os import shutil import sys from zipfile import ZipFile import django from internetarchive import upload sys.path.append("/var/projects/museum/") os.environ.setdefault("DJANGO_SETTINGS_MODULE", "museum.settings") django.setup() from museum_site.models import File ZGAMES_PATH = "/var/projects/muse...
3,458
1,078
import ffmpeg import os import tempfile import re from pydub import AudioSegment import math FRAME_NAME_PATTERN = "frame-%08d.jpg" def get_filename_from_path(path): base = os.path.basename(path) return os.path.splitext(base)[0] FRACTION_PATTERN = r"(\d+)/(\d+)" FRACTION_RE = re.compile(FRACTION_PATTERN) def...
3,591
1,290
#! /usr/bin/python3 # 20180726 - wiki.binefa.cat # Based on a code from Tony DiCola (AdaFruit) # License: Public Domain import time import Adafruit_ADS1x15 import time import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) GPIO.setup(32, GPIO.OUT) GPIO.setup(33, GPIO.OUT) GPIO.setup(12, GPIO.OUT) GPIO.setup(35, GPIO.OUT) ...
1,159
647
from .users import * from .summaries import * from .keys import *
65
20
import sys import warnings import numpy as np from scipy.stats import rankdata TAB = ' ' maxfloat = np.float128 if hasattr(np, 'float128') else np.longdouble class ReprMixin: def __repr__(self): return f'{self.__class__.__name__}\n' + '\n'.join([f'\t{k}: {v}' for k, v in self.__dict__.items()]) de...
3,423
1,523
#!/usr/bin/env python # coding: utf-8 # Copyright (c) Qotto, 2019 """ BaseCommandHandler Module All command handler must be inherit from this class. Execute function was called by consumer on each received command. For make an transaction in execute function return 'transaction' as string after end transaction other...
1,372
347
from django.contrib import admin from django.urls import path,re_path from . import views from rest_framework.authtoken.views import obtain_auth_token from rest_framework_simplejwt import views as jwt_views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', views....
1,373
503
#!/usr/bin/python3 # -*- coding: utf-8 -*- import argparse import codecs def arguments(): # Handle command line arguments parser = argparse.ArgumentParser(description='Adventofcode.') parser.add_argument('-f', '--file', required=True) args = parser.parse_args() return args class Matchsticks: ...
1,517
502
from . import polygon_geo_cpu def polygon_iou(poly1, poly2): """Compute the IoU of polygons.""" return polygon_geo_cpu.polygon_iou(poly1, poly2)
155
60
class CarrinhodeCompras: def __init__(self): self.produtos = [] #agregação na lista def inserir_produtos(self, produto): self.produtos.append(produto) def lista_produto(self): for produto in self.produtos: print(produto.nome, produto.preco) def soma_total(self): ...
536
175
from ..app.crud import CRUDBase from .models import ( User, UserGroup, UserGroupMember, UserGroupPermission, UserPermission, ) class UserCRUD(CRUDBase): model = User @classmethod def get_by_uuid(Cls, session, uuid: str): return User.query.filter_by(uuid=uuid).first() @cla...
2,632
830
from dataclasses import dataclass, field from datetime import datetime from typing import Dict, Optional, Set from .alibaba_compute_source import AlibabaComputeSource from .alibaba_instance_charge_type import AlibabaInstanceChargeType from .alibaba_spot_strategy import AlibabaSpotStrategy from .compute_source_exhausti...
3,392
913
from flask import Flask, render_template, request, redirect, url_for, session from flask_session import Session from tempfile import mkdtemp from cs50 import SQL from random import randint from werkzeug.security import check_password_hash, generate_password_hash from functions import get_coms_count, get_pages_count im...
11,440
3,512
import json from asyncy.hub.sdk.db.Service import Service from playhouse.shortcuts import dict_to_model class ConstServiceHub(): """ A constant service hub class that allows serving a pre-defined set of fixed services. """ def __init__(self, services): self.services = services @cla...
826
249
# -*- coding: utf-8 -*- from QAutoLibrary.extension import TESTDATA from selenium.webdriver.common.by import By from QAutoLibrary.QAutoSelenium import * from time import sleep from pagemodel.ss_version import Ss_version class Component_ss_version(CommonUtils): """ Components common to security server version v...
721
212
import pytest from django.db import connection, transaction, ProgrammingError from django.db.backends.base.schema import BaseDatabaseSchemaEditor from django.db.backends.dummy.base import DatabaseWrapper as DummyDatabaseWrapper from django.db.backends.postgresql.schema import ( DatabaseSchemaEditor as PostgresqlDat...
6,938
1,982
#!/usr/bin/python import numpy as np import math import cv2 import config as cf class Line(): def __init__(self, side, img_shape, polyDelta=cf.POLYFIT_MARGIN, nWindow=cf.N_WINDOWS, windowMargin=cf.WINDOW_MARGIN, reThresh=cf.RECENTER_WINDOW_THRESH): # side identifier self.side = s...
14,149
4,916
from PyObjCTools.TestSupport import * from Quartz.PDFKit import * class TestPDFAnnotation (TestCase): def testMethods(self): self.assertResultIsBOOL(PDFAnnotation.shouldDisplay) self.assertArgIsBOOL(PDFAnnotation.setShouldDisplay_, 0) self.assertResultIsBOOL(PDFAnnotation.shouldPrint) ...
485
142
from selenium import webdriver from selenium.webdriver.chrome.options import Options import zipfile ip = '127.0.0.1' port = 9743 username = 'foo' password = 'bar' manifest_json = """ { "version": "1.0.0", "manifest_version": 2, "name": "Chrome Proxy", "permissions": [ "proxy", "tabs", ...
1,585
507
''' Created on 2012-10-23 @author: hzzhoushaoyu ''' import webob.exc import json from umbrella.common import wsgi import umbrella.common.log as logging from umbrella.common import cfg import umbrella.context LOG = logging.getLogger(__name__) CONF = cfg.CONF context_opts = [ cfg.BoolOpt('owner_is_tenant', defau...
3,925
1,133
# coding: utf-8 from __future__ import absolute_import from ibutsu_server import util from ibutsu_server.models.base_model_ import Model class Group(Model): """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). Do not edit the class manually. """ def __init__(...
1,813
557
# x_7_2 # # import re pattern = 'い' str = input('ひらがなの「い」のつく言葉を入力してください:') print(re.sub(pattern, 'レヽ', str))
112
72
from clipper_admin import ClipperConnection, DockerContainerManager from clipper_admin.deployers import keras as keras_deployer import keras clipper_conn = ClipperConnection(DockerContainerManager()) clipper_conn.connect() # if cluster exists inpt = keras.layers.Input(shape=(1,)) out = keras.layers.multiply([inpt, i...
1,172
392
from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * from utils.io import get_host_config from utils.params import MessageType, Mode, Topology class CommandUI(QMainWindow): """控制台主界面。""" def __init__(self) -> None: super().__init__() self.__mode = Mode.UNICAST ...
8,017
2,971
""" -file concerned with implementation of GET /scans -should return as many scans as possible starting from newest -return size must be capped at 6mb """ from boto3.dynamodb.conditions import Key from lib.dynamodb import scans_table from lib.lambda_decorator.decorator import api_decorator, format_result BYTE_LIMIT =...
1,166
378
import logging from sparrow_cloud.restclient import rest_client from sparrow_cloud.restclient.exception import HTTPException from sparrow_cloud.utils.get_cm_value import get_cm_value logger = logging.getLogger(__name__) def access_verify(user_id, app_name, resource_code): """ access control verify """ ...
1,119
339
""" Open Test Arbatrage System USE AT YOUR OWN RISK! MULTIPLE EXCHANGE ACCEPTANCE ALLOWS 'USERS' TO CHOOSE THEIR OWN STRATEGY AS WELL AS TRADING COINS PROVIDES DETAILED INFORMATION ABOUT EXCHANGES & PLATFORMS ALLOWS USERS TO CONNECT IN A FRIENDLY ENVIRONMENT Author: ~Skrypt~ """ import sys import os impor...
29,735
9,440
from datetime import datetime from django.core.exceptions import ValidationError from fms_core.models import Container from ..containers import CONTAINER_KIND_SPECS def get_container(barcode): container = None errors = [] warnings = [] if barcode: try: container = Container.object...
7,097
1,797
import pytest import time from datetime import timedelta from typing import Optional, Dict, Any from whendo.core.util import Rez, SystemInfo, Now, KeyTagMode, DateTime, Rez from whendo.core.action import Action from whendo.core.server import Server from whendo.core.actions.list_action import ( UntilFailure, All...
32,053
10,610
import os from functools import reduce __here__ = os.path.dirname(__file__) TEST_DATA = '''\ 2199943210 3987894921 9856789892 8767896789 9899965678\ ''' def gen_neighbors(array, x, y): '''Generated points in north, south, east, and west directions. On edges only valid points are generated. ''' dir...
3,298
1,195
#!/usr/bin/env python """ This is the installation script of the step module, a light and fast template engine. You can run it by typing: python setup.py install You can also run the test suite by running: python setup.py test """ import sys from distutils.core import setup from step.tests import TestCommand...
2,046
541
#!/usr/bin/env python # -*- coding: utf-8 -*- import functools from flask import url_for, redirect, session def login_required(view): @functools.wraps(view) def _(**kwargs): if session.get('admin_name') is None: return redirect(url_for('admin_bp.admin_login')) return view(**kwargs...
335
113
from . import config, client, context from .client import APIClient from .context import ClientContext
104
25
ip = open("input.txt","r") lst = ip.readlines() lst.reverse() lst.insert(1,'\n') ip.close() op = open("output.txt",'w') op.write("".join(lst)) op.close()
158
71
from pathlib import Path from fhir.resources.codesystem import CodeSystem from oops_fhir.utils import CodeSystemConcept __all__ = ["EffectEstimateType"] _resource = CodeSystem.parse_file(Path(__file__).with_suffix(".json")) class EffectEstimateType: """ EffectEstimateType Whether the effect estimate...
3,006
794
from django.test import TestCase, Client from django.urls import reverse class TaskAboutViewsTests(TestCase): def setUp(self): self.guest_client = Client() @classmethod def setUpClass(cls): super().setUpClass() cls.about_views = { 'about:author': 'author.html', ...
1,361
385
""" user token @version: v1.0.1 @Company: Thefair @Author: Wang Yao @Date: 2019-11-17 15:21:11 @LastEditors: Wang Yao @LastEditTime: 2019-11-17 21:17:19 """ from functools import wraps from flask import request from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData from library.response.tfexcep...
1,937
652
from paa191t1.pph.pph_median import pph_median from paa191t1.tests.pph import TestPPHBase class TestPPHMedian(TestPPHBase): def setUp(self): self.pph = pph_median
178
80
# -*- coding: utf-8 -*- # Copyright 2019 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Artifacts service tests.""" from __future__ import print_function import json import os import shutil import mock from chro...
27,910
9,680
"""Helper for evaluation on the Labeled Faces in the Wild dataset """ # MIT License # # Copyright (c) 2016 David Sandberg # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software withou...
8,044
2,878