content
stringlengths
5
1.05M
import os import pickle import numpy as np import tqdm from hmc.applications import newton_raphson from hmc.applications.fitzhugh_nagumo import posterior_factory from hmc.linalg import solve_psd from load_data import load_data def rejection_sampler(mean, std, logm, log_posterior): k = 9 low = mean - k*std ...
# coding: utf-8 from setuptools import setup, find_packages from distutils.command.build_py import build_py import os with open("README.md", "r", encoding="utf8") as file: long_description = file.read() with open("segregation/__init__.py", "r") as f: exec(f.readline()) def _get_requirements_from_files(gr...
#!/usr/bin/env python import socket, time, sys from walt.client import config from walt.client.link import ClientToServerLink from walt.client.auth import get_auth_conf EXPLAIN_CREDEDENTIALS='''\ These credentials must match your account at hub.docker.com. The username will also be used to identify your work on the Wa...
import os import sys import argparse import numpy as np import pandas as pd import smurff import time from scipy.special import expit from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import roc_auc_score class ActiveLearner(): def __init__(self, dataset, train_file, test_file, acquisition,...
from django.shortcuts import render,redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from appward.form import PostForm from .forms import UserRegisterForm # Create your views here. def register(request): if request.method =='POST': form = UserRegisterForm(r...
""" Create two circles and write coordinates into files. """ import pathlib import math import numpy def create_circle(R=0.5, center=(0.0, 0.0), ds=0.01): """ Generate coordinates of circle. Parameters ---------- R: float, optional radius; default: 0.5. center: 2-tuple of flo...
from itertools import islice from typing import List, Tuple from opt_einsum import contract_expression import numpy as np import torch from torch import Tensor, nn from spanet.network.symmetric_attention.symmetric_attention_base import SymmetricAttentionBase from spanet.network.utilities.linear_form import contract_...
from utils.re_utils import execute_query SAMPLE_NODE_COLLECTION = "samples_nodes" SAMPLE_SAMPLE_COLLECTION = "samples_sample" META_AQL_TEMPLATE = f""" let version_ids = (for sample_id in @sample_ids let doc = DOCUMENT({SAMPLE_SAMPLE_COLLECTION}, sample_id.id) RETURN {{ ...
from rest_framework import serializers from .models import SMSQueue, Recipients from django.contrib.auth.models import User class SMSQueueSerializer(serializers.ModelSerializer): """ Serializing all the data in the SMSQueue """ class Meta: model = SMSQueue # fields = ('message', 'recep...
from django.conf import settings from allauth.socialaccount.models import SocialAccount from dal import Orcid class OrcidOAuth: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be exe...
from swisscom_ai.research_keyphrase.embeddings.emb_distrib_interface import ( EmbeddingDistributor, ) import numpy as np from sentence_transformers import SentenceTransformer class EmbeddingDistributorSBert(EmbeddingDistributor): def __init__(self, model: str = "all-mpnet-base-v2"): self.model = Sent...
if __name__ == "__main__": with open("input_02.txt") as fhandle: instructions = fhandle.readlines() def get_digit(pos): return digits[pos[0]][pos[1]] def apply_command(pos, command): if command == "L": candidate = (pos[0], pos[1] - 1) elif command == "R": ...
from django.urls import path from . import views # Add URLConf urlpatterns = [ path('', views.index, name='index'), path('play/', views.play, name='play'), path('leaderboard/', views.leaderboard, name='leaderboard'), path('user-home/', views.user_home, name='user-home'), path('submission-result/<int...
# -*- coding: utf-8 -*- from .base_spider import BaseSpider class TienPhongSpider(BaseSpider): name = 'tienphong' allowed_domains = ['tienphong.vn'] start_urls = [ None, 'https://www.tienphong.vn/the-thao/', 'https://www.tienphong.vn/the-gioi/', None, None, ...
#!/usr/bin/env python """The setup script.""" from setuptools import setup, find_packages with open('README.md') as readme_file: readme = readme_file.read() history = "" requirements = ['websockets==8.1'] setup_requirements = [ ] test_requirements = [ ] setup( author="Lionell Loh", author_email='lio...
""" Copyright 2013 Rackspace Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software dist...
import glob import logging import os import re import posixpath import warnings try: from pxr import Usd except ImportError: warnings.warn("Warning: module pxr not found", ImportWarning) from kaolin import io logger = logging.getLogger(__name__) __all__ = [ 'Timelapse', 'TimelapseParser' ] class Ti...
from PIL import Image import pytesseract from tika import parser import docx2txt import os # pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe" # os.environ["TIKA_SERVER_JAR"] = 'generator/functions/tika-server.jar' # TIKA_SERVER_JAR="file:////tika-server.jar" class textParse: d...
import yaml import logging import hashlib import shutil import os, sys import subprocess from utils import * REQUIRED_KEYS_SINGLE = [ "project", "caravel_test", "module_test", "wrapper_proof", "wrapper_cksum", "openlane", "gds" ] class Project(): def __init__(self, args, directory, system_config): self.a...
import torch from torchvision import transforms import numpy as np class SingleObjectData(torch.utils.data.Dataset): def __init__(self, transform=None): self.transform = transform self.observation = torch.load("data/img/obs_prev_z.pt").unsqueeze(1) self.action = torch.load("data/img/action...
# Copyright 2015 Red Hat, 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/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
#!usr/bin/env python3 # -*- coding: utf-8 -*- """ Application that actually uses Strategy Pattern to provide multiple algorithms, a family of algorithms, to perform a specific task (solve a specific problem), so that the client can select which actual implementation to use at runtime. """ __author__ = 'Ziang Lu' fro...
import os from api import create_app, config def test_TestingConfig(): app = create_app() app.config.from_object(config.TestingConfig) assert app.config["TESTING"] is True assert app.config["SQLALCHEMY_DATABASE_URI"] == os.environ.get( "DATABASE_TEST_URL" ) assert app.config["SECRET_K...
# Licensed under an MIT open source license - see LICENSE from fil_finder import fil_finder_2D from astropy.io.fits import getdata import matplotlib.pyplot as p img, hdr = getdata("filaments_updatedhdr.fits", header=True) # Add some noise import numpy as np np.random.seed(500) threshs = [75, 95, 99] patches = [7, 1...
from flask import Blueprint, render_template from flask_cors import cross_origin bp = Blueprint("site", __name__) def init_app(app): app.register_blueprint(bp) @bp.route("/") @cross_origin() def index(): return render_template("index.html", title="Sierra Maestra") @bp.route("/nueva-coccion") @cross_origi...
import torch from .egt_training import EGTTraining from ..training_mixins import LinearLRWarmupCosineDecay, VerboseLR class EGT_MOL_Training(LinearLRWarmupCosineDecay, VerboseLR, EGTTraining): def get_default_config(self): config_dict = super().get_default_config() config_dict.update( ...
#!/usr/bin/env python """tilestache-render.py will warm your cache. This script is *deprecated* and will be removed in a future TileStache 2.0. This script is intended to be run directly. This example will save two tiles for San Francisco and Oakland to local temporary files: tilestache-render.py -c ./config.jso...
import json import os from pprint import pprint from time import sleep import boto3 from invoke import run, task PRINCE_FILENAME = 'prince-14.1-linux-generic-x86_64' ZIP_FILENAME = 'splat.zip' FUNCTION_NAME = 'splat' LAYER_FILENAME = 'requests_layer.zip' LAYER_NAME = 'requests_layer' def create_zip(prince_license):...
"""Flwidget module.""" # -*- coding: utf-8 -*- from PyQt6 import QtWidgets # type: ignore[import] from typing import TYPE_CHECKING if TYPE_CHECKING: from PyQt6 import QtGui # type: ignore[import] # pragma: no cover class FLWidget(QtWidgets.QWidget): """FLWidget class.""" logo: "QtGui.QPixmap" f_c...
print("DASHNextGen_Master_for_Task_Scheduler.py is starting") import DASHNextGen_Builder import DASHNextGen_File_delimited_date import DASHNextGen_Job_date_BIG_v2 import DASHNextGen_Service_Report_date_BIG_v2 import DASHNextGen_Service_EnteredDate_v2 print("DASHNextGen_Master_for_Task_Scheduler.py is done")
# .. License # # Copyright 2017 Bryan A. Jones # # 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, modify, merge, publ...
import bootcamp_utils def is_valid(seq): seq=seq.upper() for aa in seq: if aa not in bootcamp_utils.aa.keys(): raise RuntimeError(aa+' is not a valid amino acid.') def number_negative(seq): """Number of negative res in a protein seq""" seq=seq.upper() is_valid(seq) return...
"""The subtoken database table.""" from __future__ import annotations from sqlalchemy import Column, ForeignKey, Index, String from gafaelfawr.schema.base import Base __all__ = ["Subtoken"] class Subtoken(Base): __tablename__ = "subtoken" child = Column( String(64), ForeignKey("token.toke...
""" This is adapted from https://github.com/locuslab/TCN/blob/master/TCN/tcn.py revision 8845f88 licensed under MIT """ import torch.nn as nn from torch.nn.utils import weight_norm dict_activation = {"ReLU": nn.ReLU, "GELU": nn.GELU} class Chomp1d(nn.Module): def __init__(self, chomp_size): super(Chomp...
""" Utilities for working with the local dataset cache. This file is adapted from the AllenNLP library at https://github.com/allenai/allennlp Copyright by the AllenNLP authors. """ from __future__ import absolute_import, division, print_function, unicode_literals import json import logging import os import tempfile im...
from django.db import models from django.contrib.auth.models import User from django.db.models.fields.files import ImageField from PIL import Image # pillow image manipulation from django.dispatch import receiver from django.db.models.signals import post_save # Create your models here. class Guest(models.Model): ...
import torch from net import GoalkeeperNet, ActorNet from memory import MemoryBank class Agent: def __init__(self, state_size, action_size, mem_size=100): self.actor = ActorNet(state_size, action_size) self.goalkeeper = GoalkeeperNet(state_size) self.memory = MemoryBank(maxlen=mem_size) self.timestep = torch...
import numpy as np import sprl.util.misc as util from scipy.stats import multivariate_normal from scipy.stats import norm import matplotlib.patches as patches class Gaussian: def __init__(self, lower_bounds, upper_bounds, mu, sigma): self.lower_bounds = lower_bounds self.upper_bounds = upper_boun...
import unicodedata from django.conf import settings from django.db import models from django.utils import timezone from django_rq import job from iso639 import languages from lattices.models import LatticeNode, LemmaNode # from lattices.utils import make_lemma from lemmatized_text.models import LemmatizedText def ...
import os import json from DownloadItem import DownloadItem Listing = [] def clear_dupes(list): workarray = [] for item in list: if item not in workarray: workarray.append(item) return workarray def find_entries(): dirs = [] videofiles = ['mp4', 'avi', 'mkv'] from coll...
from django.http import HttpResponse def login_required(request): if 'user' in dir(request): if request.user.is_authenticated: return HttpResponse('success') return HttpResponse('fail') def blank(request): return HttpResponse('')
# pyTweener # # Tweening functions for python # # Heavily based on caurina Tweener: http://code.google.com/p/tweener/ # # Released under M.I.T License - see above url # Python version by Ben Harling 2009 import math class Tweener: def __init__(self): """Tweener This class manages all active tween...
import shutil from pathlib import Path # I know that this is not very resource efficient, but if it matters you are using this script wrong... def get_exercise_number(): try: value = int(input("Exercise number: ")) except ValueError: print("Please enter a number!") value = get_exercise...
# This is the template for the setcreds.py file. Make sure it is called setcreds.py, and add your api key below. import openai openai.api_key = '<YOUR-API-KEY>'
import logging import queue import os import OpenEIT.reconstruction import OpenEIT.backend import dash from dash.dependencies import Output, Event import dash_core_components as dcc import dash_html_components as html import plotly.plotly as py import plotly.graph_objs as go from flask import request #logger = logging...
import base64 import os.path as op from io import BytesIO import matplotlib matplotlib.use("agg") import matplotlib.pyplot as plt import nibabel as nib import numpy as np from dipy.segment.mask import median_otsu from nipype.utils.filemanip import save_json, load_json def reorient_array(data, aff): # rearrange...
from __future__ import division from __future__ import print_function import time import numpy as np import tensorflow as tf from tqdm import tqdm from dataset import load_data, evaluate, BatchSampler from model import Model FLAGS = tf.app.flags FLAGS.DEFINE_integer('seed', -1, '') FLAGS.DEFINE_string('dataset', 'b...
import sys #functions #multiplication function print('functions:') def multiply(f,n): mul=f*n return mul print('Multiplication of %d×%d=%d'%(10,5,multiply(10,5))) #use inputs and functions #print('Enter two values:') #i,j = map(int,sys.stdin.readline().split()) i,j = [int(x) for x in input("Enter...
from math import log from PIL import Image from scipy.misc import imresize import numpy as np def FractalDimensionF(I, width=256, plotflag=False, test=False): """ Input: - I: A 2D image - plotflag: A locical flag to enable/disable visualization. Default: False - width: larges...
from utils import add_gaussian_noise, symetrize from bm3d_1st_step import bm3d_1st_step from bm3d_2nd_step import bm3d_2nd_step from psnr import compute_psnr def run_bm3d(noisy_im, sigma, n_H, k_H, N_H, p_H, tauMatch_H, useSD_H, tau_2D_H, lambda3D_H, n_W, k_W, N_W, p_W, tauMatch_W, useSD_W, ...
from ._abstract import AbstractScraper from ._utils import get_minutes, normalize_string class TwoPeasAndTheirPod(AbstractScraper): @classmethod def host(self): return 'twopeasandtheirpod.com' def title(self): return self.soup.find('h2').get_text() def total_time(self): retu...
# test: indent_only quux( var_one, var_two, var_three, var_four) quux(var_one, var_two, var_three, var_four) quux(var_one, var_two, ) quux(var_one, var_two ) meal = ( spam, beans) meal = (spam, beans) meal = [ spam, beans] meal = [spam, beans] meal = [ ...
""" In order to remind myself of all the cli tools at my disposal in the computer, this module will take a random entry from the database and pass it to dunst. """ import webbrowser from mysql.connector import Error, connect def app_reminder(): """ We'll take out the information from the database and pas...
#! /usr/bin/env python3 """Prepare a phylogenetic tree for using in RASE. Author: Karel Brinda <kbrinda@hsph.harvard.edu> Licence: MIT """ import argparse import collections import os import pprint as ppprint import sys from ete3 import * NW_IN_FORMAT = 1 NW_OUT_FORMAT = 1 def test_file(fn): try: with...
# Return the "centered" average of an array of ints, which we'll say is the mean average of the values, # except ignoring the largest and smallest values in the array (list). # what do we do if smallest or largest is duplicated # - we only consider 1 of smallest and 1 of largest to be valid # what data type are we ex...
from text_train_sl import TrainClassifier import argparse from text_paramtuning import HyperParamTuning from cords.utils.config_utils import load_config_data import torch if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--lr', type=float, default=0.001, help='learning rate')...
#!/usr/bin/env python # -*- coding: utf_8 -*- def strQ2B(ustring): rstring = "" for uchar in ustring: inside_code = ord(uchar) if inside_code == 0x3000: inside_code = 0x0020 else: inside_code -= 0xFEE0 if inside_code < 0x0020 or inside_code > 0x7E: rstring += uchar else: rstring += unichr(insid...
#!/usr/bin/env python # -*- coding:utf-8 -*- from jinja2 import Template def redirect(request, html_path, **kwargs): request['coding_dream_location'] = html_path request['coding_dream_status'] = '307 Temporary Redirect' return b'' def render_html(html_path, **kwargs): html_path = html_path.lstrip('/...
import importlib import tensorflow as tf from trainer import dataset from trainer import model FLAGS = tf.app.flags.FLAGS tf.flags.DEFINE_string("model_config_path", "test", "File name for model parameter configuration") tf.logging.set_verbosity(tf.logging.INFO) def main(unused_argv): params = importlib.import_...
import json import logging import sys import time from datetime import (datetime, timedelta, tzinfo) from logging.handlers import RotatingFileHandler import cbint from cbapi.connection import CbAPISessionAdapter from cbapi.response import * from cbint.utils.daemon import CbIntegrationDaemon from requests import Sessio...
""" Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. For example, Given: s1 = "aabcc", s2 = "dbbca", When s3 = "aadbbcbcac", return true. When s3 = "aadbbbaccc", return false. """ class Solution: # @return a boolean def isInterleave(self, s1, s2, s3): l1 = len(s1); l2 = len(s2); ...
""" Low level functions for generating Duo Web API calls and parsing results. """ from __future__ import absolute_import from __future__ import print_function import six __version__ = '3.3.0' import base64 import collections import datetime import email.utils import hashlib import hmac import json import os import so...
from __future__ import absolute_import import logging from cytoolz import ( assoc, ) from eth_utils import ( to_tuple, ) from evm.consensus.pow import ( check_pow, ) from evm.constants import ( BLANK_ROOT_HASH, MAX_UNCLE_DEPTH, ) from evm.exceptions import ( BlockNotFound, TransactionNotFo...
class error_msgs: STAMP_NOT_FOUND = "Could not find stamp image!" STAMP_READ_FAIL = "Faild to read stamp image!" NO_FILES = "No files to stamp in chosen directory!" STAMP_UNSUPPORTED = "Unsupported stamp image format!" PREVIEW_FAIL = "Could not preview image!" FILE_READ_FAIL = "Could not read f...
__author__ = 'rencui' import numpy import json from textstat.textstat import textstat import utilities from sklearn.feature_extraction.text import * from sklearn import svm from tokenizer import simpleTokenize import logging from scipy.sparse import hstack, csr_matrix from sklearn.externals import joblib import pickle ...
#!/usr/bin/python # -*- coding: utf-8 -*- # ALLSKY FITS GENERATOR # =============================================== # Author: Ricardo Vallés Blanco (Timelab Technologies) # # The following code reads a ligthcurve and an # attitude file and generates an all sky image # of high resolution that later is exported to # WCS...
import pyyoutube from microdotphat import write_string, set_decimal, clear, show import config as cfg import math import datetime import time # Calls the YouTube API and returns the subscribers count. def get_subscribers(): api = pyyoutube.Api(api_key=cfg.API_KEY) result = api.get_channel_info(channel_id=cfg....
import json import numpy as np # import pandas as pd import matplotlib.pyplot as plt from live_plotter import live_plotter import torch dates = np.empty(0) repos = np.empty(0) f_list = [ '../adam_api_repo_curve_anomaly_detection/data/cleaned/NKY/Repo/repo_schedule_NKY_from_20130101_to_20190726.json',...
class Battery: def __init__(self, evaluator): raise NotImplementedError def get_action(self, current_state): raise NotImplementedError
import builtins import logging as python_logging from ._version import version_info, __version__ from datafaucet import logging from datafaucet import project from datafaucet import metadata from datafaucet import engines from datafaucet.paths import rootdir from datafaucet.resources import Resource from datafauce...
import os import tuneuptechnology client = tuneuptechnology.Client(os.getenv('API_EMAIL'), os.getenv('API_KEY')) locations = client.Locations.all() print(locations)
__author__ = 'Volodya'
# https://www.sanfoundry.com/python-program-solve-celebrity-problem/ def get_possible_celeb(matrix): """Take an n x n matrix that has m[i][j] = True iff i knows j and return person who is maybe a celebrity.""" possible_celeb = 0 for p in range(1, len(matrix)): if (matrix[possible_celeb][p] ...
# encoding: utf-8 import requests class HtmlDownloader(object): def get_content(self, url): if url is None: return headers = { 'Referer': 'https://baike.baidu.com/', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like ...
import Domoticz from adapters import adapter_by_model from zigbee_message import ZigbeeMessage class DevicesManager: def __init__(self): self.devices = {} def _register_device(self, domoticz_devices, device_data): model = device_data['model'] Domoticz.Debug('Device ' + model + ' ' + de...
""" A script to automatically download the f-net data. """ from datetime import datetime from os.path import isfile, join, isdir import click import numpy as np import obspy import sh from FnetPy import Client from logbook import FileHandler, Logger from tqdm import tqdm def get_download_dict(events): result = {...
from o365spray.core.utils.helper import Helper # type: ignore from o365spray.core.utils.colors import text_colors # type: ignore from o365spray.core.utils.writer import ThreadWriter # type: ignore from o365spray.core.utils.defaults import Defaults, DefaultFiles # type: ignore
'''OpenGL extension NV.gpu_program4 The official definition of this extension is available here: http://oss.sgi.com/projects/ogl-sample/registry/NV/gpu_program4.txt Automatically generated by the get_gl_extensions script, do not edit! ''' from OpenGL import platform, constants, constant, arrays from OpenGL import ex...
import os import pygame from PIL import Image import constants as C import exceptions as e ROOT = os.path.dirname(__file__) IMAGES = os.path.join(ROOT, "images") class Space: """Empty spaces on the sector tiles. """ def __init__(self, sector, location, num, pixel_x, pixel_y): self.sector = sec...
# coding: utf-8 from setuptools import setup, find_packages setup( name='zomato-top-ten', version = '1.0.0', description= 'top 10 restaurants in a category in a city', author = 'yvvarun', author_email = 'yvvarun@gmail.com', url = 'https://github.com/yvvarun/zomato-top-ten', packages=find_pa...
#!/usr/bin/python # coding: utf-8 import numpy as np import torch from utils.utils import AverageMeter class Tester(object): def __init__( self, model, test_loader, device, criterion, fts_flag=False, logger=None, verbose=1, ): self.mode...
from utils import load_dataset, save_pickle import os dtypes = dict( id=int, age=float, monthly_income=float, collateral_value=float, loan_amount=float, city=str, state=str, collateral_debt=float, verified_restriction="category", dishonored_checks="category", expired_debts="...
# Example script for building a component # Your code should go in this file... # Define script -> pack and upload to s3 -> deploy stack -> deploy component to device # To deploy as a component: # 1. Pack script using pack.sh # 2. Uncomment the 'component' area in cdk/data_ingest_stack.py... # this will push ...
""" --- Ångström --- Quaternion operations for Ångström Python package. """ import numpy as np class Quaternion(object): """ Quaternion class for quaternion operations and 3D rotations. """ def __init__(self, param_list): """ Initialize Quaternion with a 4 element list -> [w, x, y, z]...
#!/usr/bin/env python3 # # Copyright (c) 2020 Ivan Teplov # Licensed under the Apache License, version 2.0 # import os import shutil from pathlib import Path implementations_path = Path(__file__).parent.parent / "Implementations" implementations_folders = [] for (dirpath, dirnames, filenames) in os.walk(str(impleme...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def __init__(self, *args, **kwargs): self.pre = None def inverse_midoder(self, node): if node is N...
from typing import Optional from sqlalchemy.orm import Session from crud_models import UserCreate from db import DBContext from db_models import User from security import hash_password, manager @manager.user_loader def get_user(email: str, db: Session = None) -> Optional[User]: """ Return the user with the corr...
""" Solve optimal control by Tensorflow Optimal Control problem: Define: dx(t) = dynamic_t( x(t), u(t) ), where dx(t) means dx/dt evaluate at t x(0) = constant Goal: Minimize J = Sum_over_t( h_t( x(t), u(t) ), where h_t(*) is a function output a scale """ import tensorflow as tf class InvestmentOptimal...
from dataclasses import dataclass, field @dataclass class User: login : str cards : list = field(default_factory=list) money : int = 1000 bet : int = 0 position: int = None actions : list = field(default_factory=list) action : str = None ready : bool = False @...
# -*- coding: utf-8 -*- """ Created on Sat Sep 19 11:35:58 2020 @author: dkloe """ import numpy as np import cv2 import sys from PIL import Image font = cv2.FONT_HERSHEY_COMPLEX # -- coding: utf-8 -- src = cv2.imread('sketch4.jpg') src = cv2.fastNlMeansDenoising(src,None,10,7,21) def image_resize(i...
from typing import Union from posthog.models.filters.filter import Filter from posthog.models.filters.path_filter import PathFilter from posthog.models.filters.retention_filter import RetentionFilter from posthog.models.filters.stickiness_filter import StickinessFilter FilterType = Union[Filter, PathFilter, Retention...
import time from rate_limiter.limiter import ThreadingRateLimiter, DistributeRateLimiter, RedisTokenCache def test_single(): limiter = ThreadingRateLimiter(10) while True: time.sleep(0.05) if limiter.acquire(): print('I acquire!') else: print("I don't acquire") ...
from setuptools import find_packages, setup setup( name="openmdao-nsga", use_scm_version=True, packages=find_packages(where="src"), package_dir={"": "src"}, include_package_data=True, python_requires=">=3.7, <4", setup_requires=["setuptools_scm"], install_requires=["openmdao", "numpy", ...
from flask.ext.wtf import (Form, HiddenField, BooleanField, TextField, SelectField, SubmitField, FormField, ValidationError, required, equal_to, email, length) from flaskext.babel import gettext, lazy_gettext as _ from nano.models import Con...
# -*- coding: utf-8 -*- # Copyright (c) 2011 Plivo Team. See LICENSE for details. from plivo.core.freeswitch.inboundsocket import InboundEventSocket from plivo.core.errors import ConnectError from plivo.utils.logger import StdoutLogger import gevent def stop(inbound_event_listener, log): log.info("stopping now !"...
import os import argparse import configparser import sys from datetime import datetime, timedelta import logging DATETIME_FORMAT = "%Y-%m-%dT%H:%M:%SZ" class GPTracking: def __init__(self, gptconfig, dirpath, dirhome): self.gptconfig = gptconfig self.dirpath = os.path.dirname(os.path.realpath(_...
from __future__ import division import os import torch import numpy as np import torch.nn.functional as F from mmcv.runner import load_checkpoint from mmcv.parallel import MMDataParallel from gae.datasets import build_dataset, build_dataloader from gae.online_evaluation import online_evaluate from utils import (clu...
""" SPDX-FileCopyrightText: 2019 oemof developer group <contact@oemof.org> SPDX-License-Identifier: MIT """ from typing import Dict import numpy as np import pandas as pd import pytest from numpy.testing import assert_allclose from pandas.util.testing import assert_series_equal from windpowerlib.power_output import ( ...
"""Changing description Revision ID: 0a6a4733b607 Revises: ebfc9f03bec8 Create Date: 2018-06-26 13:36:12.088752 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '0a6a4733b607' down_revision = 'ebfc9f03bec8' branch_labels = None depends_on = None def upgrade():...
# Copyright (c) 2014 Mirantis 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/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, so...