source
stringlengths
3
86
python
stringlengths
75
1.04M
graphics.py
# Copyright (c) 2018-present, Royal Bank of Canada. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # import numpy as np from PIL import Image import time import threading def save_image(x, path): im = Image.fromarra...
cloud_verifier_tornado.py
#!/usr/bin/python3 ''' SPDX-License-Identifier: Apache-2.0 Copyright 2017 Massachusetts Institute of Technology. ''' import signal import traceback import sys import functools import asyncio import os from multiprocessing import Process from sqlalchemy.exc import SQLAlchemyError from sqlalchemy.orm.exc import NoResul...
client.py
import time import socket import threading class Client: PORT = 5050 FORMAT = 'utf-8' SERVER = "192.168.1.216" ADDR = (SERVER, PORT) def __init__(self, name): self.msgs = [] self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.client.connect(self.ADDR) ...
open_file_dialog.py
import webview import threading """ This example demonstrates creating an open file dialog. """ def open_file_dialog(): file_types = ('Image Files (*.bmp;*.jpg;*.gif)', 'All files (*.*)') print(webview.create_file_dialog(webview.OPEN_DIALOG, allow_multiple=True, ...
client.py
# region Imports import socket, os, subprocess, threading, sys # endregion Imports # region Client Class class Client: # region Public # region Constructor # constructor with host IP and Port parameters def __init__(self, HOST, PORT): self.__HOST = HOST self.__PORT = PORT ...
single_thread.py
import logging import threading import time def thread_function(name): logging.info(f'Thread {name}: starting') time.sleep(2) logging.info(f'Thread {name}: finishing') if __name__ == "__main__": format = "%(asctime)s: %(message)s" logging.basicConfig(format=format, level=logging.INFO, datefmt='%H...
salient_region_concatenation.py
import os import cv2 import numpy as np import pandas as pd import multiprocessing from saliency_update import * def rotate_img(img, iteration = 1): #0: remain same, +n: rotate left in 90*n degree, -n: rotate right in 90*n degree (some part of img is sliced off) if len(img.shape) == 3: height, width, _...
streamer_throughput.py
from dotenv import load_dotenv import os, tweepy, time, multiprocessing # Load dotenv library load_dotenv() # User-defined Tweepy Stream listener class class Stream(tweepy.Stream): # Initialize Preprocessor Object def __init__(self, auth, total_timer=3600, interval=300, daemon=False): super(Stream, s...
server.py
#!/usr/bin/env python import threading import io import os import sys import json import logging import logging.handlers try: import argparse except ImportError: sys.exit("ImportError: You do not have the Python 'argparse' module installed. Please install the 'argparse' module and try again.") from time impor...
common_utils.py
r"""Importing this file must **not** initialize CUDA context. test_distributed relies on this assumption to properly run. This means that when this is imported no CUDA calls shall be made, including torch.cuda.device_count(), etc. torch.testing._internal.common_cuda.py can freely initialize CUDA context when imported....
test_callbacks.py
import os import multiprocessing import numpy as np import pytest from numpy.testing import assert_allclose from csv import reader from csv import Sniffer import shutil from keras import optimizers from keras import initializers from keras import callbacks from keras.models import Sequential, Model from keras.layers i...
lan_sc2_env.py
# Copyright 2017 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 ...
amqpbridge.py
import os import psycopg2 import pika from pika.exceptions import StreamLostError, AMQPConnectionError import time import select import logging from datetime import timedelta from multiprocessing import Process def get_logger(name): log_lvl = os.environ.get("LOG_LVL", "debug") if log_lvl == 'info': log...
main_window.py
import re import os import sys import time import datetime import traceback from decimal import Decimal import threading import asyncio from typing import TYPE_CHECKING, Optional, Union, Callable, Sequence from electrum_dash.dash_ps_util import (PSPossibleDoubleSpendError, PSSpe...
common.py
# Parallel Python Software: http://www.parallelpython.com # Copyright (c) 2005-2012 Vitalii Vanovschi. # Copyright (c) 2015-2016 California Institute of Technology. # Copyright (c) 2016-2020 The Uncertainty Quantification Foundation. # All rights reserved. # Redistribution and use in source and binary forms, with or wi...
chromectrl.py
import urllib, urllib2, json, threading, itertools try: import websocket except ImportError: websocket = None class ChromeDebuggerControl(object): ''' Control Chrome using the debugging socket. Chrome must be launched using the --remote-debugging-port=<port> option for this to work! ''' def __ini...
car-without-arduino.py
import socket import io import picamera import struct import time import threading from gpiozero import Motor class Car(object): def __init__(self, ip, port): self.client = socket.socket() self.client.connect((ip, port)) self.connection = self.client.makefile('wb') self.msg = None ...
main.py
# -*- coding: utf-8 -*- import logging import inspect import imp import os import operator import re import sys import time import traceback from clint.textui import colored, puts, indent from os.path import abspath, dirname from multiprocessing import Process, Queue import bottle from listener import WillXMPPClient...
resolver.py
import struct import socket import datetime import struct from threading import Lock, Thread from server import BaseServer, BUFFER_SIZE from cache import Cache, get_qname, set_padding from random import randint TYPES = { 1: 'A', 2: 'NS', 3: 'MD', 4: 'MF', 5: 'CNAME', 6: 'SOA', 7: 'MB', 8: 'MG', 9: 'MR', 10...
camgear.py
""" =============================================== vidgear library source-code is deployed under the Apache 2.0 License: Copyright (c) 2019 Abhishek Thakur(@abhiTronix) <abhi.una12@gmail.com> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with th...
interface.py
import json import logging import Queue from . import codes, commands, events from .util import WorkerThread log = logging.getLogger(__name__) class Interface(object): def __init__(self, conn): self._conn = conn conn.event_callback = self.__on_event self._event_queue = Queue....
rplidar-save2.py
'''Simple and lightweight module for working with RPLidar rangefinder scanners. Usage example: >>> from rplidar import RPLidar >>> lidar = RPLidar('/dev/ttyUSB0') >>> >>> info = lidar.get_info() >>> print(info) >>> >>> health = lidar.get_health() >>> print(health) >>> >>> for i, scan in enumerate(lidar.iter_scans()):...
scraper.py
# -*- coding: utf-8 -*- from bs4 import BeautifulSoup from pymongo import MongoClient from datetime import datetime from threading import Thread from constants import * import re import requests import time def convert_job_type(job_type): return job_type_dict.get(job_type, 'other') def convert_fresh_or_switch(fr...
knapsack_big.py
import sys import threading def main(): with open("knapsack_big.txt", mode='r') as f: lines = f.readlines() w, n = map(int, lines[0].split()) print(f'Knapsack size: {w}') print(f'number of items: {n}') items = [tuple(map(int, line.split())) for line in lines[1:]] A = dict() def ...
marathon_lb.py
#!/usr/bin/env python3 """# marathon-lb ### Overview The marathon-lb is a service discovery and load balancing tool for Marathon based on HAProxy. It reads the Marathon task information and dynamically generates HAProxy configuration details. To gather the task information, marathon-lb needs to know where to find Mar...
opencv_t_est.py
# -*- coding: utf-8 -*- import sys import cv2 import numpy as np import threading from time import sleep import os from PyQt5.QtCore import QUrl, QObject from PyQt5.QtGui import QGuiApplication from PyQt5.QtQuick import QQuickItem from PyQt5.QtQml import qmlRegisterType, QQmlComponent, QQmlApplicationEngine, QQmlEngin...
echo_server.py
"""TCP server. Multithreaded TCP echo server. """ import socketserver import logging import click import signal from functools import partial import threading class EchoConnectionHandler(socketserver.StreamRequestHandler): """Handler to the TCP connections. Methods setup(), finish() and handle() are callba...
cluster_status_test.py
# Copyright (c) 2018 PaddlePaddle 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 app...
test_subprocess.py
import unittest from unittest import mock from test import support import subprocess import sys import signal import io import itertools import os import errno import tempfile import time import traceback import selectors import sysconfig import select import shutil import threading import gc import textwrap import jso...
nvme_object.py
#!/usr/bin/python3 """ (C) Copyright 2020-2021 Intel Corporation. SPDX-License-Identifier: BSD-2-Clause-Patent """ import threading import avocado import time from pydaos.raw import DaosApiError from apricot import TestWithServers def container_write(container, record, array_size=None): """Write to a contai...
articlecrawler.py
#!/usr/bin/env python # -*- coding: utf-8, euc-kr -*- from time import sleep from bs4 import BeautifulSoup from multiprocessing import Process from korea_news_crawler.exceptions import * from korea_news_crawler.articleparser import ArticleParser from korea_news_crawler.writer import Writer import os import platform im...
node.py
import threading from time import sleep from logzero import logger from twisted.internet import reactor, task from neo.Network.NodeLeader import NodeLeader from neo.Core.Blockchain import Blockchain from neo.Implementations.Blockchains.LevelDB.LevelDBBlockchain import LevelDBBlockchain from neo.Settings import settin...
loop.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # filename: loop.py # modified: 2019-09-11 __all__ = ["main"] import time import random from queue import Queue, Empty from collections import deque from threading import Thread, current_thread from requests.compat import json from requests.exceptions import RequestExcep...
auto_distiller_exp.py
import os import json import glob import torch import logging import random import numpy as np from Distiller.configs import parse from Distiller.autoaug import AutoAugmenter from Distiller.utils import Logger, cal_layer_mapping, uploadDirectory, glue_criterion from Distiller.mp_aug import aug_process, generate_aug_dat...
client.py
import socket import os import threading import shutil import pygame import random class game: x = pygame.init() def __init__(self): self.gameWindow = pygame.display.set_mode((400, 500)) pygame.display.set_caption("RollDice - By Ritesh Kr. Gupta") self.one = pygame.image.load("dice_i...
threads_join.py
""" Enumerate. Various examples exhibiting Thread use. """ from threading import Thread from threading import current_thread import logging import os import time # Environment ENV = os.environ.get("ENV") or "development" LOG_LEVEL = os.environ.get("LOG_LEVEL") or "info" # Configuration DELAY = os.environ.get("DELAY"...
pyminer.py
#!/usr/bin/python # # Copyright (c) 2011 The Bitcoin developers # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # import time import json import pprint import hashlib import struct import re import base64 import httplib import...
Hiwin_RT605_ArmCommand_Socket_20190627173037.py
#!/usr/bin/env python3 # license removed for brevity import rospy import os import numpy as np from std_msgs.msg import String from ROS_Socket.srv import * from ROS_Socket.msg import * from std_msgs.msg import Int32MultiArray import math import enum pos_feedback_times = 0 mode_feedback_times = 0 msg_feedback = 1 #接收策略端...
tester.py
import asyncio import time from threading import Thread class Test: def __init__(self, func, ignored_exception, *args): self.func = func self.value = args self.ignored_exception = ignored_exception self.completed = None self.time = 0 self.result = None self....
decorators.py
import atexit import Queue import re import time import threading from django.conf import settings from django.core.cache import cache from django.http import HttpResponseForbidden, HttpResponseRedirect, Http404 from django.utils.functional import wraps from djutils.cache import key_from_args class EmptyObject(obje...
taskqueue_stub.py
#!/usr/bin/env python # # Copyright 2007 Google 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 o...
vespa-exporter.py
#!/usr/bin/env python import json import time import os from prometheus_client import start_http_server, Gauge import requests import logging import re from threading import Lock, Thread http_port = 9426 config_server = os.getenv('VESPA_CONFIGSERVER', 'localhost:19071') configurl = 'http://' + config_server + '/conf...
wrappers.py
# Copyright 2017 The TensorFlow Agents Authors. # # 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...
servidor.py
import socket import struct import cv2 import numpy as np import time import threading import os import argparse import sys from pynput import keyboard import select from queue import Queue # Obtener argumentos parser = argparse.ArgumentParser() parser.add_argument('--ip', type=str, help='La IP donde el servidor escuc...
flex_index_phase1.py
from .tuq import QueryTests from pytests.fts.random_query_generator.rand_query_gen import DATASET from collections import Mapping, Sequence, Set, deque from deepdiff import DeepDiff import json import threading from pytests.fts.fts_base import CouchbaseCluster from membase.api.exception import CBQError class FlexIndex...
main.py
import asyncio import functools import logging import os import signal import sys from concurrent.futures import ThreadPoolExecutor from functools import partial from multiprocessing import Process from pathlib import Path from time import time from typing import Any, Awaitable, Callable, Dict, Optional, Set, Tuple, Ty...
export_d3po.py
import os import json from glue.core import Subset DISPATCH = {} def save_page(page, page_number, label, subset): """ Convert a tab of a glue session into a D3PO page :param page: Tuple of data viewers to save :param label: Tab label """ result = {} # layout settings result['grid'] = ...
widget.py
from ._version import js_version_info import importlib.util from urllib.parse import quote_plus import json # Widget dependencies import ipywidgets as widgets from traitlets import Unicode, Dict, Int, Bool import time # Server dependencies import asyncio from hypercorn.config import Config from hypercorn.asyncio impo...
server.py
# -*- coding: utf-8 -*- ''' Server worker process ''' from __future__ import absolute_import # Import pythond stdlib import os import re import time import base64 import signal import logging import threading # Import third party libs import zmq import umsgpack from prometheus_client import Counter # Import napalm-l...
messenger.py
# Copyright 2012 Douglas Linder # 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...
test_runtime_captures_signals.py
import multiprocessing import os import signal import time import pytest from cli.api import gateway, executor_native from jina import Executor, DocumentArray, Document, requests from jina.clients.request import request_generator from jina.parsers import set_gateway_parser, set_pea_parser from jina.peapods.networking...
tkasyncframe.py
#!python3 # -*- coding: utf-8 -*- # author: yinkaisheng@foxmail.com import os import sys import time import queue from collections import namedtuple from threading import Thread from typing import (Any, Callable, Dict, List, Sequence, Tuple) import tkinter as tk from tkinter import ttk from tkinter.scrolledtext import ...
wsgi.py
""" WSGI config for youtube project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/ """ import os from threading import Thread from apiCall.youtube import youtube from djang...
Browser.py
print("Starting Browser imports... ") from os import chdir, getcwd from collections.abc import Iterable from collections import defaultdict from random import choice, shuffle from math import ceil from time import sleep from datetime import datetime, timedelta from typing import Tuple, Any, Union, Iterable, List, Opt...
client_3.py
import socket from threading import Thread def send_message(): while True: text = input() sock.sendall(bytes(text, "utf-8")) if text == "exit": sock.close() break def receive_message(): while True: data = sock.recv(1024) print(data.decode("utf-...
test_concurrent_transaction.py
from test.integration.base import DBTIntegrationTest, use_profile import threading from dbt.adapters.factory import FACTORY def get_adapter_standalone(config): plugin = FACTORY.plugins[config.credentials.type] cls = plugin.adapter return cls(config) class BaseTestConcurrentTransaction(DBTIntegrationTest...
simulator.py
#!/usr/bin/env python2 # -*- coding: utf-8 -*- # File: simulator.py # Author: Yuxin Wu <ppwwyyxxc@gmail.com> import tensorflow as tf import multiprocessing as mp import time import threading import weakref from abc import abstractmethod, ABCMeta from collections import defaultdict, namedtuple import numpy as np import...
joycond-cemuhook.py
import sys import evdev import pyudev import threading import socket import struct from binascii import crc32 import time import asyncio import signal import dbus import json import argparse import subprocess from termcolor import colored import os.path def print_verbose(str): global args if args.verbose: ...
client.py
from json.decoder import JSONDecodeError import socket import threading import time import plyer import json import re # A thread operated function continuously printing the server response def recieverThread(clientSocket, myMessage): while True: recvdMsg = str(clientSocket.recv(1024).decode()) try: recvdMsg ...
setup.py
# -*- coding: utf-8 -*- """ bromelia.setup ~~~~~~~~~~~~~~ This module implements the central Diameter application object. It works as per Peer State Machine defined in RFC 6733 in order to establish a Diameter association with another Peer Node. :copyright: (c) 2020-present Henrique Marques Ri...
start.py
import threading from telegram import ChatAction, ParseMode from telegram.utils.helpers import escape_markdown from Brain.Modules.help import get_help from Brain.Utils.dbfuncs import user_collect, command_collect PM_START_TEXT = """Hello {}, my name is {}! If you have any questions on how to use me, read /help. I'm ...
test_pipe.py
# -*- coding: utf-8 -*- # ------------------------------------------------------------------------------ # # Copyright 2022 Valory AG # Copyright 2018-2021 Fetch.AI Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # ...
trezor.py
import traceback import sys from typing import NamedTuple, Any, Optional, Dict, Union, List, Tuple, TYPE_CHECKING from electrum_cintamani.util import bfh, bh2u, versiontuple, UserCancelled, UserFacingException from electrum_cintamani.bip32 import BIP32Node, convert_bip32_path_to_list_of_uint32 as parse_path from elect...
_nixcommon.py
# -*- coding: utf-8 -*- import struct import os import atexit from time import time as now from threading import Thread from glob import glob try: from queue import Queue except ImportError: from Queue import Queue event_bin_format = 'llHHI' # Taken from include/linux/input.h # https://www.kernel.org/doc/Docu...
main_window.py
import re import os import sys import time import datetime import traceback from decimal import Decimal import threading import asyncio from typing import TYPE_CHECKING, Optional, Union, Callable, Sequence from electrum.storage import WalletStorage, StorageReadWriteError from electrum.wallet_db import WalletDB from el...
AsynchronousSender.py
from .SenderBase import SenderBase, DEFAULT_ENDPOINT_URL from threading import Lock, Thread class AsynchronousSender(SenderBase): """An asynchronous sender that works in conjunction with the :class:`AsynchronousQueue`. The sender object will start a worker thread that will pull items from the :func:`queue`. Th...
subproc_vec_env.py
import multiprocessing as mp from collections import OrderedDict from typing import Any, Callable, List, Optional, Sequence, Tuple, Type, Union import gym import numpy as np from stable_baselines3.common.vec_env.base_vec_env import ( CloudpickleWrapper, VecEnv, VecEnvIndices, VecEnvObs, VecEnvStep...
files.py
""" author: Jordan Prechac created: 23 Jan, 2020 """ from django.db import connection from django.conf import settings from django.core.files.base import ContentFile from django.core.files.images import get_image_dimensions import gc from io import BytesIO, StringIO import boto3 import os from PIL import Image as PIL...
_logger.py
""" .. References and links rendered by Sphinx are kept here as "module documentation" so that they can be used in the ``Logger`` docstrings but do not pollute ``help(logger)`` output. .. |Logger| replace:: :class:`~Logger` .. |add| replace:: :meth:`~Logger.add()` .. |remove| replace:: :meth:`~Logger.remove()` .. |...
example_selector.py
import importlib import os import pkgutil import signal import string from multiprocessing import Process import igibson.examples as examples from igibson.utils.utils import let_user_pick TIMEOUT = 3 def interrupted(signum, frame): raise ValueError("Time-up for keyboard input") signal.signal(signal.SIGALRM, i...
test_main.py
#!/usr/bin/python import subprocess import os import json import pytest import uuid import time import sys import threading import shutil from convoy import VolumeManager TEST_ROOT = "/tmp/convoy_test/" CFG_ROOT = os.path.join(TEST_ROOT, "convoy") PID_FILE = os.path.join(TEST_ROOT, "convoy.pid") LOG_FILE= os.path.jo...
app.py
"""Application """ import os import time import re import tkinter as tk import json import threading from reversi import BitBoard, MIN_BOARD_SIZE, MAX_BOARD_SIZE, Player, Window, WindowDisplay, ConsoleDisplay, Game, ErrorMessage, strategies class Reversi: """ リバーシゲーム """ INIT, DEMO, PLAY, END, REINI...
controller.py
#!/home/pi/code/pi_env/bin/python3 # Copyright 2020 Harlen Bains # linted using pylint # formatted using black """This script runs on the Raspberry Pi and sends commands to Arduinos. Once a command is sent it then waits a reply and then loops. """ from threading import Thread import serial # pylint: disable=import-er...
test_state.py
# -*- coding: utf-8 -*- ''' Tests for the state runner ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import errno import logging import os import shutil import signal import tempfile import time import textwrap import threading # Import Salt Testing Libs from tests....
__init__.py
""" Socket Extension Hosts a socket server for devices to connect and send data through to MudPi. """ import time import socket import threading from mudpi.workers import Worker from mudpi.exceptions import ConfigError from mudpi.utils import decode_event_data from mudpi.logger.Logger import Logger, L...
MrRobot_02.py
import itertools, string, time, sys, urllib, socket, requests, paramiko, os, threading from datetime import timedelta socket.setdefaulttimeout(2) if sys.platform == "ios": import console else: class con(object): def set_color(r=False,g=False,b=False,c=False): if b: sys.stdout.write("\xb1[34m") else: ...
probe.py
""" This handler, when signaled, gets the active and pending configurations from supervisord and posts to the DartAPI. """ from . import BaseHandler from ..configurations import ConfigurationsManager from dart.common.supervisor import SupervisorClient from dart.common.killer import GracefulEventKiller import dart.agen...
server.py
# server.py from http.server import BaseHTTPRequestHandler,HTTPServer from urllib.parse import urlparse from urllib import parse import socket import threading import logging HTML = ''' <!DOCTYPE html> <html> <head> <meta http-equiv="Content-type" content="text/html;charset=UTF-8"> <title>Short Circuit Loca...
test_ssl.py
import pytest import threading import socket as stdlib_socket import ssl from contextlib import contextmanager from functools import partial from OpenSSL import SSL import trustme from async_generator import asynccontextmanager import trio from .. import _core from .._highlevel_socket import SocketStream, SocketList...
robex.py
import multiprocessing import os import subprocess from time import time from utils.data_utils import DATAROOT import numpy as np def strip_skull_ROBEX(paths, out_dir=None, num_cpus=None): """Use ROBEX to strip the skull of a T1 weighted brain MR Image. Takes ~100s DOES NOT WORK PROPERLY FOR T2 WEIGHTED IMA...
test_shell_interactive.py
#!/usr/bin/env impala-python # -*- coding: utf-8 -*- # # 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 Apach...
helpers.py
"""Auxiliary functionality""" from enum import Enum, auto import time import threading class TaskStates(Enum): """Background task states""" STOPPED = auto() RUNNING = auto() TERMINATING = auto() class ConsoleHeartBeat: """A context manager starting a heart beater printing dots to the given ...
listen.py
import multiprocessing import select from typing import List, Union from django.db import connection, transaction from psycopg2._psycopg import Notify from pgpubsub import process_stored_notifications from pgpubsub.channel import ( BaseChannel, Channel, ChannelNotFound, locate_channel, registry, )...
utils.py
import queue import threading import time class ScheduleQueue(queue.PriorityQueue): """Variant of queue.PriorityQueue where the priorities are times. Entries are tuples of the form (time, data...). Any entry whose time is in the future is treated as not yet in the queue. The perceived length of the queue is eithe...
benchmark.py
# Copyright (c) 2017-2020, Carl Cheung # All rights reserved. import logging import time from multiprocessing import Process USE_GEVENT = True if USE_GEVENT: import gevent as_completed = gevent.wait from gevent.threadpool import ThreadPoolExecutor as ThreadPoolExecutor else: from concurrent.futures i...
jupyter_kernel.py
# -*- coding: utf-8 -*- """Hooks for Jupyter Xonsh Kernel.""" import sys import json import hmac import uuid import errno import hashlib import datetime import builtins import threading from pprint import pformat from argparse import ArgumentParser from collections.abc import Set import zmq from zmq.eventloop import i...
tests.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Sep 24 20:47:48 2019 @author: mrich """ import socket import re import threading import queue """ regex = r"]->!(.+)" test_str = ("[dawg]->bo!rk\n" "[dawg]->b!ork\n" "[dawg]->!bork\n" "[dawg]->!peer\n\n") matches = re.finditer(regex, test_str, re...
ws_core.py
import threading, time, datetime, json, uuid from concurrent.futures.thread import ThreadPoolExecutor import traceback import tornado.ioloop import tornado.web import tornado.websocket import tornado.template import tornado.httpserver from tornado import gen import ssl,os import OmniDB_app.include.Spartacus as Sparta...
test_multiprocessing.py
#!/usr/bin/env python # # Unit tests for the multiprocessing package # import unittest import Queue import time import sys import os import gc import signal import array import socket import random import logging import errno import test.script_helper from test import test_support from StringIO import StringIO _multi...
routes.py
from app import app,forms,db,socketio,mail from flask_socketio import emit,leave_room,join_room from flask import request,redirect,url_for,render_template,flash,get_flashed_messages,flash,jsonify from flask_login import current_user,login_user,logout_user,login_required from app.models import User,thread,post,Courses,e...
devserver.py
import os import time import traceback import threading from werkzeug.serving import run_simple, WSGIRequestHandler from lektor.db import Database from lektor.builder import Builder, process_extra_flags from lektor.watcher import Watcher from lektor.reporter import CliReporter from lektor.admin import WebAdmin from l...
utils.py
import cv2 import numpy import time import struct import os import lz4.block from imutils import contours, grab_contours from datetime import datetime, timedelta from random import uniform, gauss, randint from scipy import spatial from util.adb import Adb from util.logger import Logger from util.config_consts import Ut...
test_lock.py
import multiprocessing import sys import time import pytest from nengo.utils.lock import FileLock, TimeoutError def acquire_lock(filename): lock = FileLock(filename, timeout=0.01, poll=0.01) try: lock.acquire() except TimeoutError: sys.exit(0) else: sys.exit(1) def acquire_...
flic.py
""" Support to use flic buttons as a binary sensor. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/binary_sensor.flic/ """ import logging import threading import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant....
thread2_tkinter.py
""" This example has been adapted from: https://stackoverflow.com/a/29729649/3778792 All credit to its authors. """ from threading import Thread from time import sleep import tkinter as tk from tkinter import ttk def on_loading(widget, status): status("Loading...") widget.start(150) sleep(15) widget....
ws_client.py
# -*- coding: utf-8 -*- import json import threading import traceback import websocket from qqbot.core.exception.error import WebsocketError from qqbot.core.network.ws.dto.enum_intents import Intents from qqbot.core.network.ws.dto.enum_opcode import OpCode from qqbot.core.network.ws.dto.ws_payload import ( WSPayl...
service_info.py
# encoding: utf-8 """ Create on: 2018-09-24 下午3:37 author: sato mail: ysudqfs@163.com life is short, you need python """ import os import subprocess # 获取所有日志文件路径 import threading from utils.services import services def cklog(s): if not os.path.isdir(s.get("logdir")): return False shell = "ls -lh %s%s...
e2e.py
""" This is an end to end release test automation script used to kick off periodic release tests, running on Anyscale. The tool leverages app configs and compute templates. Calling this script will run a single release test. Example: python e2e.py --test-config ~/ray/release/xgboost_tests/xgboost_tests.yaml --test-...
Device.py
import requests from openhomedevice.RootDevice import RootDevice from openhomedevice.TrackInfoParser import TrackInfoParser from openhomedevice.Soap import soapRequest, subscribeRequest, unsubscribeRequest, renewSubscriptionRequest import xml.etree.ElementTree as etree import socket import threading import time cla...
app.py
"""App module. This module define all the class related to UI. """ import os import secrets import threading from typing import Any, Dict, List, Tuple from flask import Flask, render_template from flask_classful import FlaskView, route from flask_socketio import SocketIO from flaskwebgui import FlaskUI ...