source
stringlengths
3
86
python
stringlengths
75
1.04M
text_console.py
import contextlib import sys import threading import traceback import wx from ..icons import icon from ..utils import Frame class CallbackStringIO: def __init__(self, callback): self.callback = callback def write(self, s: str): sys.__stdout__.write(s) self.callback(s) def flush...
standalone_test.py
"""Tests for acme.standalone.""" import multiprocessing import os import shutil import socket import threading import tempfile import unittest import warnings import time from contextlib import closing from six.moves import http_client # pylint: disable=import-error from six.moves import socketserver # type: ignore ...
_inversion.py
# Copyright (2013) Sandia Corporation. Under the terms of Contract # DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government # retains certain rights in this software. # # This software is released under the FreeBSD license as described # in License.txt import time import string import subprocess import os im...
executors.py
import copy import cloudpickle import itertools import multiprocessing import os import signal import subprocess import sys import threading import warnings from concurrent.futures import ThreadPoolExecutor from concurrent.futures import TimeoutError as FutureTimeout from functools import wraps from logging import Logg...
data_plane_test.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...
telnet.py
import socket import threading class net: """Sort of a lightweight telnet server.""" def __init__(self): # super(net, self).__init__() self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.host = 'localhost' #socket.gethostname() # print('timeout:',socket.getdefaulttimeout()) def telnet(se...
utils.py
# -*- coding: utf-8 -*- import hashlib import logging import sys import threading Unify_encoding = "utf-8" class helper: """used by WuKongQueueClient and WuKongQueue""" def __init__(self, inst): self.inst = inst def __enter__(self): return self def __exit__(self, exc_type, exc_val...
__init__.py
"""Hermes MQTT server for Rhasspy TTS using external program""" import io import logging import socket import threading import time import typing import wave from queue import Queue import pyaudio import webrtcvad from rhasspyhermes.asr import AsrStartListening, AsrStopListening from rhasspyhermes.audioserver import (...
1.4.2.py
#coding:utf-8 ''' 1. threading模块创建多线程 import random import time, threading # 新线程执行的代码: def thread_run(urls): print 'Current %s is running...' % threading.current_thread().name for url in urls: print '%s ---->>> %s' % (threading.current_thread().name,url) time.sleep(random.random()) print '%...
tensorflow_inference_service.py
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import logging import os import signal import threading import time import subprocess #import pyarrow as pa import tensorflow as tf from abstract_inference_service import AbstractInfe...
p2p_utils.py
# P2P helper functions # Copyright (c) 2013-2015, Jouni Malinen <j@w1.fi> # # This software may be distributed under the terms of the BSD license. # See README for more details. import logging logger = logging.getLogger() import threading import time import Queue import hwsim_utils MGMT_SUBTYPE_PROBE_REQ = 4 MGMT_SU...
thread_consumer_producer.py
import threading, time import queue # 3.7.生产者消费者模型 # # 在并发编程中使用生产者和消费者模式能够解决绝大多数并发问题。该模式通过平衡生产线程和消费线程的工作能力来提高程序的整体处理数据的速度。 # # 为什么要使用生产者和消费者模式? # # 在线程世界里,生产者就是生产数据的线程,消费者就是消费数据的线程。 # 在多线程开发当中,如果生产者处理速度很快,而消费者处理速度很慢,那么生产者就必须等待消费者处理完,才能继续生产数据。 # 同样的道理,如果消费者的处理能力大于生产者,那么消费者就必须等待生产者。为了解决这个问题于是引入了生产者和消费者模式。 # # 什么是生产者消费...
feedback-server.py
import socket import threading import re import sys s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(('', 8080)) s.listen() def get_body(data): body = b'None' body_length = -1 try: parts = data.split(b'\r\n\r\n') if parts...
main.py
import numpy as np import tensorflow as tf print('tensorflow', tf.__version__) from trainer import Trainer from config import get_config from utils import prepare_dirs_and_logger, save_config, load_config from colorama import Fore, Back, Style from dataLoad import * from folderDefs import * import subprocess, threa...
sproc.py
""" ################################################## ⛏️sproc: subprocesseses for subhumanses ⛏ ################################################## Run a command in a subprocess and yield lines of text from stdout and stderr ********* EXAMPLES ********* .. code-block:: python import sproc CMD = 'my-unix-c...
_rpc.py
# Copyright 2017 gRPC 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 agreed to in writing...
oke.py
# -*- coding: utf-8 -*- #My Script by danrfq #Support by My Beloved Team Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ #i'm Owner Ꭲ̡̦͎͇͈̘̻̎̉̅́̒͗ͅϵѧᴍ̸̩̟̗͎̯͙̺̺̜̬̙̟̀̑̓͋̐͆͌̓̒́̒͗͒͑̚͟͜ᎶʀҽѧᴛᏴøᴛ̢͓̹̗̘̠̪̖͗̃̄̅̆̽̀̕͜͞ import LINETCR from LINETCR.lib.curve.ttypes import * from datetime import datetime i...
teleop_client.py
# Adapted from https://github.com/sergionr2/RacingRobot # Author: Antonin Raffin import argparse import os import time from threading import Event, Thread import numpy as np import pygame from pygame.locals import * from stable_baselines.bench import Monitor from stable_baselines.common.vec_env import VecFrameStack, V...
data_store_test.py
#!/usr/bin/env python # -*- mode: python; encoding: utf-8 -*- """These are basic tests for the data store abstraction. Implementations should be able to pass these tests to be conformant. """ from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals import functool...
multi_process_runner.py
# Lint as: python3 # Copyright 2019 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 ...
map_reduce.py
# -*- coding: utf-8 -*- r""" Parallel computations using RecursivelyEnumeratedSet and Map-Reduce There is an efficient way to distribute computations on a set `S` of objects defined by :func:`RecursivelyEnumeratedSet` (see :mod:`sage.sets.recursively_enumerated_set` for more details) over which one would like to perfo...
test.py
#!/usr/bin/env python # # Copyright 2008 the V8 project authors. 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 # noti...
tooling.py
############################################################################### # Copyright 2019 UChicago Argonne, LLC. # (c.f. AUTHORS, LICENSE) # # This file is part of the NRM project. # For more info, see https://github.com/anlsys/nrm-python # # SPDX-License-Identifier: BSD-3-Clause ################################...
DPPO.py
""" A simple version of OpenAI's Proximal Policy Optimization (PPO). [http://adsabs.harvard.edu/abs/2017arXiv170706347S] Distributing workers in parallel to collect data, then stop worker's roll-out and train PPO on collected data. Restart workers once PPO is updated. The global PPO updating rule is adopted from Deep...
misc_para.py
import multiprocessing #http://stackoverflow.com/questions/3288595/multiprocessing-how-to-use-pool-map-on-a-function-defined-in-a-class/21345308 def fun(f,q_in,q_out): while True: i,x=q_in.get() if i is None: break q_out.put((i,f(x))) def parmap(f,X,nprocs=multiprocessing.cpu_...
_utilities_test.py
# Copyright 2015, Google Inc. # 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 # notice, this list of conditions and the f...
coconutbar.py
""" Author : k0rventen License : MIT Version : 0.4 Home : https://github.com/k0rventen/coconutbar """ import socket # For IP import os # for listing dirs import argparse # cli arg parser import time # sleepy import subprocess # both for import threading # bspc thread import signal # Exit cleanly from datetime i...
collect_data.py
import threading from logging import Logger from typing import Dict from injector import inject, singleton from altymeter.api.exchange import TradingExchange from altymeter.module.constants import Configuration @singleton class DataCollector(object): @inject def __init__(self, config: Configuration, ...
independent.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import json import math import os import random import threading import numpy as np import tensorflow as tf import conll import metrics import optimization import util from bert import modeling from bert impo...
windows.py
import configargparse import pickle as pickle from ctypes import byref, windll, Structure from ctypes.wintypes import DWORD import os import socket import socketserver import struct import threading import time from collections import OrderedDict from pydivert.windivert import WinDivert from pydivert.enum import Direc...
more_program.py
# import threading # # num = 1 # # # def demo1(): # global num # 把num提升为全局变量 # num += 1 # print("demo1的num是%s" % num) # # # def demo2(): # print("demo2的num是%s" % num) # # # def main(): # t1 = threading.Thread(target=demo1) # t2 = threading.Thread(target=demo2) # t1.start() # t2.start() ...
_queue.py
import multiprocessing q= multiprocessing.Queue(3) def download(q): data=[1,2,3] for i in data: q.put(i) def handle(q): data=list() while True: data.append(q.get()) if q.empty(): break print('下载的数据为{}'.format(data)) def main(): p1=multiprocessing.Process(target=download,args=(q,)) p...
bd.py
#!/usr/bin/python3 #Title: bd.py #Author: ApexPredator #License: MIT #Github: https://github.com/ApexPredator-InfoSec/back_door #Description: This script provides a reverse shell or bind shell on Linux or Windows systems. It can be used to establish persistence after compromising a system by setting a cronjob, schedule...
zssdk_bak.py
import re import sys try: import urllib3 except ImportError: print 'urlib3 is not installed, run "pip install urlib3"' sys.exit(1) import string import json from uuid import uuid4 import time import threading import functools import traceback import base64 import hmac import sha from hashlib import sha1 i...
tab_base_classes.py
##################################################################### # # # /tab_base_classes.py # # # # Copyright 2013, Monash University ...
dirbust.py
import requests import sys from threading import Thread, Lock from queue import Queue from colorama import Fore, Back, Style q = Queue() list_lock = Lock() discovered_directories = [] def scan_directories(host): global q while True: try: # Get the directory from the queue direc...
Attack.py
from TrivialFunctions import * from AttackPatterns import * import threading import socket minPort = 1024 bind_ip = "0.0.0.0" localIP = "192.168.56.101" def encodeFile(OS, filename): #OR veil https://github.com/Veil-Framework/Veil #@TODO have casual cyphers if OS == "Linux": executeCommand("msfveno...
stream2bytes.py
""" Directly map received ZMQ frames to files without decoding. This interface is meant for performance testing. DISCLAIMER: This code is build for demonstration pupose only. It is not meant to be productive, nor efficient or complete. If you have any questions regarding the implementation of the EIGER stream interfa...
keep_alive.py
from flask import Flask from threading import Thread app = Flask('') @app.route('/') def home(): return "I'm alive" def run(): app.run(host='0.0.0.0',port=5764) def keep_alive(): t = Thread(target=run) t.start()
mmalobj.py
# vim: set et sw=4 sts=4 fileencoding=utf-8: # # Python header conversion # Copyright (c) 2013-2017 Dave Jones <dave@waveform.org.uk> # # Original headers # Copyright (c) 2012, Broadcom Europe Ltd # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted...
live_response_api.py
from __future__ import absolute_import import json import random import string import threading import time import logging from collections import defaultdict import shutil from cbapi.errors import TimeoutError, ObjectNotFoundError, ApiError, ServerError from cbapi.six import itervalues from concurrent.futures impor...
window.py
from Xlib import X, Xutil from Xlib.display import Display from threading import Thread class Window(object): def __init__(self, display=None): if display is None: display = Display() self.d = display self.screen = self.d.screen() bgsize = 20 bgpm = self.screen...
Queue.py
# -*- coding: utf-8 -*- # MIT License # # Copyright (c) 2020 Northwave B.V. (www.northwave-security.com) # # 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 with...
git_common.py
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # Monkeypatch IMapIterator so that Ctrl-C can kill everything properly. # Derived from https://gist.github.com/aljungberg/626518 import multiprocessing.pool ...
mybot.py
# -*- coding: utf-8 -*- import os, sys from threading import Thread from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, ConversationHandler, CallbackQueryHandler from app.utils import func_handler, task def main(): if func_handler.Config.ifproxy == 'true': updater = Updat...
tracking_gs.py
""" Tkinter based ground station for the tracking data coming down from JAGER. """ import Tkinter import time import threading import random import Queue import socket import sys import numpy as np import tracking_msg_parser as tmp # matplot lib handling for use with Tkinter import matplotlib matplotlib.use('TkAgg') f...
evolve.py
"""This module contains the `evolve` function used to obtain an instance of `Specimen` fit to the given fit function. """ from threading import Thread from specimen import Specimen from inspect import isfunction def evolve( function_table, fit_function, inputs_num, nodes_num, outputs_num, des...
test_threading.py
# Very rudimentary test of threading module import test.support from test.support import verbose import random import re import sys import threading import _thread import time import unittest import weakref from test import lock_tests # A trivial mutable counter. class Counter(object): def __init__(self): ...
NLU.py
###################################################################################################### # # Organization: Asociacion De Investigacion En Inteligencia Artificial Para La Leucemia Peter Moss # Repository: GeniSysAI # Project: Natural Language Understanding Engine # # Author: Adam Milton-Ba...
script-render.py
#!/usr/bin/python3 # -*- coding: UTF-8 -*- '''BlendNet Script Render Description: Special script used by the agent to render the task ''' # Since blender reports status only to stdout - we need this # separated script to watch on progress from the agent process. # # When it will be possible to read the status of rend...
microtvm_api_server.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 u...
upgrade_center.py
import time import threading from .base.event_base import EventBase class UpgradeCenter(EventBase): def __init__(self): super(UpgradeCenter, self).__init__() self.workers = {} self.run_status = [] self.is_processing = False self.is_error = False self.current = 0 ...
sxclzy.py
import logging import pickle import re import sys import threading import time from inspect import isfunction from dill.source import getsource as gs import datetime import prettytable as pt import psutil from .sqlite_model import SxclzySchedule from .sqlite_orm import GetData from .Dict import Dict class Sxclzy: ...
http_server.py
import webview import sys import threading try: from BaseHTTPServer import HTTPServer from SimpleHTTPServer import SimpleHTTPRequestHandler except ImportError: from http.server import SimpleHTTPRequestHandler, HTTPServer """ This example demonstrates how a trivial application can be built using a HTTP se...
DarkMatter.py
import socket import os from time import sleep import multiprocessing import random import platform print("Detecting System...") sysOS = platform.system() print("System detected: ", sysOS) if sysOS == "Linux": try: os.system("ulimit -n 1030000") except Exception as e: print(e) print("Could not start t...
mission.py
#!/usr/bin/env python3 # encoding: utf-8 # # Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved. # # This file is part of ewm-cloud-robotics # (see https://github.com/SAP/ewm-cloud-robotics). # # This file is licensed under the Apache Software License, v. 2 except as noted # otherwise in the LIC...
HiwinRA605_socket_ros_test_20190626133115.py
#!/usr/bin/env python3 # license removed for brevity #接收策略端命令 用Socket傳輸至控制端電腦 import socket ##多執行序 import threading import time ## import sys import os import numpy as np import rospy import matplotlib as plot from std_msgs.msg import String from ROS_Socket.srv import * from ROS_Socket.msg import * import HiwinRA605_s...
script.py
import sys import ConfigParser from os.path import expanduser # Set system path home = expanduser("~") cfgfile = open(home + "\\STVTools.ini", 'r') config = ConfigParser.ConfigParser() config.read(home + "\\STVTools.ini") # Master Path syspath1 = config.get('SysDir','MasterPackage') sys.path.append(syspath1) # Built Pa...
test_generator_mt19937.py
import sys import hashlib import pytest import numpy as np from numpy.linalg import LinAlgError from numpy.testing import ( assert_, assert_raises, assert_equal, assert_allclose, assert_warns, assert_no_warnings, assert_array_equal, assert_array_almost_equal, suppress_warnings) from numpy.random import G...
logging.py
"""Cyberjunky's 3Commas bot helpers.""" import json import logging import os import queue import threading import time from logging.handlers import TimedRotatingFileHandler as _TimedRotatingFileHandler import apprise class NotificationHandler: """Notification class.""" def __init__(self, program, enabled=Fa...
device_handlers.py
import re, os, socket from threading import Thread import serial import netifaces as ni class TestDevice: def __init__(self): pass def download(self): pass def deviceLearn(self): pass def deviceReset(self): pass def waitDeviceReady(self, timeout=20): pass...
proxy-con-to-cli.py
#!/usr/bin/python3 # This is a simple port-forward / proxy, written using only the default python # library. If you want to make a suggestion or fix something you can contact-me # at voorloop_at_gmail.com # Distributed over IDC(I Don't Care) license import socket import select import time import sys import threading #...
main_tsa.py
import time import sys import threading import mininet.link as link from mininet.util import irange from traffic import iperf, iperf_udp from wireless import PhyModel from mobility_model import RegionDistribution from fill_rt import configure_downlink, configure_uplinks from selection_algorithm import simple_tsa_algo...
test_decimal.py
# 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 """ These are the test cases for...
execute_code.py
''' This module is responsible for handling the execution of python code given by the telegram user. ''' import logging from subprocess import TimeoutExpired import subprocess import multiprocessing from .config import BANNED, TIMEOUT, TIMEOUT_MESSAGE, RESTRICT_MESSAGE def contains_restricted(input_text): '''retu...
app_utils.py
# From http://www.pyimagesearch.com/2015/12/21/increasing-webcam-fps-with-python-and-opencv/ import struct import six import collections import cv2 import datetime from threading import Thread from matplotlib import colors class FPS: def __init__(self): # store the start time, end time, and total number ...
event.py
import threading from queue import Queue from .const import JobEventName from .models import JobStartedEvent, JobSucceededEvent, JobStoppedEvent, JobAbortedEvent from lightflow.models.exceptions import (EventTypeUnknown, JobEventTypeUnsupported, WorkerEventTypeUnsupported) de...
utils.py
# -*- coding: utf-8 -*- # Copyright 2012-2021 CERN # # 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 a...
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...
demo.py
import logging from multiprocessing import Process, Queue from pathlib import Path from suitcase.jsonl import Serializer from bluesky import RunEngine from ophyd.sim import det, det4, noisy_det, motor, motor1, motor2, img from bluesky.plans import scan, count, grid_scan from bluesky.preprocessors import SupplementalDa...
camera.py
# pylint: disable=protected-access, line-too-long, logging-fstring-interpolation, dangerous-default-value, logging-not-lazy, too-many-lines from signal import signal, SIGINT, SIGTERM import argparse from io import BytesIO from socket import SocketIO import socket from sys import maxsize, argv from enum import Enum im...
websocket.py
import asyncio import logging import json import threading import websockets logger = logging.getLogger("pyCharity." + __name__) class WebsocketClient: """ A threaded websocket client in charge of updating the canvas board in real-time. """ def __init__(self, uri: str, canvas): self.uri = u...
localmultithread.py
from __future__ import absolute_import from pysnptools.util.mapreduce1.runner import Runner,_JustCheckExists, _run_all_in_memory, _shape_to_desired_workcount, _work_sequence_for_one_index import os import logging try: import dill as pickle except: logging.warning("Can't import dill, so won't be able to clusteri...
ccpreprocessor.py
# use this if you have a spare computer with multiple CPUs and a very good internet link # command line: python3 worker-multicpu.py N nickname # where N = max number of CPU to use # nickname is you nickname for the leaderboard # examples: # 10Gbps internet link and 6 million PPS routing - use N = 40 (max) # 1Gbps inter...
doji.py
# ## Complete Doji # import threading # import pandas as pd # from queue import Queue # import time # import requests # file = open("stock_pred.txt", "w") # data = pd.read_csv("C:\\Users\\BEST BUY\\Desktop\\NASDAQ_20200331.csv") # symbols = data.iloc[:100,0:1].values # th = Queue(maxsize = 4000) def doji(arg): # p...
process_dataset.py
import numpy as np import os import sys import cv2 import time import queue import argparse from tqdm import tqdm import threading from constants import * parser = argparse.ArgumentParser(description='Preprocess SegNet Data') parser.add_argument('--data_root', required=True) parser.add_argument('--mask_dir', required...
gemini.py
import asyncio import base64 import hashlib import hmac import json import os import queue import ssl import time import traceback from datetime import date, datetime, timedelta from threading import Thread from typing import Dict, List, Optional, Tuple import pandas as pd import requests import websocket from pytz im...
__init__.py
from __future__ import unicode_literals, print_function import json import threading from awsshell import shellcomplete from awsshell import autocomplete from awsshell import app from awsshell import docs from awsshell import loaders from awsshell.index import completion from awsshell import utils __version__ = '0....
Interpreter_test_util.py
# This file is licensed under the MIT license. # See license for more details: https://github.com/leonard112/OctaneScript/blob/main/README.md import pytest import mock import builtins import time import threading import _thread from Interpreter import Interpreter # References for timout class # https://stackoverflow...
miditokey.py
# encoding: utf-8 ''' author: Taehong Kim email: peppy0510@hotmail.com ''' import keyboardex as keyboard import mido # import pyautogui import threading import time # pyautogui.press('a') # pyautogui.typewrite('quick brown fox') # for i in range(10): # pyautogui.hotkey('alt', 'ctrl', 'shift', 'w') # pyautogui...
webcam-opencv-example.py
import numpy as np import cv2 import time import requests import threading from threading import Thread, Event, ThreadError class Cam(): def __init__(self, url): self.stream = requests.get(url, stream=True) self.thread_cancelled = False self.thread = Thread(target=self.run) print "camera initi...
Classes.py
import socks import threading import proxy from tqdm import tqdm def progressBar(iterable, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = "\r"): total = len(iterable) def printProgressBar (iteration): percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / fl...
tests.py
from __future__ import unicode_literals import threading from datetime import datetime, timedelta from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist from django.db import DEFAULT_DB_ALIAS, DatabaseError, connections from django.db.models.manager import BaseManager from django.db.models.que...
dashboard.py
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
server.py
#!/usr/bin/env python from http.server import BaseHTTPRequestHandler, HTTPServer import json import sys import videoModule from threading import Thread #videoModule.testHTTPServer_RequestHandler is in videoModule because otherwise import loop def run(): print("Instantiiate video processor") videoProcessor = vi...
file_server.py
from functools import partial from http.server import HTTPServer, SimpleHTTPRequestHandler from threading import Thread def run_file_server_thread(debug): server = _create_file_server(debug) Thread(target=lambda: server.serve_forever(), daemon=True).start() return server.server_address def _create_file_...
filesystem.py
# Snafu: Snake Functions - Filesystem Connector import pyinotify import threading import os import configparser gcb = None gf = None class EventHandler(pyinotify.ProcessEvent): def process_IN_CREATE(self, event): event = {"file": event.pathname, "action": "create"} gcb(gf, event=event) def process_IN_DELETE(s...
rest_helper.py
#!/usr/bin/env python3 # # """rest_helper.py Usage: rest_helper.py [-v] [-n=<count>|--num=<count>] [-c=<fname>|--config=<fname>] rest_helper.py (-h | --help) rest_helper.py (-V | --version) Options: -h --help Show this screen and exit -V --version Show Version and exit...
collect_telemetry_events.py
# Microsoft Azure Linux Agent # # Copyright 2020 Microsoft Corporation # # 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 b...
test_ga.py
import unittest from unittest.mock import patch, create_autospec, NonCallableMagicMock import os from datetime import datetime from copy import deepcopy import multiprocessing as mp import threading from time import sleep import itertools import tests.data_files as _df from tests.models import IEEE_9500, IEEE_13 from ...
example0.py
#!/usr/bin/env python3 import multiprocessing def worker(): print('new worker') for i in range(8): multiprocessing.Process(target = worker).start()
KeepAlive.py
from flask import Flask from threading import Thread app = Flask('') @app.route('/') def home(): return("Hello I am alive") def run(): app.run(host='0.0.0.0', port=8080) def keep_alive(): t=Thread(target=run) t.start()
sqlite_time_scheduling.py
import time import json import threading import requests import psutil import datetime from twisted.logger import Logger from .config import Config from scrapydartx import global_values as glv class TimeSchedule: def __init__(self, lock, host='127.0.0.1', port='6800'): config = Config() self.db =...
train.py
import argparse import logging import math import os import random import time from copy import deepcopy from pathlib import Path from threading import Thread import numpy as np import torch.distributed as dist import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torch.optim.lr_sche...
test_logging.py
# Copyright 2001-2019 by Vinay Sajip. All Rights Reserved. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose and without fee is hereby granted, # provided that the above copyright notice appear in all copies and that # both that copyright notice and this permissio...
OnkyoCore.py
import re import struct import time import socket, select import threading import xmltodict import json from copy import deepcopy import queue as queue import netifaces from collections import namedtuple from OnkyoCommands import COMMANDS, ZONE_MAPPINGS, COMMAND_MAPPINGS, VALUE_MAPPINGS from OnkyoUtils import ValueRan...
teamtalk.py
"""PyTeamTalk A wrapper around the TeamTalk 5 TCP API. author: Carter Temm license: MIT http://github.com/cartertemm/pyteamtalk """ import shlex import time import threading import telnetlib import warnings import functools # constants ## MSG Types NONE_MSG = 0 USER_MSG = 1 CHANNEL_MSG = 2 BROADCAST_MSG = 3 CUSTO...
telegram_downloader.py
import logging import random from time import time from threading import RLock, Lock, Thread from bot import LOGGER, download_dict, download_dict_lock, app, STOP_DUPLICATE, STORAGE_THRESHOLD from bot.helper.ext_utils.bot_utils import get_readable_file_size from ..status_utils.telegram_download_status import TelegramD...
example_jack_o_lantern.py
# Python code generated by CAIT's Visual Programming Interface import random import cait.essentials import threading face_coordinate = None screen_center = None rotate_power = None playing_audio = None x1 = None audio_list = None x2 = None face_center = None person = None coordinates = None face = None power = None s...
mail_libs.py
# !/usr/bin/env python # -*-coding:utf-8 -*- # PROJECT : web-common-service # Time :2020/12/4 11:25 # Warning :The Hard Way Is Easier from threading import Thread from flask_mail import Message from flask import current_app from webAPi.extensions import mail def _send_async_mail(app, message): """异步发送...