content
stringlengths
5
1.05M
""" instabot example Workflow: Follow user's followers by username. """ import argparse import os import sys import random import time sys.path.append(os.path.join(sys.path[0], "../")) from instabot import Bot # noqa: E402 parser = argparse.ArgumentParser(add_help=True) parser.add_argument("-u", ty...
from cipherkit.alphabets import ascii_basic from cipherkit.alphabets import decimal from cipherkit.alphabets import english from cipherkit.alphabets import spanish def test_alphabet_spanish(): expected_alphabet = "ABCDEFGHIJKLMNÑOPQRSTUVWXYZ" assert spanish() == expected_alphabet def test_alphabet_english()...
import shutil import json import bs4 import requests from .constants import BASE_DIR, CONFIG def download_response_sheet_json(url_to_response_sheet): """ Incase the response_sheet file is not present or user has explicitly requested it. """ with open('./temp/response_sheet.html', 'wb') as response_sheet_fi...
def csv_parser(delimiter=','): field = [] while True: char = (yield(''.join(field))) field = [] leading_whitespace = [] while char and char == ' ': leading_whitespace.append(char) char = (yield) if char == '"' or char == "'": suround ...
import django_filters from django.db import transaction from django.db.models import Q from django.http import Http404 from django.utils.translation import ugettext_lazy as _ from rest_framework import exceptions, serializers, status, viewsets from rest_framework.response import Response from metarecord.models import ...
import logging import multiprocessing from multiprocessing.managers import ( BaseManager, ) import tempfile import pytest from hvm.chains.ropsten import ROPSTEN_GENESIS_HEADER, ROPSTEN_NETWORK_ID from hvm.db.atomic import ( AtomicDB, ) from hvm.db.chain import ( ChainDB, ) from helios.chains import ( ...
import setuptools with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() setuptools.setup( name="behavior_mapper", version="1.2.1.dev1", author="Jason Summer", author_email="jasummer92@gmail.com", description="Clusters channel activities or steps according to the tra...
import pyodbc connstr = pyodbc.connect('DRIVER={SQL Server};SERVER=CATL0DB728\INTCCIPROD;DATABASE=itt;Trusted_Connection=yes;') cursor = connstr.cursor() cursor.execute("SELECT u_server_name FROM LCM_SNOW") #for row in cursor: # print(row) columns = [column[0] for column in cursor.description]
print("Test".ljust(20,".")+"20$") print("Pear".ljust(20,".")+"99$") print("Apple".ljust(20,".")+"120$")
#-------------------------------------------------------------------------------- ## Protein Pow(d)er #-------------------------------------------------------------------------------- ## This program looks for an optimal folding configuration for a protein. #-------------------------------------------------------------...
# This script combines all csv files in the current folder # It assumes all csv files in this folder have the same header/formats import os import pandas as pd combined_csv_file = "combined_csv.csv" df = None for root, dirs_list, files_list in os.walk('.'): for file_name in files_list: extension = os.p...
#// #//----------------------------------------------------------------------------- #// Copyright 2007-2011 Mentor Graphics Corporation #// Copyright 2007-2010 Cadence Design Systems, Inc. #// Copyright 2010 Synopsys, Inc. #// Copyright 2019 Tuomas Poikela #// All Rights Reserved Worldwide #// #// Licensed...
import os from PIL import Image, ImageOps import click import shutil from typing import Optional IMAGES_EXTS = ["jpg", "png"] @click.command(name="reduce-image-size") @click.argument("path-to-images") @click.argument("new_width", default=1920) @click.option("--quality", default=95) @click.option("--grayscale", is_fl...
from fib_route import FibRoute def test_constructor(): _route = FibRoute("1.0.0.0/8", ["nh1", "nh2"]) def test_property_prefix(): route = FibRoute("1.0.0.0/8", ["nh1", "nh2"]) assert route.prefix == "1.0.0.0/8" def test_str(): route = FibRoute("1.0.0.0/8", ["nh2", "nh1"]) assert str(route) == "1....
from sympy import ( Rational, Symbol, N, I, Abs, sqrt, exp, Float, sin, cos, symbols) from sympy.matrices import eye, Matrix, dotprodsimp from sympy.core.singleton import S from sympy.testing.pytest import raises, XFAIL from sympy.matrices.matrices import NonSquareMatrixError, MatrixError from sympy.simplify.si...
import diy w = diy.mpi.MPIComm() m = diy.Master(w) diy.add_my_block(m, 0) diy.add_my_block(m, 5) print(m)
# title # defines the title of the whole set of queries # OPTIONAL, if not set, timestamp will be used title = "General overview queries" # description # defines the textual and human-intended description of the purpose of these queries # OPTIONAL, if not set, nothing will be used or displayed description = "Queri...
class Solution: def find_min(self, nums: list[int]) -> int: lo, hi = 0, len(nums) while lo < hi: mid: int = (lo+hi) // 2 if nums[mid] >= nums[0]: lo = mid+1 else: hi = mid return lo def bi_search(self, nums: list[int], target: int, lo: int, hi: int) -...
""" Generate a random permutation of a finite sequence Shuffle an array """ import random def shuffle_std(arr): """Shuffle an array using the standard library in-place""" random.shuffle(arr) def shuffle_fy(arr): """ Fisher-Yates shuffle generates a random permutation of a finite sequence in-...
from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.utils.translation import ugettext_lazy as _ from django.core.validators import RegexValidator # Create your models here. class PersonalInfo(AbstractBaseUser): alphanumeric = RegexValidator(r'^[0-9a-zA-Z]*$', message='...
#!/usr/bin/env python import os, sys, string, re, csv, xmlrpc.client, pickle, signal import pandas as pd import patients import concept_finder # path to temporary progress tracking file progress_path = 'data/mimic/extract_concepts_progress' # path to MIMIC-III's NOTEEVENTS.csv noteevents_path = 'mimic-iii-clinical-...
import time import threading def calcSquare(numbers): print("Calculating square numbers") for n in numbers: time.sleep(0.2) print("square:", n*n) def calcCube(numbers): print("Calculating cube numbers") for n in numbers: time.sleep(0.2) print("cube:", n*n*n) array = [2,3,8,9] start = time.time() threa...
######################################################### ### There is no EBS Snapshot provider in CloudFormation # ### like in Terraform. Leaving this placeholder # #########################################################
from pathlib import Path import pytest @pytest.fixture(scope="session") def data_dir() -> Path: """Data directory fixture""" return Path(__file__).parent / "data" @pytest.fixture(scope="session") def genome_fasta_dir(data_dir: Path) -> Path: """Genome fasta direcotry""" return data_dir / "genome_fa...
"""shared raw nodes that shared transformer act on""" import pathlib from dataclasses import dataclass from typing import Union from marshmallow import missing from . import base_nodes @dataclass class RawNode(base_nodes.NodeBase): pass @dataclass class ResourceDescription(RawNode, base_nodes.ResourceDescript...
from mwapi import * print(messages) print(services)
""" light cone generator test """ #----------------------------------------------------------------------------- # Copyright (c) 2017, yt Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #-----------------...
from engine import Decoration from engine import Wall from engine import Map2d from engine import Player def test_create_with_pattern(): pattern = "0B010F110A\n3CFF3E 3C" map2d = Map2d.create_with_pattern(pattern) grid = map2d.grid assert isinstance(grid.get_block(0, 0), Wall) assert grid.get_bloc...
# -*- coding: utf-8 -*- from __future__ import print_function import re import sys import subprocess if sys.version_info >= (3, 0): import pathlib as pathlib else: import pathlib2 as pathlib import click_spinner import yaml from aiida_project import constants def clone_git_repo_to_disk(github_url, locatio...
#!/usr/bin/env python # coding: utf-8 # # Overview # # This is the __expert level__ version of [question 3](../novice/Q3.ipynb) from the novice level and [question 3](../intermediate/Q3.ipynb) from the intermediate level. Previously we focused on the frequency of the different types of lesion diagnosis and finding if...
''' Disclaimer: this code is highly based on trpo_mpi at @openai/baselines and @openai/imitation ''' import argparse import os.path as osp import logging import numpy as np import gym import os from mpi4py import MPI from tqdm import tqdm from baselines.gail import mlp_policy from baselines.common import set_global_se...
import numpy as np import random from cost_functions import * from constants import * import heapq # TODO - tweak weights to existing cost functions WEIGHTED_COST_FUNCTIONS = [ (time_diff_cost, 1), # requested duration cost (s_diff_cost, 8), # s coordinate differ from the goal cost (...
"""Components that apply forcing. See jax_cfd.base.forcings for forcing API.""" from typing import Callable import gin from jax_cfd.base import equations from jax_cfd.base import forcings from jax_cfd.base import grids from jax_cfd.spectral import forcings as spectral_forcings ForcingFn = forcings.ForcingFn ForcingM...
"""FastAPI main module for the Clearboard application. origins : string[], url to whitelist and on which the fastapi server should listen (basicly the core address) """ import base64 import os import shutil from functools import lru_cache from typing import List, Optional from fastapi import FastAPI, File, Response, U...
# Finite Decks, Aces = reactive # Reinforcement learning agent which plays against a delaer import numpy as np import matplotlib.pyplot as plt from rl_tools import ( simulation, scorecalc, countcalc, initializedrawpile, actionupdate, acecheck, newcard, twist, ) # stage 1 of learning -...
import logging from df_engine.core.keywords import GLOBAL, LOCAL, RESPONSE, TRANSITIONS, PROCESSING from df_engine.core import Context, Actor import df_engine.labels as lbl import df_engine.conditions as cnd from examples import example_1_basics logger = logging.getLogger(__name__) def create_transitions(): r...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models from django.conf import settings import pgweb.core.models class Migration(migrations.Migration): dependencies = [ ('auth', '0006_require_contenttypes_0002'), migrations.swappable_dependency(...
#!/sw/bin/python3.3 __author__ = 'Michael+Dan' 'Last Modified from Michael doron - 25.11.2014' ''' TODO: Use OS.path,join insteado f + strings. (cross OS compatability + saves headaches. Also - make it clearer about how to just predict for example.. and valid/invalid options 'TODO: Add "Get top features" to command l...
import enum import time from pymodbus.constants import Endian from pymodbus.payload import BinaryPayloadBuilder from pymodbus.payload import BinaryPayloadDecoder from pymodbus.client.sync import ModbusTcpClient from pymodbus.client.sync import ModbusSerialClient from pymodbus.register_read_message import ReadInputRegi...
from django.shortcuts import render from tsuru_autoscale.instance import client from tsuru_autoscale.event import client as eclient def list(request, app_name=None): token = request.session.get('tsuru_token').split(" ")[-1] instances = client.list(token).json() context = { "list": instances, ...
from pathlib import Path from numpy.testing import assert_allclose, assert_equal import pandas as pd import pytest from statsmodels.tsa.seasonal import MSTL @pytest.fixture(scope="function") def mstl_results(): cur_dir = Path(__file__).parent.resolve() file_path = cur_dir / "results/mstl_test_results.csv" ...
""" Support for Mailgun. For more details about this component, please refer to the documentation at https://home-assistant.io/components/mailgun/ """ import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.const import CONF_API_KEY, CONF_DOMAIN, CONF_WEBHOOK_ID from homeassi...
import sys, getopt import re import pandas as pd import os from pathlib import Path import urllib.request from urllib.request import Request, urlopen def SRARunTable(): inputFile = read_argv(sys.argv[1:]) print (inputFile) print ('Opening file & creating categories in Downloads/categories') df = pd.rea...
""" 2018 Day 21 https://adventofcode.com/2018/day/21 """ from typing import Iterator, Optional # #ip 1 # seti 123 0 5 # bani 5 456 5 # eqri 5 72 5 # addr 5 1 1 # seti 0 0 1 # seti 0 9 5 # bori 5 65536 2 # seti 7571367 9 5 # bani 2 255 4 # addr 5 4 5 # bani 5 16777215 5 # muli 5 65899 5 # bani 5 16777215 5 # gtir 256 ...
import tensorflow as tf import tf_metrics from tensorflow import keras class CategoricalTruePositives(keras.metrics.Metric): def __init__(self, name='categorical_true_positives', **kwargs): super(CategoricalTruePositives, self).__init__(name=name, **kwargs) self.true_positives = self.add_weight(name='...
from django.apps import AppConfig class GwdapisConfig(AppConfig): name = 'GWDapis'
# -*- coding: utf-8 -*- """ Methods for platform information. @author: - Thomas McTavish """ import platform def get_platform_info(): """ Retrieve platform information as a dict. Code borrowed from the file, ``launch.py`` from the Sumatra package. """ network_name = platform.node() bits, ...
from astboom.cli import cli import sys if __name__ == "__main__": sys.exit(cli(prog_name="astboom"))
from datetime import timedelta from django.test import TestCase from django.utils import timezone from graphene.test import Client from graphql_relay import to_global_id from itdagene.app.career.models import Joblisting from itdagene.app.company.models import Company from itdagene.core.models import User from itdagene...
from ozekilibsrest import Configuration, Message, MessageApi configuration = Configuration( username="http_user", password="qwe123", api_url="http://127.0.0.1:9509/api" ) msg1 = Message( to_address="+3620111111", text="Hello world 1!" ) msg2 = Message( to_address="+36202222222", text="Hel...
from PyInstaller.utils.hooks import collect_data_files import spacy # add datas for spacy datas = collect_data_files('spacy', False) # append spacy data path datas.append((spacy.util.get_data_path(), 'spacy/data')) datas.extend(collect_data_files('thinc.neural', False)) hiddenimports=['cymem', 'cymem.cymem', 'thinc....
# Copyright 2021 The TensorFlow Authors. 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 applica...
import requests import json import os def Wechat(msg, corpid, secret, agentid): data = json.dumps({ "touser" : "admin", "msgtype" : "text", "agentid" : agentid, "text" : { "content" : msg }, "safe":0, "enable_...
def get_keywords(js): info = get_info(js) film_name = info[0] film_id = info[1] keyword_list = [] try: keywords = js['keywords'][0]['keywords'] if keywords != None: for k in keywords: keyword = k['keyword'] keyword_id = k...
# -*- coding: utf-8 -*- """Console script for light_tester.""" import sys import click from .ledSolve import parseFile click.disable_unicode_literals_warning = True @click.command() @click.option("--input", default=None, help="input URI (file or URL)") def main(input=None): print("input", input) input = sys...
from functools import reduce import warnings import tensorflow as tf from . import kernels from ._settings import settings from .quadrature import mvhermgauss from numpy import pi as nppi int_type = settings.dtypes.int_type float_type = settings.dtypes.float_type class RBF(kernels.RBF): def eKdiag(self, X, Xcov...
def ejercicio11(): numero1 = int(input("Escriba un numero: ")) numero2 = int(input("Escriba otro numero: ")) op1 = numero1 op2 = numero2 if numero1 == numero2: print("El mcd es ", numero1) elif numero1 > numero2: while numero1 > op2: op2 = op2 + numero2 resto = op2 - numero...
from .fbgemm import get_fbgemm_backend_config_dict def validate_backend_config_dict(backend_config_dict): return "quant_patterns" in backend_config_dict
# Copyright 2020, Schuberg Philis B.V # # 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 ...
################################################################################ # # Copyright 2021-2022 Rocco Matano # # 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, in...
n, m = map(int, input().split()) a = list(map(int, input().split())) b = list(map(int, input().split())) a.sort(reverse=True) b.sort(reverse=True) ans = -1 if a[0] == n*m and b[0] == n*m:
# coding: utf-8 import numpy as np import networkx as nx import random import multiprocessing import torch import torch.nn as nn import torch_geometric as tg import torch.nn.functional as F from torch.nn import init # Position-aware Graph Neural Networks. For more information, please refer to https://arxiv....
###!/user/bin/env python """ Top line for Unix systems. Comment out for Windows """ import os # needed for file access. import sys # needed for sys functions. lootTag = 'You have looted ' sellTag = 'll give you ' lootDB = {} # blank dictionary. def logParse(fname): 'Parse a formatted log file' ...
import pygame from Color import Color from itertools import repeat class Level: def __init__(self,filename): self.block_size = (self.w,self.h) = (100,100) self.level = [] self.screen_player_offset = (100,300) self.player_position = (0,0) self.enemies = [] self.floor = [] self.screen_shake = False f = ...
"""Simulate the generative process of LDA and generate corpus based on it """ import numpy as np from scipy.sparse import coo_matrix from scipy.stats import poisson from sklearn.utils import check_random_state from six.moves import xrange class LdaSampleGenerator(object): """Generate LDA samples Parameters...
from picostack.process_spawn import invoke from picostack.textwrap_util import wrap_multiline class VmBuilder(object): def get_build_jeos_call(self): return wrap_multiline(''' sudo vmbuilder kvm ubuntu --suite quantal --flavour virtual --arch i386 -o --libvirt qemu:///system ...
# local_blast_zum.py # # Run on Python3 # Created by Alice on 2018-06-26. # import argparse from os import listdir, remove, makedirs from os.path import exists, isdir, isfile, join from statistics import mean from Bio.Blast.Applications import NcbiblastnCommandline import xml.etree.ElementTree as ET from Bio.Bla...
from collections import defaultdict from . import builtin from .. import options as opts from .path import buildpath, relname, within_directory from .file_types import FileList, make_file_list, static_file from ..backends.make import writer as make from ..backends.ninja import writer as ninja from ..build_inputs impor...
""" Binary Search Tree and Tree node """ from typing import Optional class Node: def __init__(self, data: int): self.data = data self.left: Optional[Node] = None self.right: Optional[Node] = None def __repr__(self): return f"{self.__class__} {self.data}" class BST: """BS...
from . import additional from . import attachments from .base import BaseModel from .community import Community from .events.community.events_list import Event as BotEvent from .message import Action from .message import Message from .user import User
import os from torchvision import datasets def download_cifar10(path, train=True, transform=None): """Download CIFAR10 dataset Args: path: Path where dataset will be downloaded. Defaults to None. If no path provided, data will be downloaded in a pre-defined directory. ...
import sys, os import commands import time import multiprocessing import random import numpy as np # Process class to run the Bayenv test phase in paralell class RunInProcess(multiprocessing.Process): def __init__(self, cmd, thread_id, testdata, testsize): multiprocessing.Process.__init__(self) ...
#!/usr/bin/env python3 ''' @file: text_gio.py @auth: Sprax Lines @date: 2020.11.22 DNA pattern matching functions and some text file utilities. Written with Python version >= 3.8.5 ''' import argparse import errno # import fnmatch import glob import ntpath import os import os.path import pickle import random # import r...
from django.conf import settings from django_statsd.clients import statsd from lib.geoip import GeoIP import mkt class RegionMiddleware(object): """Figure out the user's region and store it in a cookie.""" def __init__(self): self.geoip = GeoIP(settings) def region_from_request(self, request)...
from main import BotClient import os # run bot bot = BotClient() bot.run(os.getenv("TOKEN"))
from enum import Enum class ContentType(Enum): Film = 0 Series = 1 class Content: def __init__(self, name, content_type, date): self.name = name self.content_type = content_type self.date = date def __str__(self) -> str: return f"name='{self.name}'; type={self.conten...
import hazelcast from hazelcast.serialization.api import IdentifiedDataSerializable class Student(IdentifiedDataSerializable): FACTORY_ID = 1 CLASS_ID = 1 def __init__(self, id=None, name=None, gpa=None): self.id = id self.name = name self.gpa = gpa def read_data(self, objec...
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ Copyright (c) 2020-2022 INRAE 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, co...
def test_edit_group(app): app.session.login(username="admin", password="secret") app.group.edit_first_group(group_name="11111") app.session.logout()
from unittest import TestCase class TestWeightedDirGraph(TestCase): def test___init__(self): from pyavia import WtDirgraph, g_link wdg = WtDirgraph() # Test basic functions. wdg['a':'b'] = 'somevalue' self.assertIn('a', wdg) # Both keys created by link assignment. ...
from kids_math.utils import valid_answer from kids_math.gifs import PeterRabbitGif, FrozenGif # from kids_math.img import Images def greater_than_less_than(first_number, second_number): """Fill in. """ gifs = PeterRabbitGif() acceptable = ('=', '>', '<') if first_number == second_number: ...
{ 'targets': [ { 'target_name': 'riskjs', 'sources': [ 'src/RiskJS.cpp', 'src/CVaRHistorical.cpp', 'src/CVaRMonteCarlo.cpp', 'src/CVaRVarianceCovariance.cpp', 'src/compute_returns_eigen.cpp', 'src/instrument.cpp', 'src/path.cpp', 'src/pca...
# # Copyright 2020 Two Sigma Open Source, LLC # # 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 agree...
import yaml from tests.base.io_test import BaseIOTest from tests.base.value_error import BaseValueErrorTest from tests.base.folder_test import BaseFolderTest from tests.base.hash_test import BaseHashTest from queenbee.plugin import Plugin ASSET_FOLDER = 'tests/assets/plugins' class TestIO(BaseIOTest): klass = ...
import schedule import settings from .poll_pull_requests import poll_pull_requests as poll_pull_requests from .poll_read_issue_comments import poll_read_issue_comments from .poll_issue_close_stale import poll_issue_close_stale def schedule_jobs(api): schedule.every(settings.PULL_REQUEST_POLLING_INTERVAL_SECONDS)...
import os from os import walk import sys try: rename_file = sys.argv[1] photo_attack_folder = sys.argv[2] video_attack_folder = sys.argv[3] real_folder = sys.argv[4] except: rename_file = 'Test.txt' photo_attack_folder = 'self_created/photo_attack' video_attack_folder = 'self_created/video_...
from http.server import BaseHTTPRequestHandler, HTTPServer import re import socket from threading import Thread import unittest import os # Third-party imports... from unittest.mock import MagicMock, Mock from pywink.api import * from pywink.api import WinkApiInterface from pywink.devices.sensor import WinkSensor fro...
import math from io import BytesIO import qrcode from reportlab.pdfbase.pdfmetrics import getAscent from reportlab.pdfgen.canvas import Canvas from lib.qrcrc import calc_crc def gen_qr(data): qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, bo...
import uuid def get_uuid_unicode(): u = uuid.uuid4() try: return unicode(u) except NameError: return str(u) class NotAuthorizedException(Exception): pass
from dacite import from_dict from sqlalchemy.sql.functions import user from src.database.models.account import Account from src.database.models.transaction import Transaction from src.models.response.razorpayx import PayoutsPayload from src.models.response.razorpay import PaymentsPayload from src.database.models.transa...
# Copyright 1996-2019 Cyberbotics Ltd. # # 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 agre...
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
# -*- coding: utf-8 -*- # # Copyright 2021 Google LLC. 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 requir...
# win32traceutil like utility for Pythonwin import _thread import win32trace, win32event, win32api from pywin.framework import winout outputWindow = None def CollectorThread(stopEvent, file): win32trace.InitRead() handle = win32trace.GetHandle() # Run this thread at a lower priority to the main message-l...
import time from math import fabs import putil.timer from putil.testing import UtilTest class TestTimer(UtilTest): def setUp(self): self.op1_times = iter([ .01, .02 ]) self.a1 = putil.timer.Accumulator() self.op2_step1_times = iter([ .005, .015, .005, .005]) self.op2_step2_times ...
# coding=utf-8 # Copyright 2018 The Google Flax Team Authors and The HuggingFace Inc. team. # # 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 enum from datetime import datetime from ipaddress import IPv4Address, IPv6Address from typing import Callable, Iterator, Union from pydantic import BaseModel, Field __all__ = ( 'MandatoryFields', 'ExtensionFields', ) MAC_REGEX = r'^([A-F0-9]{2}:){5}[A-F0-9]{2}$' HOSTNAME_REGEX = r'^[A-Za-z0-9][A-Za-z...
from typing import Any class State: """Basic implementation of a state object""" _state = {} def set_prop(self, prop: str, value: Any) -> None: self._state[prop] = value def get_prop(self, prop: str) -> Any: return self._state.get(prop, None) state = State()
"""Init Control""" from .keycontroller import *
class FileResult: def __init__(self, filename, content): self.content = content self.filename = filename def __repr__(self): n_char = 20 content = self.content if len(self.content) < n_char else f'{self.content[:n_char]}...' return f'FileResult({self.filename!r}, {conten...