content
stringlengths
5
1.05M
import zlib import sys import re import logging def heading_wrap(message): """[summary] Used to wrap a message in a heading, to include things such as a Footer, a Header, the length of the original message, and the CRC32 hash of the original message. Args: message ([str]): [A message to be wrapped i...
import os import random # Write a password generator in Python. # Be creative with how you generate passwords - strong passwords have a mix of lowercase letters, uppercase letters, numbers, and symbols. # The passwords should be random, generating a new password every time the user asks for a new password. # Include y...
__copyright__ = """ Copyright (C) 2009-2017 Andreas Kloeckner Copyright (C) 2014-2017 Aaron Meurer """ __license__ = """ 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, includ...
from collections import defaultdict, Counter, deque from functools import cache from itertools import product, pairwise from multiprocessing import Pool import math import re non_digits = re.compile('[^0-9]+') def sign(a, b, step=1): return int(math.copysign(step, b-a)) def autorange(a,b, step=1): if a == b:re...
import torch import numpy as np from scipy.io.wavfile import read from scipy.io.wavfile import write import audio.stft as stft from audio.audio_processing import griffin_lim import hparams _stft = stft.TacotronSTFT( hparams.filter_length, hparams.hop_length, hparams.win_length, hparams.n_mel_channels, hparams...
from opentracing import SpanContextCorruptedException from .context import SpanContext class InvalidSpanContextException(Exception): """InvalidSpanContextException is used when the provided span context instance does is not a W3C span context.""" pass class TextPropagator(object): """A W3C Trace C...
from collections import defaultdict, deque def make_graph(dictionary): adj_list = defaultdict(set) for word in dictionary: adj_list[word[0]].add(word[-1]) return adj_list def breadth_first_search(graph, origin, target): q = deque() q.appendleft([origin[-1], 1]) seen = set() while ...
# Copyright 2021 Zuva 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, softwa...
from typing import List, Tuple from abc import ABC, abstractmethod import pandas as pd from summer.utils import ref_times_to_dti from autumn.tools.project.timeseries import TimeSeries from .priors import UniformPrior def convert_targets_to_dict(raw_targets): """ Take the raw targets data structure, which is...
import os import base64 from config import Config class TemporaryFileManager(object): def __init__(self, extra_path=''): self.extra_path = extra_path self.dir = os.path.join(Config.APP_ROOT, Config.STATIC_DIR, extra_path) self.file = self.dir self.file_name = '' def open_file...
# Copyright 2012 Google 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 by applicable law or ag...
#!/usr/bin/env python3 import os import sys import json import time import io import warnings from ssos import SSOS from apollo.config import VERBOSE from apollo.config import DEBUG from apollo.config import FRAME_INTERVAL from apollo.config import ONCE_THEN_EXIT import apollo.utils def log(level, msg): if (le...
from heapq import heapify, heappop, heappush # Inspired by https://rosettacode.org/wiki/Huffman_coding#Python class HuffmanTree(object): def __init__(self, frequencies=None, iterable=None): """ A implementation of Huffman tree that provides encoding without loss of data. Paramat...
def get_answer_in_helper(): """Get an answer.""" return True def get_message(): return """ hello world! """
import setuptools long_description = """ # test.helper.yandex.alice.flask Class for autotests YandexAlice skill, that implemented as flask application """ setuptools.setup( name = 'tester_alice_skill_flask', version = '1.1', author = 'Vitaly Bogomolov', author_email = 'mail@vitaly-bogomolov.ru', ...
""" WiderFace evaluation code author: wondervictor mail: tianhengcheng@gmail.com copyright@wondervictor """ import os from os.path import join import tqdm import pickle import argparse import numpy as np from IPython import embed import sys import pickle import numpy as np sys.path.append("..") from widerface_evaluate...
import sqlite3 class DB: def __init__(self, db_file): self.conn = sqlite3.connect(db_file) def add_egg(self, trainer, dist, pokemon): c = self.conn.cursor() print("new egg:", trainer["id"], dist + "km", pokemon) c.execute("INSERT OR IGNORE INTO trainers(t_id, t_username) VALUES(?, ?)", (trainer["id"], train...
# Conjuntos em Pythons # Set só aceita valores unicos. são valores imutaveis # add (adiciona), update (atualiza), clear, discard. # union | (une) # intersection & (Todos os elementos presente nos dois sets) # difference - (elementos apenas no set da esquerda) # symmetric_difference ^ (Elementos que estão nos dois set, ...
# -*- coding: utf-8 -*- """ Profile: http://hl7.org/fhir/StructureDefinition/ChargeItem Release: STU3 Version: 3.0.2 Revision: 11917 Last updated: 2019-10-24T11:53:00+11:00 """ import io import json import os import unittest import pytest from .. import chargeitem from ..fhirdate import FHIRDate from .fixtures impor...
a,b = map(int, raw_input().split()) def gcd(a,b): if b==0: return a else: c = a%b return gcd(b,c) print gcd(a,b)
#!/usr/bin/python3 # -*- coding: utf-8 -*- # novell eDirectory access # https://www.novell.com/coolsolutions/feature/15853.html last access: 20.09.2018 # nds.py (Raphael Wimmer) import ldap class LDAPConnection: __port = 0 def __init__( self): self.__host = 'ldaps://ldap3.ur.de' self.__port ...
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
from typing import List import numpy as np import torch import torch.nn as nn from pydantic import validate_arguments from lantern import module_device, Tensor, Numpy from .standardized_image import StandardizedImage from .prediction import PredictionBatch class Model(nn.Module): def __init__(self): supe...
# Copyright 2020-2021 eBay 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 # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, so...
from functools import wraps, partial from inspect import getfullargspec, iscoroutinefunction from contextmgr import context_dict from contexts import PROGRESS_CONTEXT, REQUEST_CONTEXT, WORKER_CONFIG_CONTEXT from uitls import current_time from worker import get_worker from config import get_config, SECTION_WORKER from t...
a, b = input().split() print(a*int(b) if a < b else b*int(a))
# -*- coding: utf-8 -*- import hashlib import dsnparse class Connection(object): """The base connection class, you will most likely always use DsnConnection""" name = "" """string -- the name of this connection, handy when you have more than one used interface (eg, nsq)""" username = "" """the ...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # no...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'cnmfe_template.ui' # # Created by: PyQt5 UI code generator 5.15.6 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCor...
# which chromecasts to use chromecasts = ("This Room", "Another Room") # use external display or not use_display = False # which GPIO pins your rotary encoder is useing clk = 17 dt = 18 sw = 23 # how big for the font to be on the screen font_size = 55 # set to 'raspberry' for raspberry pi or 'orange' or orange pi ...
# -*- coding: utf-8 -*- # Generated by Django 1.11.16 on 2019-09-17 15:54 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('App', '0002_user_phonenumber'), ] operations = [ migrations.AlterField( ...
from getratings.models.ratings import Ratings class NA_Veigar_Mid_Aatrox(Ratings): pass class NA_Veigar_Mid_Ahri(Ratings): pass class NA_Veigar_Mid_Akali(Ratings): pass class NA_Veigar_Mid_Alistar(Ratings): pass class NA_Veigar_Mid_Amumu(Ratings): pass class NA_Veigar_Mid_Anivia(Ratings): ...
#!/usr/bin/python # -*- coding: utf-8 -*- import pytsk3 from optparse import OptionParser from utility import carpe_db import sys import pdb BUFF_SIZE = 1024 * 1024 class Carpe_File_Extractor(object): """docstring for Carpe_FS_Alloc_Info""" def __init__(self): super(Carpe_File_Extractor, self).__ini...
# A list is symmetric if the first row is the same as the first column, # the second row is the same as the second column and so on. Write a # procedure, symmetric, which takes a list as input, and returns the # boolean True if the list is symmetric and False if it is not. def is_symmetric(L): """ Returns Tru...
# rough work to probe / understand / visualize # the spherical multilevel grid data structures # produced for a given input spherical polygon # hopefully, this will help me discover some issues import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import proj3d from mpl_tool...
import os, sys import scvi import anndata import scanpy.api as sc import numpy as np if __name__ == '__main__': if len(sys.argv) != 2: sys.exit("Please make sure the result directory is given") result_dir = sys.argv[1] train_adata = anndata.read_h5ad(result_dir+os.sep+'train_adata.h5ad') test_...
import cv2 import math import progressbar from pointillism import * img_path = "port1-1024.jpg" stroke_scale = 2 stroke_width = 1 gradient_smoothing_radius = 1 original_image_blur = 51 # I think this has to be an odd number grid_scale = 3 color_k = 20 strokes_overlay_alpha = 0.4 batch_size = 100 palette_size = 20 ...
# -*- coding: utf-8 -*- """ Created on Sat Apr 11 15:18:39 2020 @author: kaisa """ from sqlalchemy import create_engine import matplotlib.pyplot as plt import os import re import numpy as np import pandas as pd from nltk.tokenize import word_tokenize from nltk.stem import WordNetLemmatizer from nltk.corpus import s...
#!/usr/bin/env python import sys import os import re import string import urllib import urllib2 import httplib import json import datetime import mimetypes import random import string import hmac import hashlib import requests import httplib import logging from models import * from urlparse import urlparse from reque...
# Generated by Django 2.2.4 on 2019-09-09 09:11 from django.conf import settings from django.db import migrations class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('inventory', '0005_auto_20190909_1202'), ] operations = [...
from django.urls import path from model_report.views import report, report_list urlpatterns = [ path('', report_list, name='model_report_list'), path('<slug>/', report, name='model_report_view'), ]
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Purpose Shows how to list all of the tables in an Amazon DynamoDB account. """ # snippet-start:[dynamodb.python.codeexample.MoviesListTables] import boto3 def print_tables(dynamodb=None): if not dynam...
# -*- coding: utf-8 -*- """ Created on Fri Jul 29 10:02:40 2016 @author: rflamary """ import sys import numpy as np import scipy as sp import scipy.io as spio import matplotlib.pylab as pl import deconv def get_fname(method,n,npsf,sigma,img): return 'res/{}_{}x{}_PSF{}_sigma{:1.3f}_{}.mat'.format(method,n,n,np...
# Copyright (c) 2016 Huawei Technologies Co., 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-2.0 # # ...
import pandas as pd import numpy as np import matplotlib.pyplot as plt currencies = [ 'AUDUSD', 'EURGBP', 'EURJPY', 'EURUSD', 'GBPJPY', 'GBPUSD', 'NZDUSD', 'USDCAD', 'USDCHF', 'USDJPY', ] for currency in currencies: print '\n' + currency print 'loading daily...' d...
from django.conf.urls.defaults import patterns urlpatterns = patterns("modpanel.views", (r"^$", "index"), (r"^wordfilter$", "wordfilter"), (r"^banlist$", "banlist"), #(r"^(?P<section>\w+)/$", "section", {"page": 1}), #(r"^(?P<section>\w+)/page(?P<page>\d+)$", "section"), #(r"^(?P<section>\w+)/(...
# Copyright (c) Gorilla-Lab. All rights reserved. import os import os.path as osp from typing import List, Union import numpy as np from gorilla.evaluation import DatasetEvaluators from .pattern import SemanticEvaluator, InstanceEvaluator CLASS_LABELS = [ "wall", "floor", "cabinet", "bed", "chair", "sofa", "tab...
import numpy as np from numpy.testing import assert_equal, assert_allclose, assert_raises from clusterlensing.clusters import ClusterEnsemble # ------ TOY DATA FOR TESTING -------------- # Note: some of this depends on cosmology & c(M) relation. # Assuming defaults of Planck13 and DuttonMaccio, respectively. toy_dat...
#-*- coding:Utf-8 -*- #To append the module to the path import os import sys sys.path.append(os.path.realpath('module')); import threading #Our custom modules from clientUDP import ClientUDP from clientTCP import ClientTCP from clientICMP import ClientICMP import display import fileReader path = './data/addresses....
__author__ = 'NoNotCar' import pygame import os from random import choice, randint import math import colorsys from itertools import count from collections import defaultdict tau = math.pi * 2 hpi = math.pi / 2 np = os.path.normpath loc = os.getcwd() + "/Assets/" pygame.mixer.init() from . import Colour class Scaled...
import threading Q=1000000 thread_list = [] def drink(max): global Q for i in range(0, max): Q-=1 for i in range(0, 2): thread_inst = threading.Thread(target=drink, args=(500000,)) thread_list.append(thread_inst) thread_inst.start() for thread in thread_list: thread.join() print(Q)
import json import datetime import glob import os from TweetModel import Tweet import logging import pathlib from mongoengine import NotUniqueError def TextToTweet(filename): ''' This is what takes the Tweets from the PHP script and puts them into the database using the TweetModel schema. It also has some ...
from database import connectToDatabase from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from pitchersToday import getStartingPitchersTodayGameTimeAndOpponentMap from typing import Dict from typing import List import json import os import smtplib import time SENDER = "pitcheralert@gm...
# Copyright 2013 OpenStack Foundation # Copyright 2015 IBM Corp. # # 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/L...
#!/usr/bin/env python import kamene.all as kamene from spylunking.log.setup_logging import console_logger from celery_connectors.utils import ev from network_pipeline.handle_packets import handle_packets log = console_logger( name='base_capture') def example_capture(): """example_capture An example ca...
""" unix/tcp server socket used for communication with the ondevice daemon """ import ondevice from ondevice.core import config from ondevice.core import state as state_ import cherrypy import json import logging import os import threading from six.moves import urllib class ControlSocket: def _toJson(self, data)...
from pprint import pprint import math from typing import List, Tuple, Dict from algorithm.dummy import is_consistant,select_unassigned_variable as dummy_select_unassigned_variable from model.case import case from utils.paths.points import get_constrained_nighbours from utils.paths.modifiers import refresh_connected_ter...
import configparser import datetime import logging import os import pandas import random import sys from django.core.management.base import BaseCommand from django.db import transaction from django.utils import timezone, dateformat sys.path.insert(1, '../../') # Find our main project from django_property_filter.uti...
def test_convert_from_bytes32(get_contract_with_gas_estimation): test_address = "0xF5D4020dCA6a62bB1efFcC9212AAF3c9819E30D7" test_bytes = b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xF5\xD4\x02\x0d\xCA\x6a\x62\xbB\x1e\xfF\xcC\x92\x12\xAA\xF3\xc9\x81\x9E\x30\xD7" # noqa: E501 test_bytes_to_address =...
import re from collections import defaultdict from typing import Callable, Optional, Union, DefaultDict Scrubber = Callable[[str],str] def create_regex_scrubber( regex: str, function_or_replace_string: Union[Callable[[int], str], str] ) -> Scrubber: def scrub(text: str) -> str: if isinstance(function_...
import argparse from pathlib import Path import torch import torch.nn.functional as F from torch_geometric.datasets import Entities from torch_geometric.nn import FastRGCNConv, RGCNConv from torch_geometric.utils import k_hop_subgraph parser = argparse.ArgumentParser() parser.add_argument('--dataset', type=str, ...
import http_server import bottle application = bottle.default_app()
import pytest import os import numpy as np from flare.otf import OTF from flare.gp import GaussianProcess from flare.struc import Structure from flare.dft_interface.vasp_util import * # ------------------------------------------------------ # test otf runs # ---------------------------------------...
# # @license # Copyright (c) 2020 XGDFalcon®. All Rights Reserved. # # # XGDFalcon LLC retains all intellectual property rights to the code # distributed as part of the Control Point System Software (CPSS) package. # """ WSGI config for django-cpss-vimeo project. It exposes the WSGI callable as a module-level variable...
from .arn import * from .stream import StreamFactory from .stream_consumer import StreamConsumerFactory class Kinesis: Arn = ArnFactory Stream = StreamFactory StreamConsumer = StreamConsumerFactory __all__ = ["Kinesis", "StreamArn", "StreamConsumerArn"]
"""The basic User class.""" from time import time from MiscUtils.Funcs import uniqueId class User(object): """The base class for a UserKit User.""" ## Init ## def __init__(self, manager=None, name=None, password=None): self._creationTime = time() self._manager = None self._na...
#!/usr/bin/env python3 """ Use this script to add a user to courses. Any user added to a course will be an instructor. """ import argparse import json from os import path import subprocess import sys from sqlalchemy import create_engine, MetaData, Table, bindparam, and_ CONFIG_PATH = path.join(path.dirname(path.real...
from dataclasses import dataclass, field from typing import Optional from transformers import Seq2SeqTrainingArguments # NOTE: The transformers package is updated during our work # , our "WrappedSeq2SeqTrainingArguments" is now a feature named "Seq2seqTrainingArguments" @dataclass class WrappedSeq2SeqTrainingArgument...
"""empty message Revision ID: 00dc014defa9 Revises: Create Date: 2021-07-11 10:05:28.256991 """ import sqlalchemy as sa from sqlalchemy.dialects import postgresql from alembic import op # revision identifiers, used by Alembic. revision = "00dc014defa9" down_revision = None branch_labels = None depends_on = None ...
from django.shortcuts import render from django.core.exceptions import PermissionDenied from django.views.generic import View from django.contrib.auth.models import User from django.contrib.auth.mixins import LoginRequiredMixin class UserTableView(LoginRequiredMixin, View): def get(self, request): if req...
# -*- coding: utf-8 -*- # author: Tiancheng Zhao import logging import copy class Agent(object): """ Abstract class for Agent (user or system) """ def __init__(self, domain, complexity): self.domain = domain self.complexity = complexity def step(self, *args, **kwargs): "...
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2005 onwards University of Deusto # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. # # This software consists of contributions made by many individuals, # list...
import factory class CourseFactory(factory.django.DjangoModelFactory): class Meta: model = "courses.Course" name = factory.Sequence(lambda n: f"Course {n}") @factory.post_generation def grade_levels(course, create, extracted, **kwargs): if not create: return if e...
from fastapi import Depends from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials from okdata.resource_auth import ResourceAuthorizer from clients import setup_keycloak_client, get_keycloak_config from .errors import ErrorResponse from .origo_clients import dataset_client def keycloak_client(keycloak...
""" Testing a pypy3 to run simple but CPU intensive calculation To run on pypy, install pypy3 then run: >> pypy3 try_pypy.py """ import sys from time import perf_counter def count(n): total = 0 for i in range(1, n): for j in range(1, n): total += (i+j) return total if __name__ == ...
# -*- coding: utf-8 -*- import numpy as np from ..base import Property from ..models.measurement.categorical import CategoricalMeasurementModel from ..types.prediction import MeasurementPrediction from ..types.state import CategoricalState from ..types.update import Update from ..updater import Updater class HMMUpda...
import taichi as ti x = ti.Matrix(2, 2, ti.i32) @ti.layout def xy(): ti.root.dense(ti.i, 16).place(x) @ti.kernel def inc(): for i in x(0, 0): delta = ti.Matrix(2, 2) delta(1, 1).assign(3) x(1, 1)[i] = x(0, 0)[i] + 1 x[i] = x[i] + delta for i in range(10): x(0, 0)[i] = i inc() for i in ra...
# -*- coding: utf-8 -*- from .core import generate_palette, COLORBLIND_FRIENDLY_PALETTE from .details import plot_details from .gantt import plot_gantt, plot_diff_gantt from .lifecycle import plot_lifecycle from .series import plot_series
# Generated by Django 2.0.10 on 2019-08-16 13:51 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('pumps', '0027_auto_20190816_2243'), ] operations = [ migrations.RemoveField( model_name='sector', name='pump_1_operating_ra...
# Copyright 2020-2022 OpenDR European Project # # 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 ...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- # Packages of Christophe from datetime import datetime import time import calendar import json import math import os,sys import socket import traceback import urllib2 as urllib user = "GW3" test = True # True to run the code locally # False to implement the code on the ...
from django.contrib import admin from recipes.models import Recipe, Tag @admin.register(Recipe) class RecipeAdmin(admin.ModelAdmin): list_display = ["title", "username", "created_dt", "approved"] list_editable = ["approved"] exclude = [ "search_vector", "ingredients_html", "instruc...
# -*- coding: utf-8 - # # This file is part of restkit released under the MIT license. # See the NOTICE for more information. from __future__ import with_statement import os import optparse as op import sys # import pygments if here try: import pygments from pygments.lexers import get_lexer_for_mimetype ...
# Copyright 2019 Marc Mosko # # 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 writ...
# Generated by get_e212.py # Based on https://www.itu.int/pub/T-SP-E.212B-2016 networks = \ {202: 'GR', 204: 'NL', 206: 'BE', 208: {1: 'MC', 2: 'FR', 3: 'FR', 4: 'FR', 5: 'FR', 6: 'FR', 7: 'FR', 8: 'FR', 9: 'FR', 10: 'MC', 11: 'FR', 12: 'F...
import click from rlpy.domains import ChainMDP from rlpy.tools.cli import run_experiment import methods def select_domain(chain_size): return ChainMDP(chain_size=chain_size) def select_agent(name, domain, max_steps, seed, **kwargs): if name is None or name == "lspi": return methods.tabular_lspi(dom...
from bs4 import BeautifulSoup from kik_unofficial.datatypes.exceptions import KikApiException class Peer: def __init__(self, jid): self.jid = jid class User(Peer): def __init__(self, data: BeautifulSoup): if 'jid' not in data.attrs: raise KikApiException("No jid in user xml {}"....
try: from setuptools import setup except ImportError: from distutils.core import setup setup(name='django-selectize', version='1.3', description='django-selectize is a Django app based on Selectize.js that help you to create Select and Multiselect widgets in Django forms.', author='Djangoer', author_email=...
import csv import logging import pathlib import shutil import sqlite3 import tempfile from pathlib import Path import click logging.basicConfig(level=logging.INFO, # level=logging.ERROR, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s') logger = logging.getLogger(__name__) # maps c...
import numpy as np import matplotlib.pyplot as plt import mplEasyAnimate as mple from tqdm import tqdm def mkdata(): return np.linspace(0, 10, 10), np.random.uniform(size=(10)) anim = mple.autoAnimation('Test2.mp4', 10, framebuffer=5, pbar=True) for i in range(10): fig, ax = plt.subplots(1, 1) x, y = mkda...
import streamlit as st def write(text): st.write(text + " (by st_extensions)")
import argparse import ast import subprocess def on_terminate(proc): print("process {} terminated".format(proc)) def str2list(s): v = ast.literal_eval(s) if type(v) is not list: raise argparse.ArgumentTypeError("Argument \"%s\" is not a list" % (s)) return v def str2bool(v): if isinstance(...
from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.db.models import Q from django.http import HttpResponse from django.shortcuts import render, redirect, get_object_or_404 from django.utils.decorators import method_decorator from django.views import View fr...
try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup def find_packages(exclude=None): return [] readme = ''' ''' with open('requirements.txt') as f: requirements = [line.strip() for line in f.read().splitlines() if l...
from .settings import * import dj_database_url DEBUG = False DATABASES = { 'default': dj_database_url.config() } STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MIDDLEWARE.append('whitenoise.middleware.WhiteNoiseMiddleware') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' ...
import numpy as np import imgviz def test_label2rgb(): data = imgviz.data.arc2017() H, W = data["class_label"].shape[:2] labelviz = imgviz.label2rgb(label=data["class_label"]) assert labelviz.dtype == np.uint8 assert labelviz.shape == (H, W, 3) labelviz = imgviz.label2rgb(label=data["class_...
#!/usr/bin/env python """ Original from: https://github.com/jpmens/mosquitto-auth-plug/tree/master/contrib/python """ import sys from getpass import getpass import hashing_passwords as hp pw = getpass("Enter password: ") pw2 = getpass("Re-enter password: ") if pw != pw2: sys.exit("Passwords don't match!") print...
from httmock import urlmatch VALID_TOKEN = "valid-token" # nosec INVAVLID_TOKEN = "bad-token" # nosec @urlmatch(path=".*/data/(.*)$") def download_mock(url, request): if request.headers.get("X-Auth-Token", "") == VALID_TOKEN: return {"status_code": 200, "content": "test content"} return {"status_co...
""" Definition of the blog app. URLs """ from django.urls import path from django.contrib.auth import views as authViews from . import views app_name = "blog" urlpatterns = [ path("", views.PostList.as_view(), name="journal"), path("<int:pk>", views.PostDetail.as_view(), name="article"), path("sign_in", ...
import json from redata import settings def load_json_data(file_name): with open(file_name) as json_file: data = json.load(json_file) return data def update_panel_element(table, panel, panel_class, **kwargs): panel_obj = panel_class(table, **kwargs) targets = load_json_data(settings.TARG...