content
stringlengths
5
1.05M
import datetime import hashlib from flask_sqlalchemy import SQLAlchemy from flask_login import UserMixin from tldr import app from urllib.parse import urlparse from itsdangerous import TimedJSONWebSignatureSerializer as Serializer db = SQLAlchemy(app) def baseN(num, b, numerals='0123456789abcdefghijklmnopqrstuvwxyz...
# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ Change directory to provide relative paths for doctests >>> import os >>> filepath = os.path.dirname( os.path.realpath( __file__ ) ) >>> datadir = os.path.realpat...
# -*- coding: utf-8 -*- ######################################################################### # # Copyright 2019, GeoSolutions Sas. # All rights reserved. # # This source code is licensed under the MIT license found in the # LICENSE.txt file in the root directory of this source tree. # #############################...
# Generated by Django 2.2.13 on 2020-11-10 08:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('studygroups', '0139_team_subtitle'), ] operations = [ migrations.AlterField( model_name='team', name='subtitle', ...
import time from locust import HttpUser, between, task class QuickstartUser(HttpUser): wait_time = between(1, 2) @task def get_users(self): self.client.get("/api/users/")
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # BCDI: tools for pre(post)-processing Bragg coherent X-ray diffraction imaging data # (c) 07/2017-06/2019 : CNRS UMR 7344 IM2NP # (c) 07/2019-present : DESY PHOTON SCIENCE # authors: # Jerome Carnis, carnis_jerome@yahoo.fr import numpy as np from numpy...
from django.shortcuts import render from django.views.generic import View class IndexView(View): """ An index view""" template_name = "base.html" def get(self, request): """ GET to return a simple template """ return render( request, self.template_name )
""" Tests for ESMTP extension parsing. """ from aiosmtplib.esmtp import parse_esmtp_extensions def test_basic_extension_parsing(): response = """size.does.matter.af.MIL offers FIFTEEN extensions: 8BITMIME PIPELINING DSN ENHANCEDSTATUSCODES EXPN HELP SAML SEND SOML TURN XADR XSTA ETRN XGEN SIZE 51200000 """ ...
import pytest from liquid import * def test_register_filter(): @filter_manager.register(mode='python') def incr(base, inc=1): return base + inc liq = Liquid('{{ 2 | incr}}', dict(mode='python')) assert liq.render() == '3' liq = Liquid('{{ 2 | incr:2}}', dict(mode='python')) assert liq....
#!/usr/bin/env python import os import json with open(os.path.join(os.environ['BOOST_CI_SRC_FOLDER'], 'meta', 'libraries.json')) as jsonFile: lib_data = json.load(jsonFile) print(lib_data['key'])
#!/usr/bin/env python2.7 import sys import argparse import gzip import clsnaputil #assumes you already have the AUCs #pulled out using: #wiggletools print non_unique_base_coverage.bw.auc AUC non_unique_base_coverage.bw RECOUNT_TARGET = 40 * 1000000 SNAPTRON_FORMAT_CHR_COL = 1 SNAPTRON_FORMAT_COUNT_COL = 11 def load_...
from optparse import make_option import os import shutil from django.core.management.base import BaseCommand from django.contrib.auth.models import User import MySQLdb from blog.models import Blog, Post, Asset class Command(BaseCommand): help = 'Import blog posts from Movable Type' option_list = BaseCommand...
"""Programa 8_5.py Descrição: Reescrever a função da listagem 8.5 de forma a utilizar os métodos de pesquisa em lista vistos no cap 7. Autor:Cláudio Schefer Data: Versão: 001 """ # Declaração de variáveis L = [] valor = int (0) # Entrada de dados L = [10, 20, 25, 30] # Processamento def pesquise (lista, valor)...
import asyncio import logging from timeit import default_timer as timer from podping_hivewriter.async_context import AsyncContext from podping_hivewriter.models.podping_settings import PodpingSettings from podping_hivewriter.podping_settings import get_podping_settings from pydantic import ValidationError class Podp...
from rest_framework import permissions from API.models import * class IsOwnerOrReadOnly(permissions.BasePermission): """ Custom permission to only allow owners of an object to edit it. """ def has_object_permission(self, request, view, obj): # Read permissions are allowed to any request, ...
WORD_EMBEDDING_FILE = './data/GoogleNews-vectors-negative300.txt' WORD_EMBEDDING_BIN_FILE = './bin/unigram_embedding.pkl' LOW_FREQ_TOKEN_FILE = './bin/unigram_low_freq_voc.pkl' EMBEDDING_SIZE = 300 if __name__ == "__main__": from preprocess.data import GigawordRaw, ParaphraseWikiAnswer from gensim.models impo...
print('Vamos somar alguns números: ') for c in range(1, 501): if c % 3 == 0: print(c)
#!/usr/bin/python """ Check current Husky battery status (via ROS) usage: ./battery.py [<node IP> <master IP> | -m <metalog> [F]] """ import sys import os from huskyros import HuskyROS # apyros should be common lib - now in katarina code from apyros.sourcelogger import SourceLogger from apyros.metalog import...
import os import tkinter.filedialog as tk import natsort pot = '/media/vid/DLS DATA/seq4Amod35/2112' seznam = os.listdir(pot) seznam = natsort.natsorted(seznam) key = 'OHL' temp = [] for i in seznam: if key in i: print(i) if '.txt' in i: continue with open(pot ...
#Will take a directory full of covariance models and feed them to Infernal's cmcalibrate one at a time. #The resulting covariance models are put in sys.argv[3]. #This script may take several days to complete. Calibrating models of large alignments is slow. #Necessary modules: biopython, infernal #Usage: python Infer...
outputText = """Yesterday I went to see {0}. To be honest, I thought it was pretty good. It's a good effort by {1}. I hadn't seen a plot move quite as fluidly as it did in {0}, but {1} does have a good hand for it.""" print('What movie are we reviewing') movie = input().title() print('And who directs it?') director ...
class ControllerSettings: def __init__(self, powerslide, air_roll, air_roll_left, air_roll_right, boost, jump, ball_cam, brake, throttle): self.powerslide = powerslide self.air_roll = air_roll self.air_roll_left = air_roll_left self.air_roll_right = air_roll_right self.boost ...
import os import nbformat def get_cur_dir(): return os.path.abspath(os.path.dirname(__file__)) def get_par_dir(): return os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)) def gen_items(path): for item in os.listdir(path): path_item = os.path.abspath(os.path.join(path, item))...
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # vim:fenc=utf-8 # File name: test.py # First Edit: 2020-03-19 # Last Change: 19-Mar-2020. """ This scrip is for test """ amount_dict = {"high": 1.2, "normal": 1.0, "low": 0.8} def main(): factorya = AbstractPizzaFactory(PizzaFactoryA()) pizza1 = factorya.make...
''' 最长公共子序列 描述 给定两个字符串,返回两个字符串的最长公共子序列(不是最长公共子字符串),可能是多个。 输入 输入为两行,一行一个字符串 输出 输出如果有多个则分为多行,先后顺序不影响判断。 输入样例 1A2BD3G4H56JK 23EFG4I5J6K7 输出样例 23G456K 23G45JK ''' ''' d为方向矩阵 1:上 2:左上 3:左 4:左or上 ''' def LCS (a, b): C = [[0 for i in range(len(b) + 1)] for i in range(len(a) + 1)] # 定义矩阵C保存最长公共子序列长度 d = [[0 for i in ra...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Script to convert YOLO keras model to an integer quantized tflite model using latest Post-Training Integer Quantization Toolkit released in tensorflow 2.0.0 build """ import os, sys, argparse import numpy as np import tensorflow as tf from tensorflow.keras.mo...
from taskcontrol.lib import EPubSubBase def run(data): print("Running Pubsub ", data) def publisher(data): print("Running publisher ", data) def subscriber(data): print("Running subscriber ", data) config = {"name": "new", "handler": run, "queue": None, "maxsize": 10, "queu...
import numpy as np import os import sys from astropy.io import fits import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec plt.style.use('araa') from matplotlib import rc rc('text.latex', preamble=r'\usepackage{amsmath}') rc("font", **{"family": "serif", "serif": ["Palatino"]}) rc("text", usetex = True...
from collections import OrderedDict from functools import partial from unittest import TestCase import os import os.path as osp import numpy as np from datumaro.components.annotation import ( AnnotationType, LabelCategories, Mask, MaskCategories, ) from datumaro.components.dataset import Dataset from datumaro.com...
""" Django 1.10.5 doesn't support migrations/updates for fulltext fields, django-pg-fts isn't actively maintained and current codebase is broken between various versions of Django. Because of that I decided to implement our migrations with intent to drop it when django develops its own solution. """ import copy from ...
import os import argparse import shutil from datetime import datetime,timedelta def main(): ''' the driver ''' args = parse() files = get_files(args) if confirm(files): copy_files(files,args) def parse(): ''' sets the args needed to run and returns them ''' #default...
import yaml from pathlib import Path from .repo import serialize_repo, deserialize_repo from .validation import validate_manifest from ..exception import AppException from ..env import MANIFEST_PATH_DEFAULT from ..logger import get_logger from ..utils import to_absolute_path, validate_writable_directory def seriali...
import logging import sqlite3 from phizz.database import get_cursor from . import GENE_DB logger = logging.getLogger(__name__) def query_hpo(hpo_terms, database=None, connection=None): """Query with hpo terms If no databse is given use the one that follows with package Args: ...
import numpy as np def gaussian_KL(mu0, Sig0, mu1, Sig1inv): t1 = np.dot(Sig1inv, Sig0).trace() t2 = np.dot((mu1-mu0),np.dot(Sig1inv, mu1-mu0)) t3 = -np.linalg.slogdet(Sig1inv)[1] - np.linalg.slogdet(Sig0)[1] return 0.5*(t1+t2+t3-mu0.shape[0]) def weighted_post_KL(th0, Sig0inv, sigsq, X, Y, w, reverse=True):...
# <editor-fold desc="Description"> x = 'foo' + 'bar' # </editor-fold>
import numpy as np from matplotlib import pyplot as plt import seaborn as sb from utils.data_handling import load_config def get_colors(): cfg = load_config() sb.set_style(cfg['plotting']['seaborn']['style']) sb.set_context(cfg['plotting']['seaborn']['context']['context'], font_scale=c...
# -*- coding: utf-8 -*- """ Created on 2021/1/12 16:51 @author: Irvinfaith @email: Irvinfaith@hotmail.com """
# Generated by Django 3.1.4 on 2020-12-12 22:01 import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("peeringdb", "0014_auto_20201208_1856"), ("peering", "0065_auto_20201025_2137"), ] operations = [ mi...
r""" Hypergraphs This module consists in a very basic implementation of :class:`Hypergraph`, whose only current purpose is to provide method to visualize them. This is done at the moment through `\LaTeX` and TikZ, and can be obtained from Sage through the ``view`` command:: sage: H = Hypergraph([{1,2,3},{2,3,4},{...
# coding: utf-8 # **In this simple kernel, I will attempt to predict whether customers will be "Charged Off" on a loan using Random Forests Classifier.** # In[ ]: # This Python 3 environment comes with many helpful analytics libraries installed # It is defined by the kaggle/python docker image: https://github.com/...
from rater import generate_pokemon_list_summary from common import pokemon_base_stats from pokedex import pokedex excluded_pokemon_name_list = [] def find_bad_pokemons(pokemon_list): pokemon_summary = generate_pokemon_list_summary(pokemon_list) bad_pokemons_ids = [] for pokemon_name in sorted(pokemon_summary.k...
app = """ library(dash) app <- Dash$new() app$layout( html$div( list( dccInput(id='input-1-state', type='text', value='Montreal'), dccInput(id='input-2-state', type='text', value='Canada'), html$button(id='submit-button', n_clicks=0, 'Submit'), html$div(id='output-state'), dccGraph...
class Solution: def wordPattern(self, pattern, str): map_letter_to_word = dict() map_word_to_letter = dict() words = str.split() if len(words) != len(pattern): return False for letter, word in zip(pattern, words): if l...
# (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org) # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php # Mostly taken from PasteDeploy and stripped down for Galaxy import inspect import os import re import sys import pkg_resources from six import ite...
from numpy import sin, cos, pi, fabs, sign, roll, arctan2, diff, cumsum, hypot, logical_and, where, linspace from scipy import interpolate import matplotlib.pyplot as plt # Cross-section class that stores x, y points for the cross-section # and calculates various geometry data d = 1000 class CrossSection: """ Cla...
#! python2.7 ## -*- coding: utf-8 -*- ## kun for Apk View Tracking ## ParseElement.py from DeviceManagement.Device import Device from TreeType import CRect from Utility import str2int class ParseElement(): def __init__(self, element_data): self.class_name = "" self.hash_code = "" ...
#Crie um progama que tenha uma tupla totalmente preenchida com uma contagem por extensão de Zero até Vinte. #Seu programa deverá ler um número pelo teclado (entre 0 e 20) e mostra-lo por extenso. numeros = ('zero','um', 'dois','três','quatro','cinco','seis','sete','oito','nove','dez','onze','doze','treze','quatorze', ...
import sys import logging import logging.handlers from command_tree import CommandTree, Config from voidpp_tools.colors import ColoredLoggerFormatter from .core import Evolution, Chain from .revision import REVISION_NUMBER_LENGTH tree = CommandTree(Config( prepend_double_hyphen_prefix_if_arg_has_default = True, ...
import os import pandapower as pp import pandapower.networks as pn from pandapower.plotting.plotly import pf_res_plotly from preparation import NetworkBuilder import_rules = dict() aemo_data = r"data/aemo_data_sources.json" tnsp_buses = r"data/electranet_buses.json" if __name__ == "__main__": builder = NetworkBui...
#!/usr/bin/env python3 import os import ssl from base64 import b64decode, b64encode from hashlib import sha256 from time import time from urllib import parse from hmac import HMAC from azure.keyvault.secrets import SecretClient from azure.identity import DefaultAzureCredential from paho.mqtt import client as mqtt def...
objConstructors = {'flow_emap.get_key' : {'constructor' : 'FlowIdc', 'type' : 'FlowIdi', 'fields' : ['sp', 'dp', 'sip', 'dip', 'prot']}} typeConstructors = {'FlowIdc' : 'FlowIdi', ...
from django.conf.urls import patterns, include, url from django.utils.translation import ugettext_lazy as _ from django.views.generic import TemplateView, RedirectView from django.core.urlresolvers import reverse_lazy as reverse from .views import reroute home = TemplateView.as_view(template_name='home.html') #: IHM...
from math import ceil from utils import hrsize from json import dumps from . import Sample class SampleSet: round = 5 def __init__(self, samples) -> None: if not (isinstance(samples, list) and all(isinstance(sample, Sample) for sample in samples)): raise Exception("samples parameter inval...
import pytest from django.core.exceptions import PermissionDenied from datahub.admin_report.report import get_report_by_id, get_reports_by_model from datahub.core.test_utils import create_test_user pytestmark = pytest.mark.django_db @pytest.mark.parametrize( 'permission_codenames,expected_result', ( ...
def factorial(n): if n < 1: return 1 else: return n * factorial(n-1) end end print factorial(5) # should output 120
""" @author: acfromspace """ # Make a function aardvark that, given a string, returns 'aardvark' # if the string starts with an a. Otherwise, return 'zebra'. # # >>>> aardvark("arg") # aardvark # >>>> aardvark("Trinket") # zebra def aardvark(string): # Add code here that returns the answer. if string[0] == ...
import datetime from django.test import TestCase from trojsten.contests.models import Competition, Round, Semester, Task from trojsten.people.models import User, UserProperty, UserPropertyKey from .model_sanitizers import ( GeneratorFieldSanitizer, TaskSanitizer, UserPropertySanitizer, UserSanitizer,...
#!/usr/bin/python from __future__ import absolute_import, division, print_function # Copyright 2019-2021 Fortinet, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the ...
import torch.nn from gatelfpytorchjson.CustomModule import CustomModule import sys import logging logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) streamhandler = logging.StreamHandler(stream=sys.stderr) formatter = logging.Formatter( '%(asctime)s %(name)-12s %(levelname)-8s %(messag...
class TimeFrame(object): _string_repr = [[" day", " hour", " min", " sec"],[" d", " h", " m", " s"]] def __init__(self, seconds = 0.0): self._seconds = 0.0 self._minutes = 0 self._hours = 0 self._days = 0 self._use_short = int(False) self._total_seconds = seconds self.set_with_seconds(seconds) de...
import subprocess import sys from optparse import OptionParser from django.core.management import LaxOptionParser from django.core.management.base import BaseCommand, CommandError from cas_dev_server.management import subprocess_environment class Command(BaseCommand): option_list = BaseCommand.option_list[1:] ...
#!/usr/bin/env python3 from dotenv import load_dotenv load_dotenv() import os import logging import argparse import pugsql import json import pandas as pd from uuid import UUID from articleparser.drive import GoogleDrive logging.basicConfig(level=os.getenv("LOG_LEVEL", "INFO")) logger = logging.getLogger(__name__) ...
import warnings from collections import namedtuple, defaultdict from functools import partial from typing import Optional, Tuple, List, Callable, Any import torch from torch import Tensor from torch import distributions from torch import nn class TemporalDifference(nn.Module): def __init__( self, ...
import unittest from httpretty import HTTPretty from notification_log import NotificationLog import requests import json class NotificationLogTests(unittest.TestCase): def setUp(self): HTTPretty.enable() self.client = NotificationLog(hostname='test.example.com', protocol='http') def tearDown...
from unittest.mock import patch from main import main_handler import sys @patch("main.hello_world") def test_mock_external_incorrect(mock_hello_world): mock_hello_world.return_value = "Hello Dolly!" assert main_handler() == "Hello Dolly!" for path in sys.path: print(path)
# Character field ID when accessed: 925070100 # ObjectID: 0 # ParentID: 925070100
y,z,n=[int(input()) for _ in range(3)] print("The 1-3-sum is",str( y+z*3+n+91))
import xarray as xr import numpy as np import pytest import pathlib from xarrayutils.file_handling import ( temp_write_split, maybe_create_folder, total_nested_size, write, ) @pytest.fixture def ds(): data = np.random.rand() time = xr.cftime_range("1850", freq="1AS", periods=12) ds = xr.Da...
from snovault.elasticsearch.searches.interfaces import SEARCH_CONFIG from snovault.elasticsearch.searches.configs import search_config def includeme(config): config.scan(__name__) config.registry[SEARCH_CONFIG].add_aliases(ALIASES) config.registry[SEARCH_CONFIG].add_defaults(DEFAULTS) @search_config( ...
from bs4 import BeautifulSoup as bs import requests import pandas as pd import random url = 'https://www.oschina.net/widgets/index_tweet_list' headers = { 'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Cache-Control': 'no-cache', 'Con...
from datetime import datetime from testil import Config, eq from .. import rebuildcase as mod def test_should_sort_sql_transactions(): def test(sql_form_ids, couch_form_ids, expect): sql_case = Config( transactions=[Config(form_id=x, details={}) for x in sql_form_ids] ) couch...
#!/usr/bin/env python3 import socket, time, sys from multiprocessing import Process HOST = "" PORT = 8001 BUFFER_SIZE = 1024 #TO-DO: get_remote_ip() method def get_remote_ip(host): print(f'Getting IP for {host}') try: remote_ip = socket.gethostbyname( host ) except socket.gaierror: prin...
# -*- coding: utf-8 -*- """ Created on Sun Feb 26 19:56:37 2017 @author: Simon Stiebellehner https://github.com/stiebels This file implements three classifiers: - XGBoost (Gradient Boosted Trees) - Random Forest - AdaBoost (Decision Trees) These three base classifiers are then ensembled in two ways: (1) Weighti...
from django.shortcuts import render from .models import Entry from rest_framework import generics from .serializers import EntrySerializer # Create your views here. class EntryCreate(generics.ListCreateAPIView): # Allows creation of a new entry queryset = Entry.objects.all() serializer_class = EntrySerial...
#!/usr/bin/python #import sys import boto3 import datetime from Crypto import Random from Crypto.Cipher import AES import argparse import base64 from argparse import Namespace from keypot_exceptions.KeypotError import KeypotError #VERSION keypot_version='Keypot-0.3' ddb_hash_key_name='env-variable-name' #Pads the dat...
import os from dotenv import load_dotenv,find_dotenv # not used in this stub but often useful for finding various files project_dir = os.path.join(os.path.dirname(__file__), os.pardir) load_dotenv(find_dotenv())
from ..views import add, configure, delete
#!/usr/bin/env python # -*- coding: iso-8859-15 -*- # Copyright (c) 2014 The New York Times Company # # 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/LIC...
# Author: Xinshuo Weng # Email: xinshuow@andrew.cmu.edu # this file includes general help functions for MUGSY data import init_paths init_paths.main() from check import isstring, isscalar from file_io import get_sheet_service, update_patchs2sheet, get_data_from_sheet, update_row2sheet # # number of points for all par...
from dataclasses import dataclass import pytest import argdcls from argdcls.config import _parse @dataclass class Config: lr: float adam: bool = False def test_load_params(): # "*" config = argdcls.load(Config, ["@lr=1.0"]) assert config.lr == 1.0 # "" config = argdcls.load(Config, ["...
#! /usr/bin/env python """ A simple demo using aubio and pyaudio to play beats in real time Note you will need to have pyaudio installed: `pip install pyaudio`. Examples: ./demo_tapthebeat.py ~/Music/track1.ogg When compiled with ffmpeg/libav, you should be able to open remote streams. For instance using youtube-d...
''' Created 03/20/2014 @authors: Yifan Ning @summary: parse Molecular Formula and drugbank_id from drugbank.xml then parse MF(Molecular Formula), FDA Preferred Term and UNNI from UNNIs records match the results from drugbank and results of parse UNNIs records output terms: FDA Preferred ...
import pandas as pd from ..util import generate_name from tickcounter.questionnaire import Encoder class MultiEncoder(object): def __init__(self, encoding_rule): if isinstance(encoding_rule, Encoder): self.rules = { encoding_rule.name: encoding_rule } elif isinstance(enc...
from rest_framework import serializers from accounts.models import User class AccountSerializer(serializers.ModelSerializer): def validate(self, attrs): username = attrs.get('username', None) email = attrs.get('email', None) password = attrs.get('password', None) try: ...
import os import pdb import random import sys import time from pprint import pformat import numpy import torch as tc import torch.nn as nn from tqdm import tqdm from utils.logger import Logger from utils.random_seeder import set_random_seed from config import get_config from training_procedure import Trainer def mai...
#!/usr/bin/env python2 # coding:utf-8 import base64 import copy import errno import getopt import json import logging import os import sys import threading import time import traceback import boto3 import oss2 import yaml from botocore.client import Config from pykit import jobq report_state_lock = threading.RLock(...
from __future__ import print_function import os import argparse import numpy as np from module.retinaface_function_in_numpy import PriorBox_in_numpy from utils.retinaface_tool_in_numpy import py_cpu_nms_in_numpy, decode_in_numpy, decode_landm_in_numpy import cv2 from module.retinaface_model_in_numpy import RetinaFace f...
import logging def init_logging(log_file, log_level): logging.getLogger().setLevel(log_level) log_formatter = logging.Formatter('%(asctime)s %(message)s') root_logger = logging.getLogger() if log_file: file_handler = logging.FileHandler(log_file, encoding='utf8') file_handler.setFormat...
from django.core.management.base import BaseCommand from apps.boxes.models import BoxUpload class Command(BaseCommand): help = 'Removes expired and completed boxes uploads' def handle(self, *args, **options): deleted = BoxUpload.objects.not_active().delete() self.stdout.write( sel...
from audhelper.audhelper import __version__, __author__ import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="audhelper", version=__version__, author=__author__, author_email="sherkfung@gmail.com", description="Audio helper functions including visualiz...
import cv2 import numpy as np img = cv2.imread(r"EDIZ\OPENCV\basin.jpg") gri = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) temp1 = cv2.imread(r"EDIZ\OPENCV\temp1.jpg",0) temp2 = cv2.imread(r"EDIZ\OPENCV\temp2.jpg",0) w,h = temp2.shape[::-1] res = cv2.matchTemplate(gri,temp2,cv2.TM_CCOEFF_NORMED) thresh = 0.5 loc = np.where(r...
### # Copyright 2017 Hewlett Packard Enterprise, 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 ...
from __future__ import annotations from discord.ext import commands __all__ = ("HierarchyFail",) class HierarchyFail(commands.CheckFailure): ...
import numpy as np import pandas as pd import os import scipy.io as spio import math from random import sample class ProcessData: def __init__(self, data_set_directory, columns_to_use): self.directory = data_set_directory self.selected_columns = columns_to_use self.datasets = [] sel...
# coding=utf-8 """ Demo app, to show OpenCV video and PySide2 widgets together.""" import sys from PySide2.QtWidgets import QApplication from sksurgerycore.configuration.configuration_manager import \ ConfigurationManager from sksurgerybard.widgets.bard_overlay_app import BARDOverlayApp def run_demo(config_...
# coding: utf-8 import sys k_bit_rate_num_bits = [ 0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 32 ] k_highest_bit_rate = len(k_bit_rate_num_bits) - 1 k_lowest_bit_rate = 1 k_num_bit_rates = len(k_bit_rate_num_bits) k_invalid_bit_rate = 255 # This code assumes that rotations, translations, and sc...
#!/usr/bin/python """ Date utilities to do fast datetime parsing. Copyright (C) 2013 Byron Platt This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) ...
'''OpenGL extension SGIS.texture_filter4 Overview (from the spec) This extension allows 1D and 2D textures to be filtered using an application-defined, four sample per dimension filter. (In addition to the NEAREST and LINEAR filters defined in the original GL Specification.) Such filtering results in higher ima...
from support import print_func import using_name print_func("Jack")
"""Various utilities used throughout the code. Here go various utilities that don't belong directly in any class, photometry utils module nor or SED model module. """ import os import pickle import random import time from contextlib import closing import numpy as np from scipy.special import erf from scipy.stats impo...