content
stringlengths
5
1.05M
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Copyright 2018 Digital Media Professionals Inc. 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/lice...
import click from fr.inria.npw import input_analyser from fr.inria.npw.errors import InputFileNotFoundError, OutputDirNotFoundError from fr.inria.npw.output_maker import create_output_files @click.command() @click.argument('input_file') @click.option('-o', '--output', 'output_dir', default='.', help="The directory i...
import os __version__ = '3.14' PHOTOLOGUE_APP_DIR = os.path.dirname(os.path.abspath(__file__))
import os import time import psutil import sys import atexit def GetDiskstate(): diskinfo = psutil.disk_usage('/') disk_str = str(int(diskinfo.total/1024/1024/1024))+"G" #disk_str += "-" #disk_str += str(int(diskinfo.used/1024/1024/1024))+"G" #disk_str += "-" #disk_str += str(int(diskinfo.free/...
# generated by datamodel-codegen: # filename: modular.yaml # timestamp: 1985-10-26T08:21:00+00:00 from __future__ import annotations from typing import Any, Dict, List, Optional from pydantic import BaseModel class CustomThing(BaseModel): attributes: Optional[Dict[str, Any]] = None class CustomThang(Bas...
from stv.tools.string_tools import StringTools class TmnProtocolIsplGenerator: # TODO: integrate with IsplGenerator class ispl_model = "" agents = ["alice", "bob", "server", "attacker"] no_messages = 3 def __init__(self): return def create_ispl_model(self): self.ispl_model +=...
""" Copyright (c) 2015 Red Hat, Inc All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. """ from __future__ import absolute_import, unicode_literals, print_function import pytest from osbs.conf import Configuration from osbs.api impo...
__________________________________________________________________________________________________ sample 32 ms submission # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def maxDepth(s...
import sys class HyperTrackException(Exception): ''' Base exception for all exceptions raised by HyperTrack library ''' def __init__(self, message=None, http_body=None, http_status=None, headers=None): super(HyperTrackException, self).__init__(message) if http_body an...
import random import numpy as np from logger import logger class Model(object): def __init__(self): pass class Kmean(Model): def __init__(self, k): super().__init__() self.k = k def _validate_data(self, X): pass def get_random_vector(self, dimension, low=0, high...
from torch.utils.tensorboard.writer import SummaryWriter, hparams from ice.llutil.argparser import args as ice_args class BoardWriter(SummaryWriter): def __init__(self, log_dir=None, comment='', purge_step=None, max_queue=10, flush_secs=120, filename_suffix=''): super().__init__(log_dir, comment, purge...
import hashlib import json from datetime import datetime, timedelta from pathlib import Path from typing import List import yaml from pydantic import Field from pydantic.main import BaseModel from stiltctl.meteorology import MeteorologyModel from stiltctl.simulations import AbstractReceptor, SimulationConfig, Surface...
print('='*10, 'Desafio Python 24','='*50) cidade = str(input('Em qual cidade você nasceu?')).strip() print(cidade) print(cidade[0:5].upper == 'SANTO') print('='*10, 'Desafio Python 24','='*50)
from __future__ import absolute_import, division, print_function class ImproperTestObject(Exception): pass class TestOctaneResource(object): TEST_RESOURCE_ID = "abc123" def _is_listable(self, request_mock): method = "get" url = self.BASE_URL request_mock.stub_request( ...
""" Copyright 2020-2021 Mikhail Paulyshka 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 agre...
''' $Id: interface.py 54 2010-02-22 02:33:10Z nikratio $ Copyright (c) 2010, Nikolaus Rath <Nikolaus@rath.org> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must ...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from . import ...
from ctseg.config import ex from ctseg.data_loader import DataLoader from ctseg.sampler import Sampler, OverlapSampler @ex.automain def main(model_config, data_config, num_classes, train_config, test_config): """Validate the train and validation datasets""" train_data_dir = train_config["inputs"]["data_dir"] ...
import functools import t5 import torch import transformers if torch.cuda.is_available(): device = torch.device("cuda") else: device = torch.device("cpu") model = t5.models.HfPyTorchModel("t5-base", "/tmp/hft5/", device) # Evaluate the pre-trained checkpoint, before further fine-tuning model.eval( "glue_col...
''' Package for built-in selection operators '''
''' if 100xp It's time to take a closer look around in your house. Two variables are defined in the sample code: room, a string that tells you which room of the house we're looking at, and area, the area of that room. Instructions Examine the if statement that prints out "Looking around in the kitchen." if room equal...
import os from .deviceflasher import DeviceFlasher from .versions import kanocode as kanocode_version class KanoCodeFlasher(DeviceFlasher): def run(self): firmware_path = os.path.join( os.path.dirname(__file__), 'firmware', 'rpk_{0}.bin'.format(kanocode_version) ...
# -*- coding: utf-8 -*- """ MIT License Copyright (c) 2017-2018 Roxanne Gibson 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 without restriction, including without limitation the rights to use...
# -*- coding: utf-8 -*- """ Copyright (c) Microsoft Open Technologies (Shanghai) Co. Ltd.  All rights reserved. The MIT License (MIT) 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 without restr...
#:coding=utf-8: from django.test import TestCase as DjangoTestCase from beproud.django.ssl.middleware import SSLProxyMiddleware from beproud.django.ssl.tests.base import request_factory class SSLProxyMiddlewareTest(DjangoTestCase): def test_secure(self): request = request_factory("get", "/path", X_HTTPS...
import numpy as np def sample_prob_picker_from_best(distribution, n=2): """ Select n top best probability in a distribution :param n: Number of best possible candidates :return: 1D vector with the selected item """ p = np.squeeze(distribution) p[np.argsort(p)[:-n]] = 0 p = p / np.sum(p)...
from zeta_basic.main import run def process_input(input): ## find PRINT statements if any statements = input.split(';') print_indexes = [] index = 0 for statement in statements: if 'PRINT' in statement: print_indexes.append(index) index +=1 ## pass cod...
import random from aiogram import types from constants.stickers import STIKERS, cant_hear_you from constants.text_messages import AUDIO_ANSWERS, DONT_WRITE_TO_ME from utils.loader import dp @dp.message_handler(content_types=types.ContentType.STICKER) async def catch_sticker(message: types.Message): await messag...
from datetime import datetime import pytest from pytz import utc from api.files.serializers import FileSerializer from api_tests import utils from osf_tests.factories import ( UserFactory, NodeFactory, ) from tests.utils import make_drf_request_with_version @pytest.fixture() def user(): return UserFactor...
# -*- coding: utf-8 -*- """ Part of the jastor library for Java AST manipulation. Jastor is a port to Java of the astor library for Python AST manipulation. License: 3-clause BSD For Astor Copyright (c) 2015 Patrick Maupin For Jastor Copyright 2021 (c) CEA LIST (Gaël de Chalendar) Pretty-print strings for the dec...
import os import shutil from pathlib import Path from typing import Union import requests def download_file( url: str, path: Union[Path, str] = Path("."), override: bool = False ) -> str: local_filename = f"{str(path)}/{url.split('/')[-1]}" if os.path.exists(local_filename) and not override: rais...
import logging import traceback import settings from matched_or_regexed_in_list import matched_or_regexed_in_list LOCAL_DEBUG = False # @added 20210518 - Feature #4076: CUSTOM_STALE_PERIOD # Branch #1444: thunder def custom_stale_period( current_skyline_app, base_name, external_settings={}...
# the name of allah # designed by MrZahaki # !/usr/bin/env python3.8 import socket import os import subprocess class DeleteError(Exception): pass class Tools: # convert a number to list of bytes @staticmethod def number_to_bytes(num): buf = [] while num: ...
# -*- coding: utf-8 -*- ''' 本地配置 ''' # 指定bilibili登录用户名密码 BILIBILI_USERNAME = '****' BILIBILI_PASSWORD = '****' # 头像存储路径 IMAGES_STORE = '../face_image/' # 指定连接到redis时使用的端口和地址 # 与代理ip公用设置 REDIS_HOST = 'Host ip' REDIS_PORT = 6379 REDIS_PASSWORD = 'if no password put None' REDIS_PROXY_DB = 'db' # Redis 存储键 REDIS_ST...
import abc import collections import collections.abc import csv from math import floor import io import itertools from itertools import zip_longest import json import os import re import shutil import sys import textwrap from typing import Callable, Optional, Type, Union from .record import Record, Header, HasHeader ...
DEFAULT_CONFIG_NAME = "config.yaml" # DEFAULT_DB = ":memory:" DEFAULT_DB = "sqlite.db" PLAYLIST_SIZE = 100 PLAYLIST_NAME = "A Random randomness" DEFAULT_WEB_PORT = 5842 DEFAULT_WEB_HOST = "localhost" # MORE INFO https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.6.1.1 CONFIG_SCHEMA = { "$...
def f(): print('In function f') print('When does this print?') f()
import sys import json import collections actual = sys.argv[1] expect = sys.argv[2] with open(actual) as file_actual: json_actual = json.loads(file_actual.read()) with open(expect) as file_expect: json_expect = json.loads(file_expect.read()) def almost_equal(x, y, threshold=0.05): return abs(x-y) < threshold ...
class my_clsss: def __init__(self): self.data=21 def print_data(self): print(self.data) my_cl = my_clsss() my_cl.print_data() a = [] a+=[1] print a
import os from cbt.private_client import PrivateClient from cbt.auth import get_new_private_connection if __name__ == "__main__": usd = os.getenv("USD_SELL") auth = get_new_private_connection() client = PrivateClient(auth) client.market_sell_btc(usd)
# pip install PyOpenGL # pip install pygame # pip install pygame==2.0.0.dev6 (for python 3.8.x) # pip install numpy # Python 3.8 from OpenGL.GL import * from OpenGL.GLUT import * from OpenGL.GLU import * import pygame from pygame.locals import * import math import random as rdn import numpy as np ### Algorithm ### ...
import os import pytest def pytest_addoption(parser): parser.addoption("--runslow", action="store_true", help="run slow tests") parser.addoption("--tctquiet", action="store_true", help="hide debug logging") parser.addoption( "--save-golden-masters", action="store_true", help="reset golden m...
# -*- coding:utf-8 -*- # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # This program is free software; you can redistribute it and/or modify # it under the terms of the MIT License. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the ...
from suricate.data.companies import getXst, getytrue from suricate.explore import Explorer, KBinsCluster, cluster_matches, cluster_stats from suricate.dftransformers import DfConnector, VectorizerConnector, ExactConnector from sklearn.pipeline import Pipeline, FeatureUnion from sklearn.impute import SimpleImputer from ...
""" Go to sleep unless something is keeping us awake """ import ulogging import utime _logger = ulogging.getLogger('eng.sw.sleepy') _logger.setLevel(ulogging.INFO) _users = {} _indicator = None def init(indicator): global _indicator #pylint: disable=global-statement _indicator = indicator if _indicato...
from tree import BinaryTree def tree_intersection(treeOne, treeTwo): if not treeOne or not treeTwo: return None values = dict() def walk(root): if not root: return values[root.value] = values.get(root.value, 0) + 1 walk(root.left) walk(root.right) ...
# Copyright (c) 2003-2019 by Mike Jarvis # # TreeCorr is free software: redistribution and use in source and binary forms, # with or without modification, are permitted provided that the following # conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of condi...
from .api import api_routes from .ui import license_verificiton_ui_bp
__author__ = 'lqrz' import os import sys from sklearn.decomposition import PCA as sklearnPCA from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.mplot3d import proj3d import numpy as np import pickle import random from nltk import FreqDist from nltk.corpus import PlaintextCor...
from setuptools import setup, find_packages setup( name="test_package", version="0.0.1", author="Tonye Jack", author_email="jtonye@ymail.com", install_requires=['requests'], packages=find_packages(), )
#Faça um Programa que peça um número e então mostre a # mensagem O número informado foi [número]. n = int(input("Informe um um valor:")) print("O número informado foi",n)
import os import socket from django.views import View from django.shortcuts import render """ RedisActiveConnections RedisCommands RedisConnects RedisUsedMemory RedisSize """ class RedisGrafanaMetric(View): category = "Redis" def autoconf(self): try: self.get_info() except socket...
import base64 def custom_jinja2_filter(string): """encodes a string using base64 schema""" return base64.b64encode(string.encode("UTF-8")).decode("UTF-8")
import h5py import numpy as np # This piece of code tests the ability to create a h5py file, append data to it, close it, then open # it again... USE_TITANX = False video_1 = np.random.rand(4,224,224,3) video_2 = np.random.rand(10,224,224,3) video_3 = np.random.rand(23,224,224,3) audio_vector_1 = np.random.rand(4,18...
import os import os.path as op import re import argparse import pathlib from ando.rulesStructured import RULES_SET def is_valid(input_directory): """Checks the validity of a data set with respect to the BIDS-animal-ephys specifications. The specifications that define what is checked by this function is avail...
def tag(tag, content, debug=False): """ Function to display a tag :param tag: the tag to display :param content: the attribut :param debug: activate debug display """ if debug: print("<{0}>{1}</{0}>".format(tag, content), end='\n') def start_title(title, debug=False): """ Fu...
import bitarray import math import mmh3 class BloomFilter(object): def __init__(self, capacity, error=0.005): self.capacity = capacity self.error = error self.num_bits = int(-capacity * math.log(error) / math.log(2)**2) + 1 self.num_hashes = int(self.num_bits * math.log(2) / ...
# ------------------------------------------------------------------------- # # Part of the CodeChecker project, under the Apache License v2.0 with # LLVM Exceptions. See LICENSE for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception # # ---------------------------------------------------...
# -*- coding: utf-8 -*- # Copyright (c) 2020, msmr.ch and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document class DPNachricht(Document): def validate(self): if not self.ungelesen: users = frappe.db.sql(...
import math import os import numpy as np import pandas as pd from tensorflow.python.keras.metrics import AUC, Precision from sklearn.preprocessing import StandardScaler from sklearn.preprocessing import LabelEncoder from sklearn.metrics import roc_auc_score, roc_curve from tensorflow.python.keras.callbacks import Call...
import re EMAIL_REGEX = re.compile(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)") HTTP_URL_REGEX = re.compile( r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+" ) CONTENT_DISPOSITION_REGEX = re.compile(r"filename=[\"|\']?(?P<file_name>.*)[\"|\']$") CONTENT_DISPOSITION_WITH...
def gcd(a, b): while b != 0: t = a a = b b = (t % a) return a print(gcd(60, 96))
""" Pyjamas UI BuilderWidget: takes a PyJsGlade builder spec and creates a widget. Copyright (C) 2010 Luke Kenneth Casson Leighton <lkcl@lkcl.net> Create a BuilderWidget as follows:: from pyjamas.builder.Builder import Builder from pyjamas.ui.BuilderWidget import BuilderWidget either:: class Applicatio...
class Solution: # @return a boolean def isValid(self,s): stack = [] for c in s: if ((c == '(') or (c == '{') or (c == '[')): stack.append(c) elif (c == ')'): if ((not len(stack)) or stack.pop() != '('): return False ...
# Note, None instead of a literal [] def append_to(element, to=None): if to is None: # test if None to = [] to.append(element) return to # Expect an explanation around compile time instantiation vs runtime. # Next step is to have the candidate work through the UTs and explain how they work. ...
''' Uma brincadeira muito comum e divertida entre dois jogadores usa uma moeda e três copos opacos (ou seja, não é possível ver o que está dentro do copo olhando pela lateral do copo). Os três copos são colocados com a boca para baixo, em uma linha, um ao lado do outro, em posições que vamos chamar de A, B e C. Uma m...
import numpy as np import pytest import scipy.stats as st import utils def test_central_credible_interval_cont(): xs = np.linspace(0, 1, 100000) a, b = 2, 6 # arbitrary positive numbers dist = st.beta(a, b) pdf = dist.pdf(xs) alpha = 0.05 lb, ub = utils.central_credible_interval(xs, pdf, alp...
import mock from rest_framework import status, test from nodeconductor.structure.tests import factories as structure_factories from nodeconductor.structure import models as structure_models from nodeconductor_plus.premium_support import models as support_models from nodeconductor_plus.premium_support.tests import fac...
import datetime from sqlalchemy.dialects.mysql import TINYTEXT from server import db from server.model import BaseModel, PermissionBaseModel class Milestone(BaseModel, PermissionBaseModel, db.Model): __tablename__ = "milestone" id = db.Column(db.Integer(), primary_key=True) name = db.Column(db.String(64...
from django.db import models class Lugat(models.Model): inglizcha = models.CharField('Inglizcha', max_length=130) uzbekcha = models.CharField('Uzbekcha', max_length=130) class Meta: verbose_name = "Lugat" verbose_name_plural = "Lugatlar"
class Solution: def removeCoveredIntervals(self, intervals: List[List[int]]) -> int: cnt = 0 n = len(intervals) for i in range(n): a, b = intervals[i] if not any(intervals[j][0] <= a and b <= intervals[j][1] for j in range(n) if j != i): cnt += 1 ...
from django.contrib import admin # Register your models here. from .models import ( GreensRolling, TeeRolling, FairwayRolling ) admin.site.register(GreensRolling) admin.site.register(TeeRolling) admin.site.register(FairwayRolling)
from typing import Optional import frappe from frappe_notification import ( NotificationClientNotFound, NotificationOutbox, NotificationOutboxNotFound, get_active_notification_client) def mark_log_seen( outbox: str, channel: Optional[str] = None, channel_id: Optional[str] = No...
# Copyright (c) Vera Galstyan Jan 2018 favorite_numbers = { 'sam':5, 'vera': 13, 'ofa':1, 'karen':7, 'mama': 5, } print("Samvel's favorite number is " + str(favorite_numbers['sam'])) print("Ofa's number is " + str(favorite_numbers['ofa'])) print("Karen likes " + str(favorite_numbers['karen'])) print(favorite_numbe...
import os, sys project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, project_root) sys.path.insert(1, project_root + '/fairseq') sys.path.insert(2, project_root + '/fairseq/scripts') # Add to $PYTHONPATH in addition to sys.path so that ray workers can see os.environ['PYTHONPATH']...
#!/usr/bin/env python from mycollections import FilteredCollection import unittest __author__ = 'kinpa200296' def get_sequence_of_size(sequence, size): res = [] for x in sequence: if size > 0: res.append(x) else: return res size -= 1 class TestFilteredCollec...
author__ = 'paulbaker' ''' get the packt book of the day ''' import requests from lxml import html import re ''' def login_to_packt() def load_promotional_page(page_url='https://www.packtpub.com/packt/offers/free-learning'): pass '''
def invert(d): return dict( (v,k) for k in d for v in d[k] )
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """This folder contains all the Sieve managers for DDOS simulation""" __Lisence__ = "BSD" __maintainer__ = "Justin Furuness" __email__ = "jfuruness@gmail.com, agorbenko97@gmail.com" __status__ = "Development" from .sieve_manager_v0 import Sieve_Manager_V0_S0, Sieve_Man...
""" @brief test log(time=5s) """ import os import unittest from pyquickhelper.loghelper import fLOG, CustomLog from pyquickhelper.pycode import is_travis_or_appveyor from pymyinstall.packaged import small_set from pymyinstall.installhelper import get_wheel_version, compare_version from pymyinstall.installhelper.m...
#!/usr/bin/env python3 import argparse import getpass import json import logging import socket import sys from channels import PipeChannel, SocketChannel from channels.poller import Poller from utils import timeout _LOGGER = logging.getLogger(__name__) _POLLER = Poller() _STDIO = None _ROUTER = None _USER = getpas...
import torch from torch import nn from torch.utils.data import DataLoader import numpy as np from models.BaseModel import BaseModel from overrides import overrides import matplotlib.pyplot as plt plt.rcParams['image.cmap'] = 'gray' def show_images(images): sqrtn = int(np.ceil(np.sqrt(images.shape[0]))) for ...
import akshare as ak epidemic_dxy_df = ak.epidemic_dxy(indicator="global") epidemic_dxy_df.to_excel('epidemic_dxy.xlsx')
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. @Author Eric Bianchi """ import os import shutil import cv2 import numpy as np from PIL import Image import random from tqdm import tqdm def buildImageFileList(BASE, TEST_IMAGES_DIR, sort_ID_string): imageFilePaths = [] image_nam...
import pytest from click.testing import CliRunner from mr_proper.main import main @pytest.mark.parametrize( 'file_or_directory_path, check_result', [ ('/test/test_files/dir_not_exist/', 'does not exist'), ('/test/test_files/file_not_exist.py', 'does not exist'), ('tests/test_files/tes...
from setuptools import setup setup(name='pymasker', version='0.4.0', description='python package for mask generation from landsat 8 Quality Assessment band and MODIS land products.', url='https://github.com/haoliangyu/pymasker', author='Haoliang Yu', author_email='haoliang.yu@outlook.com'...
import copy import logging import pandas as pd import time from core.libs.error import get_job_error_desc from core.libs.task import taskNameDict from core.settings.local import defaultDatetimeFormat import core.constants as const _logger = logging.getLogger('bigpandamon') def get_error_message_summary(jobs): ...
# -*- coding: utf-8 -*- # %% import matplotlib.pyplot as plt import numpy import numpy as np def amplification_factor(A, b, z): lhs = (numpy.eye(N=A.shape[0]) - z * A) lhs_inv = np.linalg.inv(lhs) rhs = z * numpy.ones(shape=(A.shape[0],)) k_vec = numpy.matmul(lhs_inv, rhs) y_1 = 1.0 + numpy.matmul...
import argparse parser = argparse.ArgumentParser(prog='train.py') '-----------------------------------training-----------------------------------------' parser.add_argument('--epochs', type=int, default=273) # 500200 batches at bs 16, 117263 images = 273 epochs parser.add_argument('--batch-size', type=int, default=...
#!/usr/bin/env python from NVMeshSDK.Utils import Utils from NVMeshSDK.Entities.Entity import Entity from NVMeshSDK.Entities.AttributeRepresentation import AttributeRepresentation class ClientsStatus(Entity): Total = AttributeRepresentation(display='Total', dbKey='totalClients') Offline = AttributeRepresentat...
from django.contrib import admin from .models import ( Pest, ChemManufacturer, Chemical, TradeChem, Spraying, ChemUsedInSpray, GreensSpraying, TeeSpraying, FairwaySpraying, RoughSpraying ) admin.site.register(Pest) admin.site.register(ChemManufacturer) admin.site.register(Chemi...
#!/usr/bin/env python import argparse import time import numpy as np from chainer import cuda from chainer import optimizers parser = argparse.ArgumentParser( description=' convnet benchmarks on imagenet') parser.add_argument('--arch', '-a', default='alexnet', help='Convnet architecture \ ...
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # http://www.sphinx-doc.org/en/master/config # -- Path setup -------------------------------------------------------------- # If extensions (or module...
import serial import cv2 as cv import numpy as np from matplotlib import pyplot as plt import subprocess from filters import SharpenFilter from edgeDetect import warpImg, getRequiredContours, euclideanDist from skimage.metrics import structural_similarity as compare_ssim SKIP_STATE_ID = 24 # skip id=24, because i...
import pytest import numpy as np import pandas as pd from mystique.match import array_matches def test_array_matches(int_array): """Test matching of arrays""" array1 = int_array[0] array2 = np.zeros(4) array3 = np.array([1, 3, 5, 7]) assert np.array_equal(array_matches(array1, int_array), np.arr...
import pytest pytestmark = pytest.mark.sphinx('html', testroot='events') @pytest.mark.parametrize('page', ['index.html', ], indirect=True) class TestEvents: def test_events(self, page): title = page.find('title').contents[0].strip() assert 'index' == title bi = page.find(id='bi').conten...
from tools import jsonl from uuid import uuid4 as uuid import os import shutil def strip_non_alphanum(string): return ''.join( c for c in string if c.isalnum() or c == ' ' or c == "'" ) def strip_non_ascii(string): return ''.join(c for c in string if 0 < ord(c) < 127) print('conv...
print("hello world") def f(): print("han hai yan") if __name__ == "__main__": for i in range(1,10): for j in range(1,i +1): print("%d*%d=%2d" % (i, j, i * j), end=" ") f() print() i = 1 while i < 6: j = 0 while j < i: print("* ", end=" ") j += 1...
import re from lib.modules.DetectionModule import * class Module(DetectionModule): def __init__(self, name, event_json): super().__init__(name=name, event_json=event_json) def run(self): self.logger.debug('Running the {} detection module'.format(self.name)) # Loop over each sandboxe...
def firstDigit(inputString): """Finds leftmost digit that occurs in a given string Args: inputString(string): input string Return: Leftmost digit occurring in string Raises: """ for char in inputString: if char.isdigit(): return char