source
stringlengths
3
86
python
stringlengths
75
1.04M
telloArucoFollow.py
# -*- coding: utf-8 -*- import numpy as np import cv2 import socket import threading import time import glob import cv2.aruco as aruco markerSize = 0.08 Detect = False rc='rc' p=' ' mtx = np.load('/home/argus/opencv/mtx.npy') dist = np.load('/home/argus/opencv/dist.npy') drone3 = socket.socket(socket.AF_INE...
worker.py
""" Background job workers """ import logging import traceback from datetime import timedelta from multiprocessing import Process from sched import scheduler from time import monotonic, sleep import sentry_sdk from google.protobuf import empty_pb2 from couchers.db import get_engine, session_scope from couchers.jobs.d...
fleetspeak_client.py
#!/usr/bin/env python """Fleetspeak-facing client related functionality. This module contains glue code necessary for Fleetspeak and the GRR client to work together. """ from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals import logging import pdb import plat...
main.py
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 import os import threading import time import sys import argparse from image_processor import ImageProcessor from task_publisher import TaskPublisher import boto3 from codeguru_profiler_agent import Profiler ...
test_storage.py
import time import random import threading import unittest from uuid import uuid4 import hiro import redis from flask.ext.limiter.strategies import FixedWindowRateLimiter, \ MovingWindowRateLimiter from flask.ext.limiter.errors import ConfigurationError from flask.ext.limiter.limits import PER_MINUTE, PER_SECOND ...
runSignalAlign.py
#!/usr/bin/env python """Run signal-to-reference alignments """ from __future__ import print_function import sys from signalAlignLib import * from multiprocessing import Process, Queue, current_process, Manager from serviceCourse.file_handlers import FolderHandler from argparse import ArgumentParser from random import ...
reader.py
# Copyright (c) 2019 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 appli...
miniterm.py
#!/mnt/storage/project.code/python/uart_project/env/bin/python3 # # Very simple serial terminal # # This file is part of pySerial. https://github.com/pyserial/pyserial # (C)2002-2015 Chris Liechti <cliechti@gmx.net> # # SPDX-License-Identifier: BSD-3-Clause import codecs import os import sys import threading impor...
test_concurrent.py
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 ############################################################################### # Integration testing for the MIE workflow API - test concurrency control # # PRECONDITIONS: # MIE base stack must be deployed ...
memory_receiver.py
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. from queue import Queue, Full, Empty import threading import numpy as np import torch from datetime import datetime fr...
bacnet_connector.py
# Copyright 2021. ThingsBoard # # 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 ...
_looperctrl.py
from abc import abstractmethod from threading import Thread, Event from loop._loopsimple import LoopWithDrum from loop._oneloopctrl import OneLoopCtrl from loop._song import Song from utils import MsgProcessor, ConfigName, clear_screen class LooperCtrl(Song, MsgProcessor): """added playback thread, message threa...
tf_inference_ssd300.py
# Needed libraries import argparse from ssd_encoder_decoder.ssd_output_decoder import decode_detections from data_generator.object_detection_2d_misc_utils import apply_inverse_transforms import numpy as np import random import cv2 from threading import Thread from datetime import datetime import time # exemple : #...
probeSniffer.py
#!/usr/bin/env python3 # -.- coding: utf-8 -.- try: import os import sys import time import json import pyshark import sqlite3 import datetime import argparse import threading import traceback import urllib.request as urllib2 except KeyboardInterrupt: print("\n[I] Stoppi...
multi_vs_single_with_sleep.py
import threading import time def worker(x): tid = threading.currentThread().name # do some hard and time consuming work: time.sleep(1) print("Worker {} is working with {}".format(tid, x)) ################################################# # Sequential Processing: #############################################...
streamcommand.py
#!/usr/bin/env python # -*- coding: utf-8 -*- ## @package dbus_vrm import logging logger = logging.getLogger(__name__) import codecs import threading import subprocess from time import sleep # Runs a command, and calls sendfeedback with the statusupdates. class StreamCommand(object): SIGNALS = { 1: "SIGHUP", 2: ...
mp_tutorial_1.py
import multiprocessing def worker(): """ Worker function """ print("worker") return if __name__ == '__main__': jobs = [] for i in range(5): #target is the function we are sending to Process p = multiprocessing.Process(target=worker) jobs.append(p) p.start()
test_threading.py
import gc from threading import Thread import pytest from sentry_sdk import configure_scope, capture_message from sentry_sdk.integrations.threading import ThreadingIntegration @pytest.mark.forked @pytest.mark.parametrize("integrations", [[ThreadingIntegration()], []]) def test_handles_exceptions(sentry_init, captu...
main.py
import os import pickle from typing import Any, Union from threading import Thread from time import sleep from twin_call import TwinUpdater from azure.iot.device import IoTHubModuleClient, Message class HubConnector(): def __init__(self): self.client = IoTHubModuleClient.create_from_edge_environment() ...
GUI.py
"""Graphical User Interface for the application that is done by kivy graphics library.""" import os import signal import socket import subprocess from subprocess import Popen import webbrowser from pathlib import Path import datetime as dt import threading import kivy kivy.require('1.10.1') from kivy.app import App ...
gstreamer.py
# Copyright 2019 Google 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
webserver1.py
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer import cgi import os import urllib2 import hashlib import collections import threading class webServerHandler(BaseHTTPRequestHandler): def compare(self,x,y) : return collections.Counter(x) == collections.Counter(y) def validate_cache...
blastparse_mt3.py
''' PLNCPRO This files reads the blastx output and extracts features for each query. This takes as input the blast output in the following format "qseqid sseqid pident evalue qcovs qcovhsp score bitscore qframe sframe" this output is generated by blast command: ./blastx -query ex.fa -db unirefdb -strand plus -evalue 1e...
main.py
import numpy as np import requests import random import pandas as pd import time import multiprocessing url = 'https://raw.githubusercontent.com/dwyl/english-words/master/words_alpha.txt' existingWords = requests.get(url) existingWords = existingWords.text.split() existingWords = [word for word in existingWo...
windows.py
import contextlib import ctypes import ctypes.wintypes import io import json import os import re import socket import socketserver import threading import time import typing import click import collections import collections.abc import pydivert import pydivert.consts REDIRECT_API_HOST = "127.0.0.1" REDIRECT_API_PORT ...
download_from_file.py
""" Given a csv or txt file, download the image urls to form the dataset. """ import argparse import os from csv import writer as csv_writer from multiprocessing import Process, Queue import requests import pandas as pd import numpy as np from tqdm import tqdm from pathlib import Path def create_dataset(filepath, url...
ttsrobot.py
# # K9 Conversation by Richard Hopkins using # Kitt-AI Snowboy for hotword recognition # Watson Speech to Text (streaming to sockets) # Watson Conversation # eSpeak Text to Speech # Robot status displayed with Adafruit PWM Servo Driver driving LED brightness # # TTS elements derived from # Joshua Rees-Jones, IBM intern...
ipsectun.py
import struct from ctypes import * import os from fcntl import ioctl import socket import threading import signal import hashlib import sys import re from random import randint try: from Crypto.Cipher import AES except ModuleNotFoundError: print ("Install pycrypto using 'sudo pip install pycrypto'" ) sys.exit(...
memdaemon.py
import tensorflow as tf import time import threading import collections import gc import numpy as np def memcheck_tensors(): from tensorflow.python.framework.ops import EagerTensor eagers=[] graphy=[] nalloc=collections.defaultdict(lambda: 0.0) for ob in gc.get_objects(): try: ...
executormarionette.py
import json import os import socket import threading import traceback import urlparse import uuid errors = None marionette = None pytestrunner = None here = os.path.join(os.path.split(__file__)[0]) from .base import (CallbackHandler, ExecutorException, RefTestExecutor, ...
server.py
"""Fix TCP server module.""" import errno import socket import select import threading import queue from testplan.common.utils.sockets.fix.parser import FixParser from testplan.common.utils.timing import ( TimeoutException, TimeoutExceptionInfo, wait, ) from testplan.common.utils.sockets.fix.utils import ...
algo_two.py
from functools import reduce from sys import * import numpy as np import random as r import socket import struct import subprocess as sp import threading from threading import Thread import ast import time import datetime as dt import os import psutil from netifaces import interfaces, ifaddresses, AF_INET import paho.m...
taobao.py
# # 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 "License"); you may not us...
check_public_headers.py
#!/usr/bin/env python # # Checks all public headers in IDF in the ci # # Copyright 2020 Espressif Systems (Shanghai) PTE 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...
spinner.py
# Copyright (c) 2018-2020, Vanessa Sochat All rights reserved. # See the LICENSE in the main repository at: # https://www.github.com/openbases/openbases-python import os import sys import sys import time import threading from random import choice class Spinner: spinning = False delay = 0.1 @staticmet...
test_queue.py
import threading import time from typing import NamedTuple import pytest import pymq class Payload(NamedTuple): name: str value: int class EventWithPayload: payload: Payload def __init__(self, payload: Payload) -> None: self.payload = payload class TestQueue: def test_queue_name(sel...
__init__.py
import argparse import gettext import os import threading import time import pkg_resources from collections import defaultdict from http.server import HTTPServer, SimpleHTTPRequestHandler from tempfile import TemporaryDirectory from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler ...
test_pool.py
import collections import random import threading import time from unittest.mock import ANY from unittest.mock import call from unittest.mock import Mock from unittest.mock import patch import weakref import sqlalchemy as tsa from sqlalchemy import event from sqlalchemy import pool from sqlalchemy import select from s...
runner.py
import logging import threading from ansible.cli import CLI from ansible.plugins.strategy.linear import StrategyModule from ansible.plugins.strategy import StrategyBase from ansible.cli.playbook import PlaybookCLI from ansible.parsing.yaml.objects import AnsibleUnicode from cotea.ansible_execution_sync import ans_syn...
test_mp.py
# 当前文件名称为test.py # 引入Process模块 from multiprocessing import Process def func(): print("子进程正在运行") if __name__ == '__main__': """由于系统创建进程机制的原因,windows下必须 写if __name__ == '__main__'语句""" p = Process(target=func,) """这一步骤将函数注册到一个进程中,p是一个进程对象, 此时还没有启动进程,只是创建了一个进程对象. 这里的func是不加括号的,因为加上括号函数就直接运行了"...
test_itertools.py
import unittest from test import support from itertools import * import weakref from decimal import Decimal from fractions import Fraction import operator import random import copy import pickle from functools import reduce import sys import struct import threading import gc maxsize = support.MAX_Py_ssize_t minsize = ...
jd_OpenCrad.py
#!/bin/env python3 # -*- coding: utf-8 -* ''' 项目名称: JD_OpenCard Author: Curtin 功能:JD入会开卡领取京豆 CreateDate: 2021/5/4 下午1:47 UpdateTime: 2021/5/23 ''' version = 'v1.1.1' readmes = """ # JD入会领豆小程序 ![JD入会领豆小程序](https://raw.githubusercontent.com/curtinlv/JD-Script/main/OpenCrad/resultCount.png) ## 使用方法 #### [手机用户(参考) https...
bench.py
import os import logging import MySQLdb import time import sys import Queue import threading import json createUserSQL = "INSERT IGNORE INTO users (name) VALUES (%s);" getUserByUsernameSQL = "SELECT * FROM users WHERE name=%s;" getAuthorByNameSQL = "SELECT * FROM authors WHERE name=%s;" createAuthorSQL = "INSERT...
SteppingTest8.py
from multiprocessing import Process, Value, Array def f(n, a): n.value = 3.1415927 for i in range(len(a)): a[i] = -a[i] if __name__ == '__main__': num = Value('d', 0.0) arr = Array('i', range(10)) p = Process(target=f, args=(num, arr)) p.start() p.join() print(num.value) ...
custom.py
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
sparse_conditional_accumulator_test.py
# Copyright 2015 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...
dependency_manager.py
from contextlib import closing from collections import namedtuple import logging import os import threading import traceback import time import shutil from codalab.lib.formatting import size_str from codalab.worker.file_util import remove_path, un_tar_directory from codalab.worker.fsm import BaseDependencyManager, Dep...
launch_client.py
#!/usr/bin/env python # -*- coding: UTF-8 -*- # # Copyright (c) 2020 ASMlover. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright...
app.py
import os import signal import threading import asyncio from flask import Flask from flask.logging import default_handler from webcandy_client import start_client from opclib import FadecandyServer from . import routes from .config import Config, configure_logger from .extensions import db, migrate, api from .models ...
ern.py
#!/usr/bin/env python import RPi.GPIO as GPIO import time import os import requests import threading import rethinkdb as rdb from gps import * import socket #This ERN node id node_id = os.environ["NODE_ID"] #The ERN server ip address or domain name ern_server = "ern.erki.net" #The RethinkDB client port ern_port = 2...
manager.py
#!/usr/bin/env python3 import os import time import sys import fcntl import errno import signal import shutil import subprocess import datetime import textwrap from typing import Dict, List from selfdrive.swaglog import cloudlog, add_logentries_handler from common.basedir import BASEDIR from common.hardware import HA...
server.py
#!/usr/bin/python2 import atexit import logging import threading import time import Pyro4 from MaxiNet.tools import MaxiNetConfig Pyro4.config.SOCK_REUSE = True class NameServer(object): def __init__(self, config=MaxiNetConfig()): self.config = config self.logger = logging.getLogger(__name__) ...
test_decimal.py
# expected: fail # - takes too long # Copyright (c) 2004 Python Software Foundation. # All rights reserved. # Written by Eric Price <eprice at tjhsst.edu> # and Facundo Batista <facundo at taniquetil.com.ar> # and Raymond Hettinger <python at rcn.com> # and Aahz (aahz at pobox.com) # and Tim Peters """ Th...
test_refleaks.py
"""Tests for refleaks.""" import itertools import platform import threading from six.moves.http_client import HTTPConnection import cherrypy from cherrypy._cpcompat import HTTPSConnection from cherrypy.test import helper data = object() class ReferenceTests(helper.CPWebCase): @staticmethod def setup_ser...
executor.py
"""HighThroughputExecutor builds on the Swift/T EMEWS architecture to use MPI for fast task distribution """ from concurrent.futures import Future import logging import threading import queue import pickle from multiprocessing import Process, Queue from ipyparallel.serialize import pack_apply_message # ,unpack_apply...
transport.py
import sys sys.path.append("..") import pypibot from pypibot import log import serial import threading import struct import time from dataholder import MessageID, BoardDataDict FIX_HEAD = 0x5a class Recstate(): WAITING_HD = 0 WAITING_MSG_ID = 1 RECEIVE_LEN = 2 RECEIVE_PACKAGE = 3 RECEIVE_CHECK = 4...
lisp-rtr.py
# ----------------------------------------------------------------------------- # # Copyright 2013-2019 lispers.net - Dino Farinacci <farinacci@gmail.com> # # 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...
loader.py
""" Shaurya Pratap Singh @shaurya-blip Shows loading message while doing something. """ import itertools import threading import time import sys # The task is not done right now done = False def animate(message="loading", endmessage="Done!"): for c in itertools.cycle(['|', '/', '-', '\\']): if done: ...
nanny.py
import asyncio from contextlib import suppress import errno import logging from multiprocessing.queues import Empty import os import psutil import shutil import threading import uuid import warnings import weakref import dask from dask.system import CPU_COUNT from tornado.ioloop import IOLoop, PeriodicCallback from to...
Model3.py
# Model3.py import Match3 import os # import shutil # import tempfile import threading import time NORMAL = 1 MISMATCH = 2 CONFLICT = 3 # Current state of the model STATE_NORMAL = 0 STATE_NEW = 1 STATE_ENUMERATING = 2 STATE_PRECOMPARING = 3 STATE_COMPARING = 4 STATE_COPYING = 5 STATE_DELETING = 6 STATE_MERGING = 7 ...
run.py
from datasource_manager import DatasourceManager from os import environ from app import app from config import LISTEN_PORT, DEBUG, PG_URL from threading import Thread import psycopg2 db_conn = psycopg2.connect(PG_URL) db_cursor = db_conn.cursor() db_cursor.execute( """ create extension if not exists "uuid-ossp...
word2vec.py
"""Multi-threaded word2vec mini-batched skip-gram model. Trains the model described in: (Mikolov, et. al.) Efficient Estimation of Word Representations in Vector Space ICLR 2013. http://arxiv.org/abs/1301.3781 This model does traditional minibatching. The key ops used are: * placeholder for feeding in tensors for eac...
irc.py
from __future__ import unicode_literals, division, absolute_import, with_statement from builtins import * # pylint: disable=unused-import, redefined-builtin from past.builtins import basestring import os import re import threading import logging from xml.etree.ElementTree import fromstring import io from uuid import ...
run_unittests.py
#!/usr/bin/env python3 # Copyright 2016-2017 The Meson development 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 # Unless required by ...
util.py
# Electrum - lightweight Bitcoin client # Copyright (C) 2011 Thomas Voegtlin # # 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 t...
core.py
import os import time import queue import re import threading import copy from collections import OrderedDict import requests import lxml.html import multiprocessing from .helpers import color_logging from .url_queue import UrlQueue from . import helpers def parse_seeds(seeds): """ parse website seeds. @para...
zk.py
# Copyright 2016 ETH Zurich # # 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, sof...
feed.py
# PyAlgoTrade # # Copyright 2011-2015 Gabriel Martin Becedillas Ruiz # # 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 ap...
gui.py
import eel import os import battlecode_cli as cli import threading import sys import json import signal import psutil import player_plain import battlecode as bc import zipfile import requests import base64 import shutil target_dir = os.path.abspath(os.path.dirname(__file__)) print('Moving into', target_dir) os.chdir...
main.py
import socket import ssl import random import time import threading import logging import json thread_amount = int(input("Number of Threads: ")) f = open('validPins.txt', 'a') def main(name): for _ in range(10000): random_numbers = str(random.randint(100000, 999999)) ssl_context ...
test_general.py
"""Collection of tests for unified general functions.""" # global import os import math import time import einops import pytest from hypothesis import given, strategies as st import threading import numpy as np from numbers import Number from collections.abc import Sequence import torch.multiprocessing as multiprocess...
web_app.py
# -*- coding: utf-8 -*- """ Created on Wed Aug 5 14:53:52 2020 @author: Nikki """ #useful references: #https://blog.miguelgrinberg.com/post/easy-websockets-with-flask-and-gevent #https://github.com/miguelgrinberg/Flask-SocketIO from threading import Lock from flask import Flask, render_template, session, request, \ ...
case_study2.py
import re import threading import glob import sys def find_derived_class(fname,pattern,old_pattern): new_pattern="\("+pattern+"\)" f=open(fname,'r') for line in f: lo=re.findall(new_pattern,line) if len(lo)>0: low=re.findall('class (\w+)',line) obj=" ".join(low) ...
installwizard.py
from functools import partial import threading import os from kivy.app import App from kivy.clock import Clock from kivy.lang import Builder from kivy.properties import ObjectProperty, StringProperty, OptionProperty from kivy.core.window import Window from kivy.uix.button import Button from kivy.uix.togglebutton impo...
main.py
from threading import Thread from multicamera import MultiCapture, FramesThreadBody, NormalizerCLAHE import time, sys, queue, cv2 import numpy as np def check_pressed_keys(key): if key == 32: # Pause while True: key = cv2.waitKey(0) if key == 27 or key == 32 or key == 13: # ente...
bartender.py
import time import sys import os import RPi.GPIO as GPIO import json import traceback import threading import Adafruit_GPIO.SPI as SPI import Adafruit_SSD1306 from PIL import Image from PIL import ImageFont from PIL import ImageDraw from dotstar import Adafruit_DotStar from menu import MenuItem, Menu, Back, MenuCont...
chronometer.py
#!/usr/bin/env python3 import time import threading class Chronometer: def __init__(self): self.clear() def init(self): self.clear() self.__stoped = False timing = threading.Thread(target=self.__init, daemon=True) timing.start() def clear(self): self.s = ...
15_6_1_argv.py
import threading, time def threading_argv(): threadObj = threading.Thread(target=print, args=['Cats', 'Dogs', 'Frogs'], kwargs={'sep':' & '}) threadObj.start() def main(): print('Cats', 'Dogs', 'Frogs', sep=' & ') threading_argv() if __name__ == '__main__': main()
__init__.py
""" Yay! It's NOT IDA!!!1!!1!one! """ import os import re import sys import time import queue import string import hashlib import logging import itertools import traceback import threading import collections import envi import envi.exc as e_exc import envi.bits as e_bits import envi.common as e_common import envi...
eval_overlapping_connected.py
import os import sys import glob import multiprocessing as mp import numpy as np import matplotlib.pyplot as plt from ctypes import c_float import math import util import util_feature_IO import util_batch import util_geometry import util_meta import util_amira import constants import calc_features_mp def getEmptySta...
buffered_queue.py
from cloudbutton.multiprocessing import Process, Queue, getpid import time def f(q): print("I'm process", getpid()) q.put([42, None, 'hello']) time.sleep(5) if __name__ == '__main__': q = Queue() p = Process(target=f, args=(q,)) p.start() print(q.get()) # prints "[42, None, 'hello']" ...
ratings.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distrib...
ltipy.py
from subprocess import Popen, PIPE, STDOUT import re import os import sys import signal import threading import time import ltmain import pickle import json def noop(): pass ipy = None respond = None requests = {} connected = noop disconnected = noop def km_from_string(s=''): """create kernel manager from IPKe...
wdf.py
#!/usr/bin/env python # coding=utf-8 from __future__ import print_function import os import requests import re import time import xml.dom.minidom import json import sys import math import subprocess import ssl import threading DEBUG = False MAX_GROUP_NUM = 2 # 每组人数 INTERFACE_CALLING_INTERVAL = 5 # 接口调用时间间隔, 间隔太短容易...
test_multiprocessing.py
from multiprocessing import Process, Value, Lock from multiprocessing.managers import BaseManager class Employee(object): def __init__(self, name, salary): self.name = name self.salary = Value('i', salary) self.data=[] def increase(self): self.salary.value += 100 self....
email.py
from threading import Thread from flask import render_template, current_app from flask_mail import Message from rhytmic_exam_app import mail def send_async_email(app, msg): with app.app_context(): with mail.connect(): mail.send(msg) def send_email(subject, sender, recipients, text_body, html...
builtin.py
""" A library for integrating Python's builtin :py:mod:`ssl` library with RaspiMote_https. The :py:mod:`ssl` module must be importable for SSL functionality. To use this module, set ``HTTPServer.ssl_adapter`` to an instance of ``BuiltinSSLAdapter``. """ from __future__ import absolute_import, division, print_functio...
mumbleBot.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import re import threading import time import sys import math import signal import configparser import audioop import subprocess as sp import argparse import os import os.path import pymumble_py3 as pymumble import pymumble_py3.constants import variables as var import logg...
process_value_array.py
#!/usr/bin/python # -*- coding: utf-8 -*- from multiprocessing import Process, Value, Array def f(n, a): n.value = n.value + 1 for i in range(len(a)): a[i] = a[i] * 10 if __name__ == '__main__': num = Value('i', 1) arr = Array('i', range(10)) p = Process(target=f, args=(num, arr)) p.start() p.join() prin...
custom.py
# pylint: disable=too-many-lines # -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -----------------------------------...
cache.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for the QueryCache functionality of johnny.""" from __future__ import print_function from threading import Thread from django.conf import settings from django.core.paginator import Paginator from django.db import connection, connections, transaction from django....
job.py
# Copyright (c) 2019 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_events.py
"""Tests for events.py.""" import collections.abc import concurrent.futures import functools import io import os import platform import re import signal import socket try: import ssl except ImportError: ssl = None import subprocess import sys import threading import time import errno import unittest from unitt...
func.py
""" 面向用户的函数 ,提供极其便捷的体验 """ import logging from datetime import time, datetime from inspect import isfunction from multiprocessing import Process from time import sleep from typing import Text, Any, List import ctpbee.app as ap from ctpbee.constant import \ (OrderRequest, CancelRequest, Direction, Exchange, ...
screens.py
import asyncio from weakref import ref from decimal import Decimal import re import threading import traceback, sys from typing import TYPE_CHECKING, List, Optional, Dict, Any from kivy.app import App from kivy.cache import Cache from kivy.clock import Clock from kivy.compat import string_types from kivy.properties im...
optimization_checks.py
# Copyright 2017 Google Inc. All rights reserved. # Use of this source code is governed by the Apache 2.0 license that can be # found in the LICENSE file. """Run the various optimization checks""" import binascii import gzip import logging import os import Queue import re import shutil import struct import subprocess i...
jabbergram.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from sys import argv, exit, stderr def log(*args): print(*args) def err(*args): print(*args, file=stderr) try: import requests except: err('HTTP Upload support disabled.') import sleekxmpp import telegram import configparser from threading import Thread from qu...
test_process.py
# (C) Copyright 2020- ECMWF. # # This software is licensed under the terms of the Apache Licence Version 2.0 # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. # # In applying this licence, ECMWF does not waive the privileges and immunities # granted to it by virtue of its status as an intergovernme...
__init__.py
import tensorflow as tf import time from datetime import datetime import math from pynvml import * import tensorpack import os from tqdm import tqdm, trange import numpy as np from dnnweaver2.tf_utils.dataset import ImageNetProducer from dnnweaver2.tf_utils.helper import DataSpec import logging def time_tensorflow_r...
instagram.py
import json import re import threading import requests from pymongo import MongoClient USERNAME = 'wwe' URL = 'https://www.instagram.com/' + USERNAME def set_threading(node, database): get_id = node['id'] src = node['thumbnail_src'] caption = node['caption'] comments = node['comments']['count'] l...