content
stringlengths
5
1.05M
import json import unittest from yoti_python_sdk.doc_scan.session.create import RequestedFaceMatchCheckBuilder from yoti_python_sdk.doc_scan.session.create.check.face_match import ( RequestedFaceMatchCheck, ) from yoti_python_sdk.doc_scan.session.create.check.face_match import ( RequestedFaceMatchCheckConfig, ...
def futdados(nome='Desconhecido', gols=0): if str(gols).isnumeric(): gols = 0 return f'O jogador {nome} fez {gols} gol(s) no campeonato.' nome = str(input('Nome do jogador: ')) gols = str(input('Quantidade de gols: ')) print(futdados(nome, gols))
from rest_framework import serializers from content.serializers import ContentBaseSerializer from generic.contenttypes_utils import reverse_contenttypes_url, add_contenttypes_info_from_context from .models import * class SerializerCommentsFieldMixin(serializers.Serializer): ''' Adds fields 'comments' for hyp...
from embedKB.models.base import GeneralFramework import tensorflow as tf class SingleLayer(GeneralFramework): name = 'SingleLayer' def __init__(self, n_entities, entity_embed_dim, n_relationships, relationship_dim, relationshi...
from discord.ext import commands class Error(commands.Cog): """Basic class for catching errors and sending a message""" def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_command_error(self, ctx, error): if isinstance(error, commands.ExpectedClosingQuoteErr...
from WumpWorld import * import random """ This is an alternative agent that uses less information than regular Agent. It will be used as a control for comparisons. """ class ReactiveAgent: def __init__(self, world, x, y, arrows): self.world = world self.pos = [x,y] self.arrows = arrows ...
number = input("Write a decimal number to be converted to binary \n") binary = [] rest = int(number) while rest != 0: if rest % 2 == 0: binary.append(str(0)) rest = rest/2 else: binary.append(str(1)) rest = (rest - 1) / 2 print(''.join(binary[::-1]))
# Copyright (c) 2015 Infoblox 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 require...
# question can be found on leetcode.com/generate-a-string-with-characters-that-have-odd-counts/ class Solution: def generateTheString(self, n: int) -> str: if n // 2 == 1: return "a" * (n - 2) + "b" + "c" else: return "a" * (n - 2) + "b"
import torch import torchvision import torchvision.transforms as transforms import numpy as np from halp.utils.utils import LP_DEBUG_EPOCH_LEN, DOUBLE_PREC_DEBUG_EPOCH_LEN import sys import logging logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) logger = logging.getLogger('') def get_cifar10_data_loader(b...
from backend.categories import Category from backend.core import Project def create_context(): context = { 'categories': Category.objects.all().prefetch_related('projects'), 'projects': Project.objects.all().select_related('category'), } return context
# Copyright 2015-2016 Rick Harris # # 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 agree...
import sys import os from torch.nn.functional import dropout from nbvnet import NBV_Net import torch import numpy as np import time def get_single_view_point(path): net = NBV_Net(dropout_prob=0) checkpoint = torch.load('my_checkpoint.pth.tar',map_location = torch.device('cpu')) net.load_state_di...
#!/usr/bin/python # brokergroupform_main.py # Form to collect params for PreservationSimulation broker.py main UI page. # Creates the crazy way-too-large form of broker options. # Runs the program and may collect the results to show on the page. import os from bottle import route, run, template, request, get, post, \ ...
from django.conf import settings from django.contrib.auth.decorators import login_required from django.core.paginator import Paginator from django.shortcuts import get_object_or_404, redirect, render from .forms import CommentForm, PostForm from .models import Group, Post, User, Follow def index(request): post_l...
import torch from torch.autograd.function import Function, InplaceFunction, once_differentiable from torch._thnn import type2backend class GRUFused(Function): @staticmethod def forward(ctx, input_gate, hidden_gate, hx, ibias=None, hbias=None): ctx.backend = type2backend[type(input_gate)] hy =...
import os from http.server import HTTPServer try: import threading except ImportError: import dummy_threading as threading from socketserver import TCPServer import time import pytest from pyzabbix import ZabbixAPI from epics import ca from . import zbxstreamserver from .ioccontrol import IocControl from .zbx...
from flask import render_template, request from flask.ext.login import login_required, current_user from flask.json import jsonify import rfk.database from rfk.site.helper import permission_required, emit_error from rfk.database.show import Tag from rfk.helper.taglist import taglist from ..admin import admin @admi...
#!/usr/bin/env python # encoding: utf-8 """ @version: python.3.6 @author: zhangjiaheng @software: PyCharm @time: 2017/9/19 10:55 """ from selenium import webdriver import os #截图函数 def insert_img(driver,file_name): base_dir = os.path.dirname(os.path.dirname(__file__)) base_dir = str(base_dir) base_dir = ba...
from bokeh.embed import components from bson import ObjectId from flask import Blueprint, render_template, request, session, url_for, flash from pymodm.errors import ValidationError from werkzeug.utils import redirect, secure_filename from newsgac.common.back import back from newsgac.pipelines.models import Pipeline f...
""" Given a binary tree, return all root-to-leaf paths. Note: A leaf is a node with no children. Example: Input: 1 / \ 2 3 \ 5 Output: ["1->2->5", "1->3"] Explanation: All root-to-leaf paths are: 1->2->5, 1->3 Solution: 1.DFS with recursion 2.BFS with stack [(node, current path)] """ # Definition...
import inspect import os import sys from abc import ABC, abstractmethod from itertools import cycle from functools import partial from typing import Sequence, Tuple, Union, Optional import numpy as np import tensorflow as tf from box import Box from tensorflow.image import resize, random_crop from tensorflow.keras.pre...
#storage for simple assets import quandl import pandas as pd try: from quandl_set import * except: pass def WR(data,period): rhmax = data.Adj_High.rolling(window = period,center = False).max() rmmin = data.Adj_Low.rolling(window = period,center = False).min() return (rhmax-data.Adj_Close)/(rhmax-r...
# Copyright (c) 2021 Alethea Katherine Flowers. # Published under the standard MIT License. # Full text available at: https://opensource.org/licenses/MIT import argparse import sys import PIL.Image import PIL.ImageDraw import phomemo_m03.printer import phomemo_m03._image_helper def _テストイメージ生成(幅): 生成イメージ = PIL....
"""Collision geometry representation for multibody systems. Each type of collision geometry is modeled as a class inheriting from the ``CollisionGeometry`` abstract type. Different types of inheriting geometries will need to resolve collisions in unique ways, but one interface is always expected: a list of scalars to ...
""" * The TE_detect class unlatches a backup battery and allows the mission_control program to continue * Author: Aaron Borger <aborger@nnu.edu (307)534-6265> """ import RPi.GPIO as GPIO #GPIO.setmode(GPIO.BCM) INPUT_PIN = 16 LATCH_PIN = 19 class TE_detect: def __init__(self): pass #GPIO.set...
import cv2 import numpy as np import scipy.fftpack from helper_geometry import order_points, line_length def four_point_transform(image, quad): rect = order_points(quad) # compute the width of the new image, which will be the # maximum distance between bottom-right and bottom-left # x-coordiates or the...
################################################################################ # JobBoard: a simple Django-based job board # Copyright (c) 2009, Imaginary Landscape # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided...
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String, ForeignKey, Table, create_engine, exists, and_, func from sqlalchemy.orm import relationship, sessionmaker import os from time import sleep def clear(): return os.system('cls') # Connection keys = { 'DBM...
""" =========================== @-*- coding: utf-8 -*- @ author: Shibo Zhou @ time: :10:08, Oct 16 2021 @ email: szhou19@binghamton.edu =========================== """ import torch from torch import nn from torch.autograd import Variable import pandas as pd import numpy as np import matplotlib as plt from...
# encoding: utf8 import os import sys import unittest import tkinter as tk import tkinter.ttk as ttk pygubu_basedir = os.path.abspath(os.path.dirname( os.path.dirname(os.path.realpath(sys.argv[0])))) if pygubu_basedir not in sys.path: sys.path.insert(0, pygubu_basedir) import pygubu import support class Tes...
import sqlScripts import config def createhdctTable(): sql_create_ichg_table = "CREATE TABLE " + config.table1 + """ ( );""" # create a database connection sql_create_detail_table = "CREATE TABLE " + config.table2 + """ ( ...
""" Discussion: This has got to do with which part of the input current distribution is transferred to the spiking activity. Intuitive understanding is difficult but this relationship arises due to non-linearities in the neuron F-I curve. When F-I curve is linear, output correlation is independent of the mean and...
import unittest from StringIO import StringIO from textwrap import dedent import newick import numpy as np from least_squares_fit import post_order, read_distance_matrix class DistanceMatrixTest(unittest.TestCase): def setUp(self): newick_str = '(((A:1, B:2)I:3.5, (C:4, D:5)J:6), E:7)K;' self.tre...
/home/runner/.cache/pip/pool/ed/03/90/3c98fa7b3215b32a4926b732caae3e98933da94b0e74e2ead3fc148800
import requests from bs4 import BeautifulSoup headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,...
from django.contrib import admin from django.contrib.contenttypes import generic from django.forms.widgets import HiddenInput from django.db.models import PositiveIntegerField from relatedcontent.models import RelatedContent, Webpage class RelatedContentInline(generic.GenericTabularInline): classes = ('collapse c...
# -*- coding: utf-8 -*- from datetime import timedelta from django.test import TestCase from django.urls import reverse from django_dynamic_fixture import fixture, get from readthedocs.gold.models import LEVEL_CHOICES, GoldUser from readthedocs.projects.models import Project from readthedocs.rtd_tests.utils import cr...
""" Copyright (c) 2016-2019 Keith Sterling http://www.keithsterling.com 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, copy, m...
from torch.utils.data import Dataset from PIL import Image import os import torch label_map = { 150 : "001.Black_footed_Albatross", 0 : "002.Laysan_Albatross", 138 : "188.Pileated_Woodpecker", 1 : "003.Sooty_Albatross", 151 : "004.Groove_billed_Ani", 2 : "005.Crested_Auklet", 152 : "006.Least_Auklet", 3 : "0...
from matplotlib import cm from matplotlib.pyplot import subplots, show from numpy import linspace, bincount, hstack, cumsum from numpy.random import rand, random_integers import numpy as np print(__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn import svm, datasets from sklear...
from functools import partial import gin import haiku as hk import jax import jax.numpy as jnp import spax from huf import initializers from huf.module_ops import dropout from jax.experimental.sparse.ops import COO from grax.projects.gat import ops as gat_ops configurable = partial(gin.configurable, module="gat") ...
# -*- coding: utf-8 -*- """ Created on Wed Apr 17 17:17:07 2019 @author: netzer The script lets you dump a portion of transaction data stored in a MySQL db into a csv file without getting into troubles with the cache (if the portion is huge). The input consists of 2 dates ('YYYY-MON-DAY') i.e. the date rang...
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-12-01 20:09 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('golf', '0068_auto_20171201_2008'), ] operations = [ migrations.AddField( ...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import operator import collections import math import os import random import zipfile import time import numpy as np from six.moves import urllib from six.moves import xrange # pylint: disable=redefined-builtin...
import os import logging from brainio import brainio from imlib.register.niftyreg.transform import run_transform from neuro.atlas_tools.paths import INVERSE_CONTROL_POINT from neuro.atlas_tools.paths import BRAIN_FILTERED as default_atlas_name def get_registered_image(nii_path, registration_dir, overwrite=False): ...
DEBUG = True ALLOWED_HOSTS = ["yourcomputer", "yourcomputer.local", "localhost", "127.0.0.1", "::1"] DATABASES = { "default": { "ENGINE": "django.db.backends.mysql", "NAME": "dracidoupe_cz", "USER": "root", "HOST": "db", "PASSWORD": "docker", "OPTIONS": {"charset": ...
#!/usr/bin/python3 import os import sys #apt install python3-mysqldb import MySQLdb import time import logging import fcntl ##########MYSQL## #classes################################# class astm_file(object): def get_link(self,my_host,my_user,my_pass,my_db): con=MySQLdb.connect(my_host,my_user,my_pass,my_db) ...
import glob import time import sys from lib import command from callbackFunc_multi import xbee_received import datetime import serial import shared_multi as shared from struct import pack,unpack from xbee import XBee from math import ceil,floor import numpy as np import scipy.io # TODO: check with firmware if this val...
def findDecision(obj): #obj[0]: Passanger, obj[1]: Weather, obj[2]: Temperature, obj[3]: Time, obj[4]: Coupon, obj[5]: Coupon_validity, obj[6]: Gender, obj[7]: Age, obj[8]: Maritalstatus, obj[9]: Children, obj[10]: Education, obj[11]: Occupation, obj[12]: Income, obj[13]: Bar, obj[14]: Coffeehouse, obj[15]: Restaurantl...
import webbrowser googleUrl: str = 'https://google.com/search?q=' ytUrl: str = 'https://youtube.com/results?search_query=' githubUrl: str = 'https://github.com/search?q=' soUrl: str = 'https://stackoverflow.com/search?q=' amz_inUrl: str = 'https://www.amazon.in/s?k=' amz_comUrl: str = 'https://www.amazon.com/s?...
""" stuff to run behave programmatically """ import os import logging import json from behave import step_registry from behave.configuration import Configuration, ConfigError from behave.tag_expression import TagExpression from behave.parser import ParserError from behave.runner_util import FileNotFoundError,\ Inv...
# Generated by Django 3.1.6 on 2021-02-13 13:52 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('account', '0001_initial'), ] operations = [ migrations.AddField( model_name='user', name='description', ...
""" Function to node transformer """ import ast import inspect from textwrap import dedent from uuid import uuid4 from lute.node.base import Constant, Node, NodeMeta def is_lambda(v) -> bool: """ Check for lambda. From https://stackoverflow.com/a/3655857 """ LAMBDA = lambda: 0 return isinstance...
from django.apps import AppConfig class WeatherAverageConfig(AppConfig): name = 'average_temperature'
from django.contrib.auth.models import AbstractUser from django.core.validators import ( MaxLengthValidator, MinLengthValidator, RegexValidator, ) from django.db import models from django.utils.translation import gettext_lazy as _ from zeynep.auth.models.managers import UserManager from zeynep.auth.models....
# V0 # V1 # https://blog.csdn.net/fuxuemingzhu/article/details/83422260 class Solution(object): def longestMountain(self, A): """ :type A: List[int] :rtype: int """ N = len(A) inc = [1] * N dec = [1] * N for i in range(1, N): if A[i] - A...
#!/usr/bin/env python3 import getpass import os import websockets import ssl import asyncio import socket import sqlite3 import json import configparser import daemon from mattermostdriver import ( Driver, Websocket, ) config = configparser.ConfigParser() config.read("/etc/mattermost_daemon/config.ini") matt...
import os import shutil import unittest import warnings from eskapade import ConfigObject from eskapade import process_manager from eskapade import resources from escore.core import execution, definitions, persistence from eskapade.logger import LogLevel class IntegrationTest(unittest.TestCase): """Base class for...
class Solution: def cleanStr(self, str) -> str: while '#' in str: for i in range(0, len(str)): if str[i] == '#': if i==0 and len(str)>1: return self.cleanStr(str[i+1:]) elif i==0: return self....
def main(): n=int(input()) a=list(map(int, input().split())) mp=(None,None) d=0 for i in range(0, n-1, 2): if a[i+1] - a[i] > d: mp=(i,i+1) a[mp[0]], a[mp[1]] = a[mp[1]], a[mp[0]] print(sum(a[::2])) if __name__ == '__main__': t=int(input()) for _ in range...
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2018-03-03 22:28 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('gravity', '0002_tilt'), ] ...
#!/usr/bin/env python from jinja2 import Template template = Template(open("story-long.jinja2").read()) story_vars = { "c1": { "title": "Princess", "name": "Clara", "p": "she", "relation": "sister" }, "c2": { "title": "Prince", "name": "Arthur", "p": "he", "relation": "brother" }, "v1": { "tit...
import asyncio import yaml from discord.ext import commands from aiohttp import web class WebServer(commands.Cog): def __init__(self, bot): self.bot = bot self.app = web.Application() self.app.router.add_get("/", self.index) self.app.router.add_get("/guilds", self.guild_count) ...
# -*- coding: utf-8 -*- """ TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-节点管理(BlueKing-BK-NODEMAN) available. Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance ...
# encoding: utf-8 """ @author: zijun @contact : zijun_sun@shannonai.com @version: 1.0 @file: accuracy @time: 2020/7/11 11:51 """ from typing import Any, Optional import torch from pytorch_lightning.metrics.functional.classification import ( accuracy ) from pytorch_lightning.metrics.metric import TensorMetric ...
""" Implements various flows. Each flow is invertible and outputs its log abs det J^-1 "regularization" via the log_det method. The Jacobian's determinant measures the local change of volume (due to stretching or squashing of space) under the flows transformation function y = f(x). We take the inverse Jacobian because...
import torch from torch.utils.data import Dataset class Memory(Dataset): def __init__(self, states, actions, log_probs, rewards, advantages, values) -> None: super().__init__() self.states = states self.actions = actions self.log_probs = log_probs self.rewards = rewards ...
# -------------- import numpy as np import pandas as pd from sklearn.model_selection import train_test_split # path- variable storing file path #Code starts here df = pd.read_csv(path) df.head() X=df.drop(['Price'],1) y=df['Price'].copy() X_train, X_test, y_train, y_test= train_test_split(X,y, test_size=0....
""" training script for the proposed model. author: David-Alexandre Beaupre date: 2020-04-29 """ import os import argparse import time as t import datetime as dt import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.optim as optim import utils.misc as misc from datahandler.LITIV import LIT...
import requests from .baseclient import AbstractClient import requests.packages.urllib3 requests.packages.urllib3.disable_warnings() class Client(AbstractClient): def __init__(self, verify_ssl_cert=False): self.verify_ssl_cert = verify_ssl_cert super(Client, self).__init__() def post(self, u...
"""Music app models""" import os from django.db import models def music_model_filepath(instance, filename): """Returns a filename for music instance""" if instance.__class__.__name__ == 'Artist': path = 'artists/images' elif instance.__class__.__name__ == 'Song': path = 'songs' elif ...
import time import subprocess import statistics from sensors import measdist from sensors import sensorscleanup def measdist_stat(): # collect multiple measurements and calculate statistics x = [0] * 20 # specify the statistics length here for i in range(0, len(x)): x[i] = measdist() return (statistics.mea...
# -*- coding: utf-8 -*- """ @date: 2020/12/30 下午6:48 @file: general_head_2d.py @author: zj @description: """ from abc import ABC import torch import torch.nn as nn from .. import registry class GeneralHead2D(nn.Module, ABC): def __init__(self, feature_dims=1024, dropout_rate...
# -*- coding: utf-8 -*- """ Created on Thu Oct 22 13:57:56 2020 @author: Arif """ ''' This script performs quantitave evaluation of the camera poses obtained by 3D reconstruction softwares Agisoft of Photoscan and Meshroom of Alicevision from the synthetic (Blender) stacked images for both moving and fixe...
ADAPTER_API_KEY = "api_key" ADAPTER_REQUESTS_PER_HOUR = "hourly_rate_limit" ADAPTER_WAIT_SECONDS_WHEN_RATE_LIMITED = "rate_limit_wait_seconds" ADAPTER_BATCH_SIZE = "batch_size" # This is used for rendering urls at the game details page once imported ADAPTER_DISPLAY_NAME = "display_name" # Used for filters and the like...
from prompt_toolkit.completion import Completion, Completer class BQCompleter(Completer): def __init__(self, schema=None): self.words = { "keyword": sorted(set([ "*", "all", "as", "asc", "by", "cross", "desc", "distinct", "except", "full", "from", "group", "hav...
#!/usr/bin/env python # -*- coding: utf-8 -*- import simplejson as json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.ClientInfo import ClientInfo from alipay.aop.api.domain.LocationInfo import LocationInfo class AlipayOpenDataServiceQueryModel(object): def __init__(self): ...
# coding=utf-8 class BaseService(object): pass
from keras.models import Sequential from keras.layers import GRU import numpy as np model = Sequential() ly = GRU(2, activation='tanh', recurrent_activation='relu',implementation = 1, stateful=False, batch_input_shape=(5, 3, 3)) model.add(ly) model.compile(optimizer='sgd', loss='mse') kernel = np.ones((3, 6)) rec_ker...
## ## Wrappers for pickling ## import os import cPickle as pickle def load_pickled_file(pickled_filename): if os.access(pickled_filename, os.F_OK): pickled_file = open(pickled_filename, 'r') loaded_obj = pickle.load(pickled_file) pickled_file.close() return loaded_obj return Non...
import functools from typing import Any, Callable, Iterable, List, Type, Union from django.apps import AppConfig from django.core import checks from rest_registration.utils.functools import update_wrapper WRAPPER_ASSIGNMENTS_WITHOUT_ANNOTATIONS = tuple( a for a in functools.WRAPPER_ASSIGNMENTS if a != '__annotat...
from django.urls import include, path from django.contrib.auth import views as auth_views from . import views urlpatterns = [ path('student/', include(([ path('', views.StudentSuccess, name='success'), ], 'classroom'), namespace='students' )), path('teacher/', include(([ path('', views.Te...
#!/usr/bin/python # -*- coding: utf-8 -*- import argparse 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 VM(): def __init__(self):...
from typing import Optional, Union import gym import numpy as np from jaxrl.datasets.dataset import Dataset class ReplayBuffer(Dataset): def __init__(self, observation_space: gym.spaces.Box, action_space: Union[gym.spaces.Discrete, gym.spaces.Box], capacity...
with open("input.txt", "r") as f: depart_time = int(f.readline()) buses = [i for i in f.readline().split(',')] def part1(depart_time, buses): valid_buses = [int(i) for i in buses if i != 'x'] times_ids = [(int(depart_time/i+1)*i - depart_time, i) for i in valid_buses] time, bus_id...
#!/usr/bin/env python2.7 from __future__ import division import os,sys,re,argparse,glob,commands def get_analysis_option(): my_cmdparser = argparse.ArgumentParser(description='generate reads filter commands for lncRNA sequence,include: raw reads filter,rRNA filter\n\tauther:zq,46211250@qq.com') my_cmdparser....
#!/bin/python3 from pyhprof.parsers import HProfParser from pyhprof.references import ReferenceBuilder import pyhprof import argparse import sys # Use truffleHog to parse any references for common API keys from truffleHogRegexes.regexChecks import regexes import re def main(): flags = {} parser = argparse.Argument...
def confusion_matrix_plot(y_true, y_pred) -> None: """ Plot a confusion matrix. Args: y_true: List of true labels y_pred: List of prediction labels Returns: """ from sklearn.metrics import ConfusionMatrixDisplay, confusion_matrix cm = confusion_matrix(y_true, y_pred) p...
import logging import uuid from pathlib import Path import blobconverter import cv2 import depthai as dai from imutils.video import FPS log = logging.getLogger(__name__) class DepthAI: def create_pipeline(self, model_name): log.info("Creating DepthAI pipeline...") pipeline = dai.Pipeline() ...
# -*- coding: utf-8 -* from videoanalyst.utils import Registry TRACK_TASKMODELS = Registry('TRACK_TASKMODELS') VOS_TASKMODELS = Registry('VOS_TASKMODELS') TASK_TASKMODELS = dict( track=TRACK_TASKMODELS, vos=VOS_TASKMODELS, )
from mesh.standard import bind from spire.mesh import MeshDependency, ModelController, support_returning from spire.schema import * from spire.support.logs import LogHelper from flux.bindings import platoon from flux.models import Message, Request from flux.operations import * from flux.resources.request import Reques...
from seetaaip.toc import * import cv2 if __name__ == '__main__': # create instance by python script or filepath = "data/__init__.py" instance = Instance(Engine(filepath), Device("cpu"), "A") """ Use Engine to load zip files: `Engine("data/aip.zip", replace=False)`, the file will extracted in "d...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' """ Кривая Минковского """ # Оригинал: https://ru.wikipedia.org/wiki/Кривая_Минковского # <?php # $i = 2; # # $image = imagecreatetruecolor(600, 400); # imagefilledrectangle($image, 0, 0, imagesx($image) - 1, imagesy($image) - 1, #...
import requests import nb import distributions def load_data(): # Loading, formatting and partitioning the data set: # This data set is described here: https://archive.ics.uci.edu/ml/datasets/Statlog+(German+Credit+Data) raw_data = requests.get("https://archive.ics.uci.edu/ml/machine-learning-database...
from tests.prepare import BaseTestCase, datatype_redis, unittest class StringTests(BaseTestCase): def test_value(self): a = "wagwaan" self.assertEqual(datatype_redis.String(a), a) def test_empty(self): self.assertEqual(datatype_redis.String(), "") def test_add(self): a = ...
from django.conf.urls import url from . import views from .models import Category categories = "|".join([category.name for category in Category.objects.all()]) app_name = 'gifspool' urlpatterns = [ url(r'^$', views.Pool.as_view(), name='gifspool'), url(r'^login/$', views.Login.as_view(), name='login'), u...
import pandas as pd import os import psycopg2 from dotenv import load_dotenv load_dotenv() DB_NAME = os.getenv('DB_NAME') DB_USER = os.getenv('DB_USER') DB_PASS = os.getenv('DB_PASS') DB_HOST = os.getenv('DB_HOST') conn = psycopg2.connect(dbname=DB_NAME, user=DB_USER, ...
""" install.py: Installs the FPP tool suite based on the version of this installer package. It will use FPP_DOWNLOAD_CACHE environment variable to pull up previously downloaded items for users that wish to install offline. """ import atexit import os import platform import shutil import subprocess import sys import ta...
from bs4 import BeautifulSoup #Importing Selenium Packages from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait, Select from selenium.webdriver.firefox.options import Options from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By ...