content
stringlengths
5
1.05M
import logging import os class DIDFormatter(logging.Formatter): """ Need a customer formatter to allow for logging with request ids that vary. Normally log messages are "level instance component request_id msg" and request_id gets set by initialize_logging but we need a handler that'll let us pass...
from django.db import models def build_models(payment_class): return []
import time import pickle import numpy as np from nltk.corpus import stopwords from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score from sklearn.metrics import average_precision_score, recall_score, f1_score,\ classification_report def add_to_arra...
import mysql.connector conn = mysql.connector.connect(user='root',password='root',database='test',host='127.0.0.1',charset='utf8') cursor = conn.cursor() cursor.execute('create table user (id varchar(20) primary key,name varchar(20))') cursor.execute('insert into user values (%s,%s)',['1','Twittytop']) print(cursor.row...
import subprocess import textwrap import pytest import signal import socket import time import os PORT = 9000 HOST = 'localhost' KEY = "testtesttest" @pytest.fixture(scope="session") def minio(): # Setup os.environ['MINIO_ACCESS_KEY'] = KEY os.environ['MINIO_SECRET_KEY'] = KEY os.environ['MINT_MO...
import os import requests import time import json import argparse from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expec...
import torch from jaclearn.logic.propositional.logic_induction import search from tqdm import tqdm def get_logic_formula(inputs, outputs, in_names, f): """ Return searched logic formula inputs, outputs are torch tensors in_names are the names for input f[k] is the set of considered variables for t...
while (True): print ('Press Q to quit') a = input('Enter a Number: ') if (a == 'q'): break try: print ('Trying...') a = int(a) if (a > 6): print ('You Enter a number greater than 6') except Exception as e: print (f'Your input resulted in...
import warnings warnings.filterwarnings("ignore") import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt plt.style.use('ggplot') import torch print(torch.__version__) import torch.nn as nn # содержит функции для реалзации архитектуры нейронных сетей import torch.optim as optim ...
import random import arcade class Cactus(arcade.Sprite): def __init__(self, width, height, speed): super().__init__() self.pic_path = random.choice(['images/cactus1_night.png','images/cactus4_night.png']) self.texture = arcade.load_texture(self.pic_path) self.center_x = width ...
#!/usr/bin/python import sys,os,re,optparse,tarfile,uuid,math,glob from arguments_RAxML import * def TF(inputTF): if( inputTF != None and inputTF!=False ): return "True" return "False" ''' Builds the submit file for RAxML runs ''' def main(): current_version = "#version 1.0.1" #1.0.1 added code for ...
from enum import Enum class AntType(Enum): Explorer = 0 Worker = 1 class MarkType(Enum): Explored = 0 FoodFound = 1 class TargetType(Enum): Explore = 0 Home = 1 Food = 2
from soniox.transcribe_file import transcribe_file_stream from soniox.speech_service import Client, set_api_key from soniox.test_data import TEST_AUDIO_LONG_FLAC set_api_key("<YOUR-API-KEY>") def main(): with Client() as client: for result in transcribe_file_stream(TEST_AUDIO_LONG_FLAC, client): ...
# Single source of truth for package version __version__ = "0.3.8"
#!/usr/bin/env python3 ''' udptee.py - like `tee` but duplicates output to a udp destination instead of a file ''' import argparse import sys import os import socket def main(argv=['udptee.py']): arg_parser = argparse.ArgumentParser( prog=os.path.basename(argv[0]), description=( 'like ...
''' Copyright (C) 2017-2020 Bryant Moscon - bmoscon@gmail.com Please see the LICENSE file for the terms and conditions associated with this software. ''' import json import logging from decimal import Decimal from itertools import product from sortedcontainers import SortedDict as sd from cryptofeed.de...
from xicam.plugins import QWidgetPlugin from pyqtgraph import ImageView, PlotItem from xicam.core.data import NonDBHeader from qtpy.QtWidgets import * from qtpy.QtCore import * from qtpy.QtGui import * import numpy as np from xicam.core import msg from xicam.gui.widgets.tabview import TabView from .SAXSViewerPlugin imp...
from typing import Optional from prompt_toolkit.styles import Style from prompt_toolkit.buffer import Buffer from prompt_toolkit.layout import Layout from prompt_toolkit.lexers import SimpleLexer from prompt_toolkit.application import get_app from prompt_toolkit.enums import DEFAULT_BUFFER from prompt_toolkit.validati...
var1 = "2" print(type(var1)) # <class 'str'> var1 = 3 print(type(var1)) # <class 'int'> ################## var1 = 1 var2 = 2.0 var3 = 3.4 + 3j ################## var4 = "Jamiryo" #-- var5 = [1,1.0,"Jamiryo"] #-- var6 = (1,1.0,"Jamiryo") ################## var7 = {"1":"Bir","2":"İki"} ################## var8 = set() var...
#!/usr/bin/env python3 import math, nltk, logging, os from Document import * import TestData, Wordlist, Settings import pickle class Metric: """Metric contains all the functions necessary to score an RDG's terminology.""" def __init__(self, rdgDir, general, working_dir = '.',overwrite=False,rank_from_previous=...
#!/usr/bin/env python """ Questions: Asks for further explanations regarding its parent. (common property) """ __all__ = ['patch', '__doc__'] def patch(target): """ These methods are appended to DBContent with type <modulename>""" # it comes in fixed order: column: <order_position> target.is_in_random_o...
# -*- coding: utf-8 -*- """ Created on Tue Jul 08 08:54:04 2014 @author: Brian Jacobowski <bjacobowski.dev@gmail.com> """ from blpapi.element import Element from blpapi.schema import SchemaElementDefinition def format_fld_name(fld_name): """Reformats input field name to match bloomberg's expected st...
"""NdArray/Tensor array extension in Arrowbic. """ from typing import Iterable, Optional, Type, TypeVar import numpy as np import pyarrow as pa from arrowbic.core.base_extension_array import BaseExtensionArray from arrowbic.core.base_extension_type import BaseExtensionType from arrowbic.core.base_types import NdArray...
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import itertools import datetime import django_rq from ralph.util.network import ping from ralph.discovery.http import get_http_family from ral...
import subprocess from .utils import logging, cwd, run_process, data_types logger = logging.getLogger(__name__) data = cwd / '../../../inputs/meta_fb' def build_vrt(name): subprocess.run([ 'gdalbuildvrt', '-q', data / f'hrsl_{name}/hrsl_{name}-latest.vrt', *sorted((data / f'hrsl_{...
from sys import platform as _platform from sys import exit as exit from requests import get as load from crontab import CronTab import os import getpass class Exploit: system = None username= "max" def __init__(self): self.system=_platform self.username= getpass.getuser() ...
import cv2 import numpy as np import os def resize_image(img, size): h, w = img.shape[:2] c = img.shape[2] if len(img.shape)>2 else 1 if h == w: return cv2.resize(img, size, cv2.INTER_AREA) dif = h if h > w else w interpolation = cv2.INTER_AREA if dif > (size[0]+size[1])//2 else cv2.INT...
from heapq import heappop, heappush from sortedcontainers import SortedList class Solution: def busiestServers(self, k: int, arrival: List[int], load: List[int]) -> List[int]: valid = SortedList(range(k)) cnt = [0] * k heap = [] for idx, (a, l) in enumerate(zip(arrival, load)): ...
""" Wins that don’t fit any category """ import logging log = logging.getLogger(__name__) import curses from . import Win from theming import get_theme, to_curses_attr class VerticalSeparator(Win): """ Just a one-column window, with just a line in it, that is refreshed only on resize, but never on refre...
#!/usr/bin/env python # coding: utf-8 # In[1]: def recommendcase(location,quality,compensate,dbcon,number): """ location: np.array quality: np.array compensate: np.array dbcon: database connection number: number of recommended cases """ import pandas as pd caseset = pd.Data...
from analyze.calc_run import * base = 'G:/Prive/MIJN-Documenten/TU/62-Stage/20180130-l/' d=-5 # short quad nocoil calc_run(base + 'run1', REACTOR_GLASS_SHORT_QUAD, scope_multiple=True, scope_file_name_index=2, # lengt meas=SHORT_MEAS_LEN, current_scaling=0.5, del...
"""Test the more robust put_item logic.""" import pytest from . import tmp_dir_fixture # NOQA try: from unittest.mock import MagicMock except ImportError: from mock import MagicMock def test_get_object_failure(): """ Mock scenario where the get fails. """ from botocore.exceptions import W...
# Generated by Django 2.1.5 on 2019-01-19 09:25 import django.utils.timezone from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("motions", "0018_auto_20190118_2101")] operations = [ migrations.AddField( model_name="motion", name=...
import gc import platform import sys import pytest from pyo3_pytests.objstore import ObjStore PYPY = platform.python_implementation() == "PyPy" @pytest.mark.skipif(PYPY, reason="PyPy does not have sys.getrefcount") def test_objstore_doesnot_leak_memory(): N = 10000 message = b'\\(-"-;) Praying that memory ...
from ... pyaz_utils import _call_az def list(): ''' List all security assessment results. ''' return _call_az("az security assessment-metadata list", locals()) def show(name): ''' Shows a security assessment. Required Parameters: - name -- name of the resource to be fetched ''' ...
import pickle import argparse import random import matplotlib.pyplot as plt import numpy as np from math import floor class MyEvaluation: def __init__(self, user_train, user_test, movie_train, movie_test, iteration, sample_test=50, TOP_M_start=10, TOP_M_end=100, pred_type='out-of-matrix', seed=42...
""" Parses data from myanimelist/anilist and themes.moe. """ from typing import List from animethemes_dl.options import OPTIONS import logging from ..models.animethemes import AnimeThemeAnime from .anilist import get_anilist from .animethemes import fetch_animethemes from .myanimelist import get_mal logger = logging....
#!/usr/bin/python """ Classes to create a complete report of an array configuration with the plots+report. First it will create the necessary simulations. Then the missing plots+reports INPUT: - Antenna List (casa format) - Band List : nominal frequencies for each band will be defined - Type of report: Complete, ...
import os import sys sys.path.append('..') from glob import glob from DeepBrainSeg.registration import Coregistration from DeepBrainSeg.helpers.dcm2niftii import convertDcm2nifti from DeepBrainSeg.brainmask.hdbetmask import get_bet_mask from DeepBrainSeg.tumor import tumorSeg coreg = Coregistration() segmentor = tumor...
""" bottle: Lightweight Python web framework - http://bottlepy.org/docs/dev/ recorder: Module for manipulating records of hours worked Record Object that simulates a single record of work done RecordMalFormedException Wrapped exception used and required, internally, by the Record class crypto: Mo...
# coding=utf8 # Copyright 2018 JDCLOUD.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 ...
# -*- coding: utf-8 -*- ''' python2 hello-caffe.py ---or--- python3 hello-caffe.py ''' from __future__ import print_function import os, sys def hello_world(): import caffe print('pycaffe version: {}'.format(caffe.__version__)) def insert_syspath(p): if is_path_exist(p): print('insert {} into sys...
from enum import Enum, unique import copy @unique class Dirn(Enum): UP = (-1, 0) DOWN = (1, 0) LEFT = (0, -1) RIGHT = (0, 1) UPL = (-1, -1) DOWNR = (1, 1) UPR = (-1, 1) DOWNL = (1, -1) @classmethod def values(cls): return [cls.UP, cls.DOWN, cls.LEFT, cls.RIGHT...
import logging import random import uuid import json from json import JSONDecodeError from locust import HttpUser, task, between, events logging.basicConfig(level=logging.INFO) formIDs = ["28","29","30","31"] formSubmissions ={ "28":{ "2": "Performance Testing", "3": "performance.testing@cds-snc.ca", "...
import logging import os import sys import time import boto3 from datadog import statsd from sqsworkers.crew import Crew statsd.namespace = 'dtech.sqs.workers' statsd.constant_tags.append('sqs-workers-test') statsd.host = 'statsd.domain.dev.atl-inf.io' msg_logger = logging.getLogger('message') msg_logger.setLevel(l...
import argparse import json import logging import os import pdb import sys import time import requests from flask import Flask, abort, jsonify, make_response, request from flask_cors import CORS from memory_profiler import memory_usage, profile from config import SetupParameters from transner import Transner app = F...
#!/usr/bin/env python import gridworld as W import maxent as M import plot as P import trajectory as T import solver as S import optimizer as O import mce_irl as I # import frozenlake_mce_irl as I import numpy as np import matplotlib.pyplot as plt import os import time def get_policy(start): pass def sttl_goal_...
import pandas as pd, numpy as np import matplotlib.pyplot as plt, seaborn as sns url = 'https://raw.githubusercontent.com/datahackformation/Posts-Python-Tips-Tricks/main/Heatmap/titanic.csv' df = pd.read_csv(url, sep=';').set_index('PassengerId') df = pd.get_dummies(df, columns=['Pclass']) df['Sex'] = df['...
"""Models for facial keypoint detection""" import torch import torch.nn as nn import torch.nn.functional as F import pytorch_lightning as pl from pytorch_lightning import Callback from pytorch_lightning.loggers import TensorBoardLogger class KeypointModel(pl.LightningModule): """Facial keypoint detection model""...
import datetime import math from physics import Coordinates from cars import Car class Node(object): """This is a node in a road.""" radius = 20 def __init__(self, coord): assert isinstance(coord, Coordinates) self.coord = coord def __repr__(self): return '<Node %s>' % sel...
""" Test for mcsim package - monte carlo NumPy module. """ import math import mcsim.monte_carlo_np as mc import numpy as np def test_calculate_distance_np_1(): """ Test calculate distance function """ point1=np.array([0,0,0]) point2=np.array([0,1,0]) expected = np.array([1.0]) observed = ...
import tensorflow as tf import keras import numpy as np import os import matplotlib.pyplot as plt URL = r'https://storage.googleapis.com/mledu-datasets/cats_and_dogs_filtered.zip' path_to_zip = tf.keras.utils.get_file('cats_and_dogs.zip', origin=URL, extract=True) PATH = os.path.join(os.path.dirname(path_to_zi...
#!/usr/bin/env python import os import subprocess import sys out = subprocess.check_output(['find . -name \"*txt\"'], shell=True) stats = out.split('\n') import hashlib stats_md5 = [(fname, hashlib.md5(open(fname, 'rb').read()).digest()) for fname in stats if fname] for i in stats_md5: for j in sta...
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ print("Test") print("New")
import gspread from oauth2client.service_account import ServiceAccountCredentials import re class KataIndo: def __init__(self): self.scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'] self.creds = ServiceAccountCredentials.from_json_keyf...
# -*- coding: utf-8 -*- from __future__ import print_function import warnings import numpy as np from lifelines.utils import coalesce def is_latex_enabled(): """ Returns True if LaTeX is enabled in matplotlib's rcParams, False otherwise """ import matplotlib as mpl return mpl.rcParams["text.u...
import math import matplotlib.pyplot as plt from utils.colors import create_background from tree.dynamics import recursive_branch image_size = (1200, 1920, 3) image = create_background(image_size, '3f3f3f') recursive_branch(image, 150, 1, math.pi/2, (500, 1200)) plt.imshow(image) plt.show() plt.imsave("wallpaper.pn...
from typing import Any from scriptable.antlr.TypescriptParser import TypescriptParser from scriptable.api import AST from scriptable.api.ast_binding import ASTBinding class Property(AST[Any]): def __init__(self, value: str, strict: bool = False): self.value = value self.strict = strict def e...
"""Support for NHC2 switches.""" import logging from homeassistant.components.switch import SwitchEntity from .helpers import nhc2_entity_processor from nhc2_coco import CoCo, CoCoSwitch from .const import DOMAIN, KEY_GATEWAY, BRAND, SWITCH KEY_GATEWAY = KEY_GATEWAY KEY_ENTITY = 'nhc2_switches' _LOGGER = logging.ge...
import base64 import json import time from json import JSONDecodeError from typing import Dict, Optional import requests from django.conf import settings from kallisticore import exceptions from kallisticore.lib.credential import Credential, TokenCredential, \ UsernamePasswordCredential __all__ = ["http_probe", ...
#!/usr/bin/env python # # Copyright (c) 2017-2019 Cloudify Platform Ltd. 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-...
#!/usr/bin/python # This script runs quill3d many times for various parameters import os import datetime as dt import rmtlib import numpy as np # qwe config = '.laser-piston' # parameter 0 rmtlib.p0_name = 'ne' #p0_value = rmtlib.geometric_progression(7e22,3e23,2) p0_value = np.array([431]) rmtlib.p0_unit = 'ncr' ...
""" disk_item.py Copyright 2012 Andres Riancho This file is part of w3af, http://w3af.org/ . w3af 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 version 2 of the License. w3af is distributed in the hope that i...
class Solution: def findShortestSubArray(self, nums: List[int]) -> int: num_range_dict = {} max_count = 0 for index, num in enumerate(nums): if num in num_range_dict: start, end, count = num_range_dict[num] new_count = count + 1 n...
from sagas.nlu.translator import translate from sagas.tool import init_logger import logging logger = logging.getLogger(__name__) class GoogleTranslator(object): def translate(self, text, target='zh-CN', source='auto', verbose=False): """ $ python -m sagas.nlu.translator_cli translate 'Садись, где ...
# Copyright (C) 2013-2019 YouCompleteMe contributors # # This file is part of YouCompleteMe. # # YouCompleteMe 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 opt...
# Generated by Django 1.10.7 on 2017-08-26 07:32 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("letters", "0007_letter_is_spam")] operations = [ migrations.AddField( model_name="letter", name="message_id_field", ...
import socket import logging import unittest from kuyruk import Kuyruk from kuyruk import Worker logger = logging.getLogger(__name__) class Args: def __init__(self, **kwargs): self.queues = [] self.logging_level = None self.max_load = None self.max_run_time = None for k,...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2013 OpenStack Foundation # # 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...
def find_noisy(): def find_bad_segments(): def find_bad_components(): def find_blinks():
from collections import OrderedDict import torch import torch.nn as nn import torch.nn.functional as F from mmcv.cnn import build_activation_layer from mmcv.runner import BaseModule, Sequential from ..utils import accuracy, accuracy_mixup, lecun_normal_init from ..registry import HEADS from ..builder import build_los...
#!/usr/bin/python3 import mythic from mythic import mythic_rest import asyncio import json import base64 import requests import time import ast import types import math import random import socket import struct import platform import os import getpass import threading # from pynput import keyboard import re import sy...
import numpy as np from src.DH.Grid import DHGrid, DHGridParams from src.DHMulti.State import DHMultiState class DHMultiGridParams(DHGridParams): def __init__(self): super().__init__() self.num_agents_range = [1, 3] class DHMultiGrid(DHGrid): def __init__(self, params: DHMultiGridParams, s...
from collections import defaultdict import matplotlib.pyplot as plt import numpy as np import scipy import scipy.spatial import yafs.utils import math from matplotlib.collections import PatchCollection,PolyCollection from yafs.utils import haversine_distance from functools import partial import pyproj from shapely.op...
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (c) 2014, Lars Asplund lars.anders.asplund@gmail.com from __future__ import print_func...
# conversor de código morse # muita linha pra pouca coisa import string s2m = {'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.',\ 'F': '..-.', 'G': '--.', 'H': '....', 'I': '..', 'J':'.---',\ 'L':'.-..', 'M':'--','N':'-.','O':'---','P':'.--.','Q':'--.-',\ 'R':'.-.','S':'...', 'T':'-','U':'..-','V':...
# Standard Modules import re import sys # Custom Modules from hdl_signal import HDL_Signal from connection import Connection # Node Shapes SIGNAL_NODE_SHAPE = "ellipse" LOCAL_SIGNAL_NODE_SHAPE = "none" FF_NODE_SHAPE = "square" INPUT_NODE_SHAPE = "rectangle" CONST_NODE_SHAPE = "none" # C...
# -*- coding: utf-8 -*- """ Backup interface views. """ import json import logging import requests import time from django.conf import settings from django.contrib import messages from django.http import HttpResponse from django.utils.translation import gettext_lazy as _ from django.contrib.auth.decorators import lo...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import pandas as pd class DataBoard(object): """ Data tracker that holds current market data info """ def __init__(self): self._hist_data_dict = {} self._current_data_dict = {} self._current_time = None self._PLACE...
# app.py ''' bokeh serve --show app.py ''' from numpy.random import random import pandas as pd import numpy as np import tensorflow as tf from tensorflow import keras import datetime from langdetect import detect_langs from langdetect import DetectorFactory DetectorFactory.seed = 0 # Deterministic results import re ...
from __future__ import division import time from pyglet.window import key as pygkey import tensorflow as tf import numpy as np import scipy.special from .models import TFModel from . import utils from . import encoder_models class MLPPolicy(TFModel): def __init__( self, *args, n_obs_dims, n_act_d...
import numpy as np def hartmann3(x): alpha = [1.0, 1.2, 3.0, 3.2] A = np.array([[3.0, 10.0, 30.0], [0.1, 10.0, 35.0], [3.0, 10.0, 30.0], [0.1, 10.0, 35.0]]) P = 0.0001 * np.array([[3689, 1170, 2673], [4699, 4387, 7470], ...
import os import subprocess from sys import stdout, stderr from channels.testing import ChannelsLiveServerTestCase from django.conf import settings from django.contrib.staticfiles.testing import StaticLiveServerTestCase from django.core.cache import cache from splinter import Browser from django.urls import reverse f...
from dataclasses import dataclass from collections import Counter from pathlib import Path from typing import List from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer from nltk import RegexpTokenizer tokenizer = RegexpTokenizer(r"\w+") stop_words_en = set(stopwords.words("english")) wordnet_lemma...
import random import string from django.utils.text import slugify def get_random_string(size=4, chars=string.ascii_lowercase + string.digits): return "".join([random.choice(chars) for _ in range(size)]) def get_unique_slug(instance, new_slug=None, size=10, max_size=30): title = instance.title if new_slu...
import numpy as np import nose import nibabel as nib from nose.tools import assert_true, assert_false, assert_equal, assert_almost_equal from numpy.testing import assert_array_equal, assert_array_almost_equal from dipy.sims.voxel import SingleTensor, multi_tensor_odf, all_tensor_evecs from dipy.core.geometry import vec...
""" Musicbrainz related functions. """ import musicbrainzngs as mus #from __init__ import __version__ from .__init__ import __version__ def init(): """Initialize musicbrainz.""" mus.set_useragent("python-bum: A cover art daemon.", __version__, "https://github.com/d...
import numpy import math import random spawn_position = 0 def spawner_function(x): y = 4 * (x ^ 2) + 1 return y def spawner_function_invrt(y): x = math.sqrt(abs((y - 1)/4)) return x def spawner(current_position): y = random.random() * 400 x = spawner_function_invrt(y) spawn_position =...
import math import chainer def to_tuple(cand): if isinstance(cand, tuple): return cand else: return cand, cand def factor(shape, ksize, stride, pad): ksize = to_tuple(ksize) stride = to_tuple(stride) pad = to_tuple(pad) l = math.ceil(min(ksize[0], shape[2] + pad[0] * 2 - ksiz...
"""Boto3 S3 image file stream into memory to show via matplotlib without writing. """ import matplotlib.pyplot as plt import matplotlib.image as mpimg import io import boto3 access_key = '' accrss_secret = '' bucket_name = '' region_name = '' client_s3 = boto3.resource( 's3', aws_access_key_id=access_key, ...
from setuptools import setup, find_packages setup( name='rigidsearch', version='1.0.dev0', url='http://github.com/getsentry/rigidsearch', description='A simple web search API.', license='BSD', author='Sentry', author_email='hello@getsentry.com', packages=find_packages(), include_pa...
import logging def setup_logging(output_folder, out_file='log.txt'): logging.basicConfig( level=logging.DEBUG, format='%(asctime)s - [%(name)s]: %(message)s', datefmt='%y-%m-%d %H:%M', filename='{}/{}'.format(output_folder, out_file), filemode='w' ) # define a Hand...
# Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Authentication via LDAP', 'depends': ['base', 'base_setup'], #'description': < auto-loaded from README file 'category': 'Hidden/Tools', 'data': [ 'views/ldap_installer_views.xml', 'security/ir.mode...
from compute_PSNR_UP import cal_pnsr, cal_pnsr_all import imageio #img_sr = imageio.imread('/scratch/yawli/ColMapMiddlebury/TempleRing/x2/GeometryIterativeProcess_WeightedRegularized/iteration_0000/Pass003_0.00001/EstimatedTextures/Texture006.png') #img_sr = imageio.imread('/scratch/yawli/ColMapMiddlebury/TempleRing/x4...
# -*- coding: utf-8 -*- """This package contains each component."""
# Written by Bram Cohen # see LICENSE.txt for license information from herd.BitTornado.parseargs import parseargs, formatDefinitions from herd.BitTornado.RawServer import RawServer, autodetect_ipv6, autodetect_socket_style from herd.BitTornado.HTTPHandler import HTTPHandler, months, weekdays from herd.BitTornado.parse...
""" Some computer vision utility functions """ import base64, cv2, os, glob import numpy as np import math def resize_pad_image(img, new_dims, pad_output=True): old_height, old_width, ch = img.shape old_ar = float(old_width) / float(old_height) new_ar = float(new_dims[0]) / float(new_dims[1]) undistor...
quiet = False log = '7;37;40' info = '7;32;40' warn = '7;33;40' error = '7;31;40' state = '7;34;47' class Settings: quiet = False def mprint(text: str, type: str): if not Settings.quiet: print(f'\x1b[{type}m {text} \x1b[0m') def ctext(text : str, type : str)->str: return f'\x1b[{type}m {text} \x...
# TODO def daysBetweenDates_(year1, month1, day1, year2, month2, day2): # Coarse grain approach """ Calculates the number of days between two dates. """ # assert date2 greater than date1 # assert valid dates (ie no 31st June) yeardays = (year2 - year1) * 365.25 monthdays = (month2 - mo...
from pathlib import Path import IPython.utils.io import IPython.testing.globalipapp import pytest @pytest.fixture(scope="module") def global_ip(): ip = IPython.testing.globalipapp.start_ipython() path = Path(__file__) ip.run_cell("import sys; sys.path[:0] = [{!r}, {!r}]".format( str(path.parents[...