content
stringlengths
5
1.05M
import pkgutil import six def import_submodules(context, root_module, path): """ Import all submodules and register them in the ``context`` namespace. >>> import_submodules(locals(), __name__, __path__) """ for loader, module_name, is_pkg in pkgutil.walk_packages( path, roo...
""" pyABF - A Python interface to files in the Axon Binary Format (ABF) by Scott Harden Documentation and code examples, and more can be found at: https://github.com/swharden/pyABF """ __version__ = '2.2.2' import sys if sys.version_info < (3, 6): sys.stdout.write("ERROR: pyabf "+__version__+" requires ...
"""Tests related to scutil module.""" import datetime import unittest.mock import numpy import satpy import pyresample.geometry import pytest from . import utils def test_get_all_areas(fake_multiscene): """Test getting areas from multiscene.""" from sattools.scutil import _get_all_areas_from_multiscene ...
import requests import pathlib import re _VERSIONS_URL = "https://raw.githubusercontent.com/actions/python-versions/main/versions-manifest.json" # noqa def parse_version(v): return tuple(int(part) for part in re.split("\W", v)[:3]) def get_github_python_versions(): versions_json = requests.get(_VERSIONS_...
# coding: utf8 from pprint import pprint import argparse import batou import batou.component import batou.environment import batou.lib.file import batou.template import socket import sys import time import xmlrpc.client class DNSAliases(batou.component.Component): """Set up DNS aliases under the .fcio.net domain...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Web client for SAML login. Make SAML2 protected webpage accesable for scripts. Working with Apache mod_auth_mellon webserver and Win ADFS server """ __author__ = "Chris Siedler" __contact__ = "mail@chris-siedler.at" __date__ = "2022/03/04" __license__ = "MIT" __statu...
from django.db import models # Create your models here. class PasswdModel(models.Model): ip = models.CharField(max_length=15) passwd = models.CharField(max_length=40) datetime = models.DateTimeField(auto_now_add=True) def __str__(self): return self.ip
import cgi import traceback from .util import dedent from .ast import source, source_nows from collections import defaultdict class TextDocument: def __init__(self): self.data = "" def add(self, data): self.data += data def clone(self): rval = self.__class__() rval.data...
import os import cv2 import numpy as np def pyConcat(img_folder='./img', border={'top':7, 'bottom':2, 'left':0, 'right':17}, output_file='full_screenshot.png'): img_list = os.listdir(img_folder) imgs = [cv2.imread(os.path.join(img_folder, fname))[border['top']:-border['bottom'], border['left']:-border['right'...
#!/usr/bin/env python import argparse import random import time def loadBaseModel(filePath): base = list() if filePath: with open(filePath) as f: for line in f: base.append(line.strip().lower()) return base def generateModel(baseModel=[], base=1): model = dict() if baseModel: for word ...
import pandas as pd def _get_categories_categorized(data) -> pd.DataFrame: counts = {} for ix in range(len(data)): category = data.get_category(ix) try: counts[category] += 1 except KeyError: counts[category] = 1 return pd.DataFrame(dict( category_in...
# encoding: utf-8 from __future__ import unicode_literals from .base import BaseImporter from data_importer.readers import XLSReader class XLSImporter(BaseImporter): def set_reader(self): ''' [[1,2,3], [2,3,4]] ''' sheet_by_name = self.Meta.sheet_name or None sheet_by_...
########################## # Test script to check if doctrines are used in 'add_tech_bonus' expression - with NSB they have separate syntax # By Pelmen, https://github.com/Pelmen323 ########################## import glob import re import os from ..data.doctrine_categories import combined_doctrines_list from ..test_clas...
"""The constants of the rayvision_max.""" PACKAGE_NAME = "rayvision_max"
import re, pywikibot, operator, os from natsort import natsorted from datetime import datetime #os.chdir(r'projects/treisijs') lvwiki = pywikibot.Site("lv", "wikipedia") file = open("tresija saraksts-raw dsdfsdfsdf- fdfsfsdfsd v2-maina.txt", "w", encoding='utf-8') wplist = set(['abwiki', 'acewiki', 'adywiki', 'afwi...
#! /usr/bin/env python import os import sys import logging import re import csv import itertools import copy import gekgo_util from gekgo_util import RunLogger, get_dict_reader from data_classes import Sample, SampleDatabase, Tissue, DnaExtraction _LOG = RunLogger(name=__file__, log_to_stderr=True, l...
"""Test the filter_data methods.""" import os import pathlib from datetime import datetime from billing import util def test_predicate_previous_date(): """Test predicate with a previous date.""" target_date = datetime(2021, 10, 1, 0, 0, 0) test_accept_row = [0, 1, 2, 3, 4, 5, 6, 7, 8, "2021-10-16"] ...
from datetime import datetime from django.contrib.auth import get_user_model from django.contrib.sites.shortcuts import get_current_site from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from django.template.defaultfilters import slugify from .helper impor...
from util.util import autoregister # Registers all models in lrs for admin autoregister('lrs')
k = int(input()) s = list(input()) t = list(input()) cnt = [k for _ in range(9)] cnt_s = [0 for _ in range(9)] cnt_t = [0 for _ in range(9)] ans = 0 for i in range(4): s[i] = int(s[i]) t[i] = int(t[i]) cnt[s[i]-1] -= 1 cnt[t[i]-1] -= 1 cnt_s[s[i]-1] += 1 cnt_t[t[i]-1] += 1 for x in range(1, 10)...
# -*- coding: utf-8 -*- """Top-level package for Mir Framework.""" __author__ = """Steven Brien""" __email__ = 'spbrien@gmail.com' __version__ = '0.1.0'
import math from datetime import datetime, timezone, timedelta, time import pytz from django.utils import timezone as tz from extutils.dt import ( is_tz_naive, now_utc_aware, localtime, parse_to_dt, time_to_seconds, TimeRange, TimeRangeEndBeforeStart, make_tz_aware ) from tests.base import TestCase __all__ =...
#!/usr/bin/env python # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "Li...
# Copyright 2021 UW-IT, University of Washington # SPDX-License-Identifier: Apache-2.0 from unittest import TestCase from uw_libraries.dao import MyLib_DAO, SubjectGuide_DAO class TestDao(TestCase): def test_mylib_dao(self): self.assertEqual(MyLib_DAO().service_name(), "libraries") def test_subject...
import sys import instaloader if "__main__" == __name__: if not len(sys.argv) == 3: sys.exit( "Invalid usage, please use: python script.py <username-to-login-with> <username-to-check>") L = instaloader.Instaloader() username_login = sys.argv[1] username_to_check = sys.argv[2] L.i...
import json data = {"a":1,"b":2,"c":3} jsonValue = json.dumps(data) print ("jsonValue = %s" % jsonValue ) pythonValue = json.loads(jsonValue) print("pythonValue = %s " % pythonValue )
from enum import Enum class Motion(Enum): FORWARD = 'F' BACKWARD = 'B' LEFT = 'L' RIGHT = 'R' HALT = 'H' class Sound(Enum): LOW_SLOW = 'V' HIGH_SLOW = 'X' LOW_FAST = 'Y' HIGH_FAST = 'Z' motions = [m.value for m in Motion] sounds = [m.value for m in Sound]
# -*- coding: utf8 -*- """ .. module:: burpui.ext.cache :platform: Unix :synopsis: Burp-UI external cache module. .. moduleauthor:: Ziirish <hi+burpui@ziirish.me> """ from flask_caching import Cache cache = Cache( config={ "CACHE_TYPE": "simple", "CACHE_THRESHOLD": 50, "CACHE_DEF...
# Copyright (c) OpenMMLab. All rights reserved. from typing import Dict, List, Optional, Union import mmcv import numpy as np import torch import torch.nn as nn from mmcv.ops import RoIPool from mmcv.parallel import collate, scatter from mmcv.runner import load_checkpoint from mmdet.datasets import replace_ImageToTens...
from django import forms from django.forms import widgets from django.core.validators import validate_email class UserRegistrationForm(forms.Form): username = forms.CharField(max_length=100, min_length=3, required=True) first_name = forms.CharField(min_length=3, max_length=30, required=True) last_name = f...
# coding=utf-8 import urllib2 __author__ = 'xubinggui' from gevaent import monkey; monkey.patch_socket() import gevent def f(n): for i in range(n): print gevent.getcurrent(), i g1 = gevent.spawn(f, 5) g2 = gevent.spawn(f, 5) g3 = gevent.spawn(f, 5) g1.join() g2.join() g3.join() def f(url): print('G...
#!/usr/bin/env python3 #Tool to edit old Multideterminant and PBC HDF5 for LCAO (Can be extended to any HDF5 file) #Takes as argument the name of the HDF5 file #Will transform the group KPTS_0 into Super_twist #Will change the Value of SpinUnResticted to SpinRestricted import h5py import sys file_name = sys.argv...
""" Django settings for backend project. Generated by 'django-admin startproject' using Django 2.1.7. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os im...
import os import sys import time import logging import traceback import functools import numpy as np lib_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)),'lib') def exception_handler(exc_type, exc_value, exc_traceback): """Print exception with a logger.""" # Do not print traceback if the except...
import pathlib import numpy as np def get_filenames_of_path(path: pathlib.Path, ext: str = '*'): """Returns a list of files in a directory/path. Uses pathlib.""" filenames = [file for file in path.glob(ext) if file.is_file()] filenames.sort() # sort alpabetically return filenames class Metrics: ...
import unittest from switchmng import config from switchmng.schema import * from switchmng.importer import IMPORT_TYPES class Test_Config(unittest.TestCase): """Test class that tests config parser""" def setUp(self): config.parse_arguments([]) def _cli_arg(self, args): # Check if args is...
from distutils.core import setup setup( name='atax', version='0.1dev', packages=['atax',], license='MIT', package_dir={ 'atax': 'atax' }, package_data={ 'atax': ['data/*.txt'] }, include_package_data=True, )
import pandas as pd import os from WORC.addexceptions import WORCKeyError # All standard texture features accepted texture_features = ['GLCM', 'GLDZM', 'GLRLM', 'GLSZM', 'NGLDM', 'NGTDM'] def convert_radiomix_features(input_file, output_folder): ''' Convert .xlsx from RadiomiX to WORC compatible .hdf5 format...
# # ___ _ ____ ____ # / _ \ _ _ ___ ___| |_| _ \| __ ) # | | | | | | |/ _ \/ __| __| | | | _ \ # | |_| | |_| | __/\__ \ |_| |_| | |_) | # \__\_\\__,_|\___||___/\__|____/|____/ # # Copyright (c) 2014-2019 Appsicle # Copyright (c) 2019-2020 QuestDB # # Licensed under the Apache...
import pytest from django.core import mail from django.test import override_settings from django.utils import translation from notifications.models import NotificationTemplate, NotificationType from notifications.tests.utils import check_received_mail_exists from payments.utils import get_price_period_display from res...
# Count inversions in an array # Tells us about how far is the array from being sorted # NAIVE APPROACH in the O(n^2) # Initial counter element and final temporary list tempList = list() counter = 0 # Function that takes initialArray, counter element and temporary final list def naiveCountInversion(toDoArray, temp...
from flask import Blueprint, current_app, request from sqlalchemy.sql.expression import true from controle_contas.ext.serializer.models import ( EntrySchema, UserSchema, SourceSchema, ) from marshmallow import ValidationError from sqlalchemy import and_ from controle_contas.ext.db.models import Entry, Sourc...
# -*- coding: utf-8 -*- # Copyright (C) 2014 Denys Duchier, IUT d'Orléans #============================================================================== from .event import Event2, Event3 class LightOnEvent(Event2): NAME = "light-on" def perform(self): if not self.object.has_prop("lightable"): ...
# add code below for problem 2
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ This file is part of the complex_terrain algorithm M. Lamare, M. Dumont, G. Picard (IGE, CEN). List of functions for the DEM horizon tool: - horizon - queues - horizon forward - horizon backward - slope The algorithm is based on Dozier et al. 1980...
import json import unittest from questionnaire import Answer, Question, Questionnaire INVALID_QUESTIONNAIRE = dict( id="1", title="Position 1", questions=[ dict( id="1", question="Questionnaire Question 1", answers=[ dict( id=...
# Generated by Django 2.0.8 on 2018-08-21 09:53 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('datasources', '0002_add_access_control_groups'), ] operations = [ migrations.AlterField( model_...
''' This program creates model directories varied by mass and metallicity (z). Lower mass models use 1M_pre_ms_to_wd, while higher mass models use make_co_wd. In the future, extra functionality will be added to make the highest mass models run on make_o_ne_wd or make_he_wd. The individual directories are then organized...
from setuptools import setup from setuptools.command.install import install from distutils.sysconfig import get_python_lib import glob import shutil __version__ = "0.0.1" __library_file__ = './lib/pyStag.cpython-38-darwin.so' class CopyLibFile(install): """" Directly copy library file to python's site-packag...
from tkinter import * import tkinter as tk from tkinter import font,ttk import calendar window = tk.Tk() window.title("CALENDAR") window.geometry("450x300") window.iconbitmap("vk.ico") window.config(bg="#F59E8B") def c(): year = n.get() month = m.get() if month=="JANUARY": me=1 elif month=="FE...
from django.apps import AppConfig class {{ cookiecutter.first_app_name.split('_')|map('capitalize')|join('') }}Config(AppConfig): name = '{{ cookiecutter.pkg_name }}.{{ cookiecutter.first_app_name }}' verbose_name = '{{ cookiecutter.project_name }}: {{ cookiecutter.first_app_name.split('_')|map('capitalize')|...
# -*- coding: utf-8 -*- """ LoggedFS-python Filesystem monitoring with Fuse and Python https://github.com/pleiszenburg/loggedfs-python tests/lib/pre.py: Stuff happening before test(s) Copyright (C) 2017-2020 Sebastian M. Ernst <ernst@pleiszenburg.de> <LICENSE_BLOCK> The contents of this file are subject to the A...
#Задача 10.Вариант 46 #Напишите программу "Генератор персонажей" для игры. Пользователю должно быть #предоставлено 30 пунктов, которые можно распределить между #четырьмя характеристиками: Сила, Здоровье, Мудрость и Ловкость. #Надо сделать так, чтобы пользователь мог не только брать эти пункты из общего #"пула", но и во...
""" K-Nearest-Neighbors Graph ------------------------- """ from typing import Optional from typing import Union import numpy as np import scipy.sparse as sp # type: ignore from anndata import AnnData # type: ignore import metacells.parameters as pr import metacells.utilities as ut __all__ = [ "compute_obs_ob...
from plugins_summary.component_summary import ComponentSummary class JupyterComponentSummary(ComponentSummary): def get_component_type(self): return 'jupyter' def get_component_summary(self, component, application): return {}
l = int(input()) # min d = int(input()) # max x = int(input()) m = l # max set to min n = None def digit_sum(num): return sum(int(char) for char in str(num)) for i in range(l, d + 1): if digit_sum(i) == x: if n is None: n = i if i > m: m = i print(n) pri...
import os import re import time import yaml import random import pickle import argparse import numpy as np import pandas as pd from tqdm import tqdm from functools import reduce from sklearn.metrics import accuracy_score, f1_score import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.utils....
# Generated by Django 2.1.5 on 2019-03-09 05:31 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0003_auto_20190220_0502'), ] operations = [ migrations.AddField( model_name='authorprofile', name='isValid', ...
from django.db import models class Story(models.Model): id = models.IntegerField(primary_key=True) by = models.CharField(max_length=64, blank=True) time = models.IntegerField(blank=True, null=True) descendants = models.IntegerField(blank=True, null=True) score = models.IntegerField(blank=True, nul...
import numpy as np import tensorflow as tf import os def get_filename_queue(split_file, data_dir): with open(split_file, 'r') as f: filenames = f.readlines() filenames = [os.path.join(data_dir, fname.strip()) for fname in filenames] for f in filenames: if not os.path.exists(f): ...
from keras import applications vgg = applications.VGG16(include_top=True, weights='models/images_model', classes=16) #vgg1 = applications.VGG16(include_top=True, weights='./vgg16_weights_th_dim_ordering_th_kernels_Holistic_91.11.h5', classes=16) import numpy as np import numpy as np from keras.preprocessing import imag...
# Mrs # Copyright 2008-2012 Brigham Young University # # 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 o...
#! /usr/bin/python3 """ Project: py-data-structs File: avl_tree.py Author: Ryan Rushton Email: ryan.rushton79@gmail.com Github: github.com/rushton3179 Date Created: 25/4/17 Licence: """ from .binary_tree import BinaryTree class AvlTree(BinaryTree): def balance_factor(self): return self.left.height() - s...
from typing import * class GeoSeries: @overload def __getitem__(self, /, key: int): """ usage.geopandas: 1 """ ... @overload def __getitem__(self, /, key: Literal["A"]): """ usage.geopandas: 1 """ ... @overload def __getitem__(s...
"""Utilites: minify response decorator.""" from htmlmin import minify from functools import wraps from flask import current_app def minify_response(f): """Minify the current output.""" @wraps(f) def wrapped(*args, **kwargs): if current_app.debug: return f(*args, **kwargs) else:...
"""Functions for converting to and from xarray objects """ from __future__ import absolute_import, division, print_function from collections import Counter, OrderedDict import numpy as np import pandas as pd from .coding.times import CFDatetimeCoder, CFTimedeltaCoder from .conventions import decode_cf from .core imp...
import morepath from morepath.error import LinkError, ConflictError from webtest import TestApp as Client import pytest def test_model_mount_conflict(): class app(morepath.App): pass class app2(morepath.App): pass class A(object): pass @app.path(model=A, path='a') def ge...
#! /usr/bin/env python # -*- coding: utf-8 -*- # # GUI module generated by PAGE version 4.14 # In conjunction with Tcl version 8.6 # Aug 13, 2018 03:57:27 PM import urllib.parse import urllib.request from urllib.error import HTTPError, URLError import shutil import sys import locale import codecs import os import os.p...
""" create app """ from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from tortoise.contrib.fastapi import register_tortoise from .v1 import v1 from core import settings app = FastAPI(title=settings.TITLE, description=settings.DESC) app.include_router(v1, prefix="/api") # 可以不要 # @app....
__author__ = "Altertech Group, https://www.altertech.com/" __copyright__ = "Copyright (C) 2012-2018 Altertech Group" __license__ = "Apache License 2.0" __version__ = "1.2.2" __description__ = "Denkovi ModBus relay DAE-RO16" __api__ = 5 __equipment__ = 'DAE-RO16-MODBUS' __required__ = ['aao_get', 'port_set', 'status', ...
from marshmallow import Schema, INCLUDE import json import os class BaseSchema(Schema): class Meta: ordered = True unknown = INCLUDE def toJson(self, obj): return self.dumps(obj) def loadFromJsonFile(self, jsonFilePath: str): if not os.path.isfile(jsonFilePath): ...
import json from glob import glob from tqdm import tqdm import re from nltk import word_tokenize as lib_tokenizer dict_map = dict({}) def word_tokenize(text): global dict_map words = text.split() words_norm = [] for w in words: if dict_map.get(w, None) is None: dict_map[w] = ' '.j...
from utils import * print(round_to(420, 60)) print(round_to(20, 60)) print(round_to(50, 60)) print(round_to(110, 60)) print(round_to(170, 60))
import time, copy, pickle import os, os.path import sys import numpy, pylab, itertools wd=os.getcwd() PyCodePath=os.path.split(os.path.split(os.path.realpath(__file__))[0])[0] sys.path.append(PyCodePath) sys.path.append(os.path.join(PyCodePath,'PythonCompositionPlots')) from readplatemap import * from myquaternaryuti...
from flask import Flask, request from http_client import place_order from exceptions import CircuitBreakerOpen app = Flask(__name__) @app.route('/buy_course', methods=['POST']) def buy_course(): post_data = request.get_json() # TODO: Validate input data try: # place the order in the external s...
from .baisc import _build_dense, _build_dropout, _build_flatten from .conv import _build_conv1d, _build_conv2d, _build_conv3d from .pooling import _build_maxpooling1d, _build_maxpooling2d, _build_maxpooling3d, _build_averagepooling3d DENSE = "Dense".lower() DROPOUT = "Dropout".lower() FLATTEN = "Flatten".lower() ...
# -*- coding: utf-8 -*- """Client module.""" from __future__ import unicode_literals try: input = raw_input except NameError: pass import socket def get_msg(): """Ask user for message to send.""" msg = input(u"What would you like to send? \n") return str(msg) def client(message): """Send data ...
import os import glob import json import collections import pandas as pd import numpy as np import prettytable import pickle from prettytable import PrettyTable from stethoscope.analytical_engine import AnalysisFramework from autoscalingsim.simulator import Simulator from autoscalingsim.infrastructure_platform.platfor...
import pytest import aiosqlite import tempfile import random import asyncio from pathlib import Path from typing import List, Tuple from tests.setup_nodes import test_constants from chia.types.blockchain_format.sized_bytes import bytes32 from chia.util.ints import uint32, uint64 from chia.cmds.db_upgrade_func import ...
""" CNC programs only support linear moves and arc moves svgpathtools supports Arc, Line CubicBezier For offsetting path: Arc -> offset_curve CubicBezier -> offset_curve Line -> Shapely """ import sys import enum import json import pathlib import math import traceback import pprint from PyQt5 import QtWidgets, QtCor...
from ..plugin import Plugin from ..loader import Loader from ..control import Control from ..exception import FrictionlessException from .. import errors # Plugin class StreamPlugin(Plugin): """Plugin for Local Data API | Usage -------- | -------- Public | `from frictionless.plugins.stream i...
import mongoengine as me from flask import Flask, render_template, request, redirect, url_for from flask_wtf import FlaskForm from wtforms import StringField, PasswordField from wtforms.validators import Length, InputRequired from werkzeug.security import generate_password_hash, check_password_hash from flask_login im...
# People may be running this on different platforms, so no #!/usr/local/bin/python... import sys from xml.dom import minidom # Read all lines from root Maven pom.xml. xmldoc = minidom.parse(sys.path[0] + '/../../../../pom.xml') deps = xmldoc.getElementsByTagName('dependency') print 'Group ID\tArtifact ID\tVersion\tCL...
import unittest from unittest.mock import MagicMock from unittest.mock import call from samsung_multiroom.service import Item from samsung_multiroom.service.tunein import TuneInBrowser def browser_main_return_value(): return [ { '@type': '0', 'title': 'Favorites', 'con...
import _plotly_utils.basevalidators class AccesstokenValidator(_plotly_utils.basevalidators.StringValidator): def __init__( self, plotly_name="accesstoken", parent_name="layout.mapbox", **kwargs ): super(AccesstokenValidator, self).__init__( plotly_name=plotly_name, par...
from __future__ import division import operator from functools import reduce from naiveBayesClassifier.ExceptionNotSeen import NotSeen class Classifier(object): """docstring for Classifier""" def __init__(self, trainedData, tokenizer): super(Classifier, self).__init__() self.data = trainedDat...
import pytest from aiohttp.test_utils import make_mocked_coro import virtool.analyses.db import virtool.analyses.format @pytest.mark.parametrize("algorithm", [None, "foobar", "nuvs", "pathoscope"]) async def test_format_analysis(algorithm, mocker): """ Test that the correct formatting function is called base...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import os import unittest # import the RestClient class from epages_client.client import RestClient # Import the contact info class from epages_client.dataobjects.contact_info import ContactInfo # Import the content page class from epages_client.dataob...
#!/usr/bin/env python from __future__ import print_function from twisted.internet.protocol import Protocol, Factory from twisted.internet import defer, task from twisted.spread import pb import attr import sys from myutils import raise_all_exceptions_on_client LOAD_AVERAGE_WINDOW = 30 # seco...
# from datetime import datetime # print timestamps to see how long sections of code # take to run # def print_time (task_name): # print(task_name) # print (datetime.now()) # print() # first_name = 'Nathaniel' # print_time ('printed first name') # for x in range(0,10): # print(x) # print_time('compl...
import datetime import hashlib class Block(object): blockNo = 0 data = None next = None hash = None nonce = 0 previousHash = 0x0 timestamp = datetime.datetime.now def __init__(self,data): self.data = data self.timestamp = datetime.datetime.now() def hash(self): ...
import operator import itertools from flask import jsonify, abort, Blueprint, request from website.database.DB import SessionFactory, SessionContextManager from website.database.models import UsersPerson, RandomPair, DrawCount from website.generate_pairs.generate_random_pairs import generate_random_pairs, Person from w...
import string import uuid from typing import Literal from auto_labeling_pipeline.models import RequestModelFactory from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.db import models from polymorphic.models import PolymorphicModel from .managers import (Annotati...
def numKeys(): return 1 class PublicKeyManager: def __init__(self): self._valid = True def valid(self): return self._valid
# -*- coding: future_fstrings -*- # # This file is part of bdsSnmpAdaptor software. # # Copyright (C) 2017-2019, RtBrick Inc # License: BSD License 2.0 # import time from pysnmp.entity.rfc3413 import cmdrsp from bdssnmpadaptor import error from bdssnmpadaptor import snmp_config from bdssnmpadaptor.config import loadC...
from django.contrib import admin from .models import Consume, Food # Register your models here. admin.site.register(Consume) admin.site.register(Food)
import pygame from pygame.locals import * import torch import torchvision import numpy as np import matplotlib.pyplot as plt from random import random DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu' pygame.init() WIN_SIZE = 1000 win = pygame.display.set_mode((WIN_SIZE,WIN_SIZE)) pygame.display.se...
__version__ = '0.4.6'
"""Lineage database and associated utilities. Extracted from sourmash LCA Databases. TODO: * implement load, save CTB: * add strict taxonomy enforcement within? ldb-specific taxlist? """ from __future__ import print_function, division import json import gzip from collections import OrderedDict, defaultdict import f...
# Definition for a Node. class Node(object): def __init__(self, val, children): self.val = val self.children = children class Solution(object): def maxDepth(self, root): """ :type root: Node :rtype: int """ return 0 if root is None else (1 if len(root.ch...