source
stringlengths
3
86
python
stringlengths
75
1.04M
sdk_worker.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...
PitchTrainingContent.py
import os import threading from pydub import AudioSegment from pydub.playback import play from Project.Constants import OS_PATH from Project.UI.CommonWidgets.CommonButtons import RadioButtonsGroup, StartStopButton from Project.UI.CommonWidgets.CommonLabels import Label, CardLabel from Project.UI.ContentComponent impor...
ProteinStructureUtilsServer.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime import json import os import random as _random import sys import traceback from getopt import getopt, GetoptError from multiprocessing import Process from os import environ from wsgiref.simple_server import make_server import requests as _requests from json...
word2vec.py
# coding: utf-8 # Copyright 2017 Shen Fei & Ein plus Ltd. All Rights Reserved. # 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 # ...
log.py
import json import sys import time from pathlib2 import Path from logging import LogRecord, getLogger, basicConfig, getLevelName, INFO, WARNING, Formatter, makeLogRecord, warning from logging.handlers import BufferingHandler from threading import Thread, Event from six.moves.queue import Queue from ...backend_api.serv...
manager.py
from dataclasses import dataclass import logging import threading import time import traceback from pathlib import Path from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Iterator from concurrent.futures.thread import ThreadPoolExecutor from blspy import G1Element from chiapos import DiskProver from ...
proxy.py
import socket, multiprocessing, time, json, webob import request class proxy: def __init__(self, configFile, domain="0.0.0.0"): with open(configFile, "r") as f: self.config = json.load(f) self.outSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.outSock.setsockopt(...
mininet.py
#!/usr/bin/python """ This example creates a multi-controller network from semi-scratch; note a topo object could also be used and would be passed into the Mininet() constructor. """ import time import subprocess from threading import Thread from time import sleep import socket from random import randint ...
train.py
import torch import torch.distributed as dist import torch.multiprocessing as mp import argparse, os, random, sys, time from ctypes import c_bool from parser.data import Vocab, DataLoader, SRLDataLoader, DynamicDataLoader, DUM, END, CLS, NIL from parser.parser import Parser from parser.work import show_progress from p...
test.py
import time import threading import random from collections import Counter import pytest from helpers.cluster import ClickHouseCluster cluster = ClickHouseCluster(__file__) node1 = cluster.add_instance('node1', macros={'cluster': 'test1'}, with_zookeeper=True) # Check, that limits on max part size for merges doesn...
workflow.py
# Copyright (c) 2014-2020, Dr Alex Meakins, Raysect Project # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # ...
nanny.py
import asyncio 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 tornado import gen from .comm import get_addre...
lock.py
import time import threading num=0 def sing(nums): global num mutex.acquire() for i in range(nums): num+=1 mutex.release() print('sing{}'.format(num)) def dance(nums): global num mutex.acquire() for i in range(nums): num+=1 mutex.release() print('dance{}'.format(num)) mutex=threading....
minion.py
# -*- coding: utf-8 -*- ''' Routines to set up a minion ''' # Import python libs from __future__ import absolute_import, print_function import os import re import sys import copy import time import types import signal import fnmatch import logging import threading import traceback import multiprocessing from random imp...
ExampleWDLServer.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime import json import os import random as _random import sys import traceback from getopt import getopt, GetoptError from multiprocessing import Process from os import environ from wsgiref.simple_server import make_server import requests as _requests from json...
wandb_run.py
# # -*- coding: utf-8 -*- from __future__ import print_function import atexit from datetime import timedelta from enum import IntEnum import glob import json import logging import numbers import os import platform import re import sys import threading import time import traceback from types import TracebackType from ...
event_emitter.py
# -*- coding: utf-8 -*- import asyncio from collections.abc import Coroutine from multiprocessing import Process class EventEmitter(object): def __init__(self, loop=None): self._events = {} self._loop = loop or asyncio.get_event_loop() def _on(self, event, listener): if event not in s...
HandSerial.py
# -*- coding: utf-8 -* # HandSerial class for communication with hand micro controlller import sys # insert at 1, 0 is the script path (or '' in REPL) sys.path.insert(1, '../serial_data_plotter') from MotorCommand import MotorCommand from collections import namedtuple from threading import Lock, Thread import serial...
framework_test.py
# Copyright 2016 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...
thread_example.py
from queue import Queue from threading import Thread import copy import time # A thread that produces data def webserver(name, outqueue): while True: # Produce some data outqueue.put(copy.deepcopy(time.time())) time.sleep(0.9) # A thread that consumes data def ledhandler(name, inqueue): while True: # Get ...
httpserver.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst # -*- coding: utf-8 -*- import os import queue import shutil import tempfile import threading import http.server import socketserver from ..extern.RangeHTTPServer import RangeHTTPRequestHandler __all__ = ['HTTPServer', 'RangeHTTPServer'] def run_ser...
monitor_hits.py
#!/usr/bin/env python # vim: ts=4 sw=4 et from datetime import datetime from collections import deque import os from io import StringIO import shutil import time import threading import matplotlib # Force matplotlib to not use any Xwindows backend. matplotlib.use('Agg') # noqa import matplotlib.pyplot as plt impor...
paralell.py
""" Functions and scripts for running paralell tasks """ # -------------------------------------------------------------------------------------------------- # IMPORTS # -------------------------------------------------------------------------------------------------- from tqdm import tqdm from multiprocessing i...
backend.py
# -*- coding: utf-8 -*- import os import re import shutil import subprocess import sys import threading import time import webbrowser # to open link on browser from collections import namedtuple from typing import Tuple from urllib import request import requests from diskcache import Cache import services as s cach...
test_dag_serialization.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...
test_fx.py
# Owner(s): ["oncall: fx"] import builtins import contextlib import copy import functools import inspect import math import numbers import io import operator import os import pickle import sys import torch import traceback import typing import types import warnings import unittest import torch.nn.utils._stateless as _...
runtests.py
#!/usr/bin/env python from __future__ import print_function import atexit import base64 import os import sys import re import gc import heapq import locale import shutil import time import unittest import doctest import operator import subprocess import tempfile import traceback import warnings import zlib import glo...
lib_pump_dump.py
# -*- coding: utf-8 -*- """ Created on Fri Apr 30 22:05:44 2021 @author: Ravi raj purohit """ import matplotlib matplotlib.use('Qt5Agg') matplotlib.rcParams.update({'font.size': 14}) import numpy as np import time, datetime from bs4 import BeautifulSoup from PyQt5 import QtCore, QtGui from PyQt5.QtCore im...
scrape.py
import multiprocessing as mp from datetime import datetime from utils import filters import time from scrapers.sections import * from scrapers import pelando # Tempo para esperar entre requisições STANDARD_DELAY=15 def InParallel(urls=[],alvo=None): queue = mp.Queue() processes = [mp.Process(target=alvo,args...
test_multithreading.py
""" Separate file for multithreading since it takes time to run """ import threading import pytest import requests import responses @pytest.mark.parametrize("execution_number", range(10)) def test_multithreading_lock(execution_number): """Reruns test multiple times since error is random and depends on CPU a...
app.py
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 import cgi import urlparse import traceback from threading import Thread from SocketServer import ThreadingMixIn from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer from django.utils.simplejson import JSONEncoder from django.db.models.query import QuerySet ...
botHandler.py
import time import os from threading import Lock, Thread import copy as cp import json from config.config import config from bots.botIRC import BotIRC from bots.botChess import BotChess from lib.misc import print_debug class BotHandler: """ Class to handle Bots """ # json file used by OBS to update its sce...
idf_monitor.py
#!/usr/bin/env python # # esp-idf serial output monitor tool. Does some helpful things: # - Looks up hex addresses in ELF file with addr2line # - Reset ESP32 via serial RTS line (Ctrl-T Ctrl-R) # - Run "make flash" (Ctrl-T Ctrl-F) # - Run "make app-flash" (Ctrl-T Ctrl-A) # - If gdbstub output is detected, gdb is automa...
frames_example.py
import sys sys.path.insert(0,'..') import threading import time import CMDUI as CMD def counter(): btn_txt.set("Stop") tt = time.time() while running: t = f"{(time.time()-tt)**10:.2f}" txt.set(t) time.sleep(0.01) btn_txt.set("Reset") def stopwatch(): if btn_txt.g...
membership_word.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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
execute.py
# Based on Katherine Crowson's CLIP guided diffusion notebook # (https://colab.research.google.com/drive/12a_Wrfi2_gwwAuN3VvMTwVMz9TfqctNj) # including a port of https://github.com/crowsonkb/guided-diffusion to jax. import math import io import sys import time import os import functools from functools import partial ...
ffmpeg.py
#!/bin/bash import subprocess as sp import datetime as dt import threading import platform import sys import os import re PY2 = (sys.version_info[0] == 2) WINDOWS = platform.system() == 'Windows' if PY2: from Queue import Queue else: from queue import Queue class FFmpeg(object): def __init__(self, cmd, stdout_si...
test_gc.py
import unittest from test.support import (verbose, refcount_test, run_unittest, strip_python_stderr, cpython_only, start_threads, temp_dir, requires_type_collecting, TESTFN, unlink, import_module) from test.support.script_helper import assert...
monitor.py
import multiprocessing import json import time import sys import re import logging from collections import defaultdict from jinja2 import Template from scipy.interpolate import spline from scipy.signal import butter, lfilter import matplotlib.pyplot as plt import numpy as np """ stats = { 'switches': defaultdict(d...
detector.py
#!/usr/bin/env python3 """ Fault detector class is part of a thesis work about distributed systems """ __author__ = "Bruno Chianca Ferreira" __license__ = "MIT" __version__ = "0.1" __maintainer__ = "Bruno Chianca Ferreira" __email__ = "brunobcf@gmail.com" import socket, os, math, struct, sys, json, traceback, zlib,...
run.py
# Copyright (c) 2020 Institution of Parallel and Distributed System, Shanghai Jiao Tong University # ServerlessBench is licensed under the Mulan PSL v1. # You can use this software according to the terms and conditions of the Mulan PSL v1. # You may obtain a copy of Mulan PSL v1 at: # http://license.coscl.org.cn/M...
demo07.py
# -*- coding: utf-8 -*- from multiprocessing import Process, Manager def f(d, l): d[1] = '1' d['2'] = 2 d[0.25] = None l.reverse() if __name__ == '__main__': manager = Manager() d = manager.dict() l = manager.list(range(10)) p = Process(target=f, args=(d, l)) p.start() p.jo...
ddos_dissector.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ############################################################################### # Concordia Project # # This project has received funding from the European Union’s Horizon # 2020 Research and Innovation program under Grant Agreement No 830927. # # Joao Ceron - joaocer...
common.py
"""Contain common discord fixtures""" import asyncio import threading from time import sleep from typing import Optional, List, Union import pytest from discord import Client, Guild, TextChannel, VoiceChannel, CategoryChannel, Role from bot.bot import BdoDailyBot from settings import settings @pytest.fixture(scope=...
Logger.py
import multiprocessing, logging, sys, re, os, StringIO, threading, time, Queue, collections from logging import Logger class MultiProcessingLogHandler(logging.Handler): """taken from http://stackoverflow.com/questions/641420/how-should-i-log-while-using-multiprocessing-in-python added counting of log message...
__main__.py
import sys import os import logging import stat import time from threading import Thread from PySide2.QtWidgets import QApplication from vlc import EventType from .player import VLC, VLCWindow, Status logger = logging.getLogger('slimvlc') DEFAULT_SNAPS_LOCATION = os.path.abspath(os.getcwd()) DEFAULT_FORMATTER = \ ...
data_loader.py
import numpy as np import h5py import time from numpy import genfromtxt from utils.myfuncs import * import threading import tensorflow as tf import sys class DataGenerator: def __init__(self, config, mode, coord=None, max_queue_size=80): self.config = config # informations in the config.json file ...
generate_mock_data.py
import hashlib import json import os import random import threading import sys import time import uuid import functools import pandas as pd import numpy as np from fate_test._config import Config from fate_test._io import echo, LOGGER def import_fate(): from fate_arch import storage from fate_flow.utils import...
timer.py
''' Timer related stuff ''' import logging import threading import time from enum import Enum from utils import config from utils import utils from utils.errors import AldebaranError, ArchitectureError logger = logging.getLogger(__name__) class Timer: ''' Timer running with a frequency, handling subtimers...
driver_util.py
"""Scripts for drivers of Galaxy functional tests.""" import collections import fcntl import httplib import json import logging import os import random import shutil import socket import string import struct import sys import tempfile import threading import time import nose.config import nose.core import nose.loader...
wrapper.py
""" Contains the wrappers for all preprocessing components. """ # There is some redundancy left between the PreprocessorWrapper on the one hand # and the TokenizerWrapper, TaggerWrapper and ChunkerWrapper on the other. Much # of it has been removed but in some cases changes on one end need to be # accompanied by sim...
recorder.py
import PIL from PIL import Image,ImageTk from tkinter import * import tkinter as tk import time from environment.variable import CONFIG_PATH import pickle import ui as Ui from imutils import face_utils import cv2 import numpy as np import dlib import os from environment.variable import ROOT_DIR,DATASET_DIR from multipr...
sleepy_barber.py
import time import queue import random import threading class SleepyBarber: def __init__(self, count_chairs=5): self.count_chairs = count_chairs self.clients = queue.Queue(self.count_chairs) self.id = 0 self.block = threading.Semaphore(1) self.start_threads() def gene...
run.py
import os, sys, time, subprocess import logging, threading from seproject_group18.app import views from seproject_group18.script import bikeinfo, weatherinfo, processmanagement from multiprocessing import Process class StreamToLogger(object): """ Fake file-like stream object that redirects writes to a logger ...
test_nc.py
import pytest import queue import threading from socketserver import StreamRequestHandler, TCPServer from netconsole import Netconsole class NetconsoleServerHandler(StreamRequestHandler): def handle(self): q = self.server.msg_queue while True: item = q.get(timeout=2.0) i...
test_plot.py
"""Tests the utils.plot module of pyexperiment Written by Peter Duerr """ from __future__ import print_function from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import import unittest import mock from multiprocessing import Queue from threading import Thread fro...
stay_alive.py
from flask import Flask import os from threading import Thread from dotenv import load_dotenv load_dotenv('./.env') app = Flask('') @app.route('/') def index(): return("Don't kill me please D:") def run(): app.run(host=os.getenv("HOST"),port=os.getenv("PORT")) def staying_alive(): t = Thread(target=run...
test_smtplib.py
import asyncore import base64 import email.mime.text from email.message import EmailMessage from email.base64mime import body_encode as encode_base64 import email.utils import hashlib import hmac import socket import smtpd import smtplib import io import re import sys import time import select import errno import textw...
concurrentImage.py
import threading import urllib.request import time def downloadImage(imagePath, fileName): print("Downloading Image from ", imagePath) urllib.request.urlretrieve(imagePath, fileName) print("Completed Download") def executeThread(i): imageName = "temp/image-" + str(i) + ".jpg" downloadImage("http://lorempix...
wifi_fap_spam.py
from scapy.all import * from websploit.core import base from threading import Thread from websploit.core.utils import get_fake_mac, get_fake_name conf.verb = 0 class Main(base.Module): """Spamming Fake access points """ parameters = { "iface": "wlan0mon", "count": 10, } completions = ...
client.py
# -*- coding: utf-8 -*- import sys import cv2 import time import numpy as np import threading import socket import json from PIL import ImageGrab from PyQt5.QtCore import Qt from PyQt5.QtGui import QPixmap, QImage from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel class Client(QMainWindow): def __init_...
test_concurrent_futures.py
import test.support # Skip tests if _multiprocessing wasn't built. test.support.import_module('_multiprocessing') # Skip tests if sem_open implementation is broken. test.support.import_module('multiprocessing.synchronize') # import threading after _multiprocessing to raise a more relevant error # message: "No module n...
threading_event.py
#!/usr/bin/env python # encoding: UTF-8 import threading import logging import time logging.basicConfig(level=logging.DEBUG, format='(%(threadName)-10s) %(message)s', ) def wait_for_event(e): logging.debug('wait_for_event starting') event_is_set=e.wait() logging.d...
wandb_run.py
# # -*- coding: utf-8 -*- from __future__ import print_function import atexit from datetime import timedelta import glob import json import logging import numbers import os import platform import re import sys import threading import time import traceback from types import TracebackType from typing import ( Any, ...
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 ...
uart_provider.py
import os import re import time import json import struct import datetime import threading from ..base import OpenDeviceBase from ..decorator import with_device_message from ...framework.utils import (helper, resource) from . import dmu_helper from .configuration_field import CONFIGURATION_FIELD_DEFINES_SINGLETON from ...
minion.py
# -*- coding: utf-8 -*- ''' Routines to set up a minion ''' # Import python libs from __future__ import absolute_import, print_function, with_statement, unicode_literals import functools import os import sys import copy import time import types import signal import random import logging import threading import tracebac...
multiple_pipelines.py
################################################################################ # The MIT License # # Copyright (c) 2021, Prominence AI, Inc. # # 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 Softwar...
collector.py
import time from logging import getLogger from multiprocessing import RLock, Event, Value, Process from threading import Thread from psutil import NoSuchProcess from tatau_core.metrics import ProcessSnapshot logger = getLogger('tatau_core') class MetricsCollector: def __init__(self, interval=1, collect_load=Fa...
lockfile_test.py
#!/usr/bin/env vpython3 # Copyright 2020 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. """Unit tests for lockfile.py""" import logging import os import shutil import sys import tempfile import threading import unittest ...
internetradio.py
# Internet Radio mode for PiRadio # Uses MPD to stream sources. Playlist of stations is defined in code below. from subprocess import check_output from time import sleep from threading import Thread from resources.basemode import RadioBaseMode # Define the radio stations STATIONS = [("Radio 1", "http://bbcmedia.ic.l...
_heartbeat.py
''' a mixin class for heatbeat to rabbitmq server. ''' from time import sleep import threading # send heartbeat signal after 5 secs to rabbitmq. HEART_BEAT = 5 class HeartBeatMixin: @staticmethod def _beat(connection): while True: # TODO: remove hardcode sleep(HEART_BEAT) ...
thermos_observer.py
from __future__ import print_function import socket import sys import time from twitter.common import app from twitter.common.exceptions import ExceptionalThread from twitter.common.http import HttpServer from twitter.common.http.diagnostics import DiagnosticsEndpoints from twitter.thermos.common.path import TaskPath...
poller.py
#!/usr/bin/env python #-*- coding: utf-8 -*- # Author: (linuxfish.exe@gmail.com) ######################################################################### # Created Time: 2016-04-12 17:43:55 # File Name: poller.py # Description: check the availability of the links of a website recursively ##############################...
rhmsg.py
# # Copyright (c) 2015,2018 Red Hat # Licensed under The MIT License (MIT) # http://opensource.org/licenses/MIT # from __future__ import absolute_import import itertools import json import logging import threading import Queue from django.conf import settings from . import BaseMessenger logger = logging.getLogger(_...
test_suite.py
#!/usr/bin/env python # Copyright 1996-2019 Cyberbotics Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
multiprocessing_experiment.py
import torch.multiprocessing as mp import os import pickle import ner from ner import ( trainer, active_heuristic, vocab, conlldataloader ) from ner.tensor_logger import Logger from ner.constants import ( ACTIVE_LEARNING_SAMPLE, ACTIVE_LEARNING_TOP_K, ) from ner.models.cached_bilstm_crf impor...
multithreading.py
import threading from datetime import datetime def s(): for i in range(1,10): print("cubes :",i**2) time.sleep(5) def c(): for i in range(1,10): print('Square :',i**3) time.sleep(5) if __name__=='__main__': tc=threading.Thread(target=c,args=()) ts=threading.Thread(tar...
fileIO_multi.py
import sys import time from multiprocessing import Process def read_file_via_heavy_task(idx,num_process,lines): for line in lines[idx::num_process]: print("process num= ",idx,"do some...",line.strip()) time.sleep(1.0) def main(): num_process=4 with open("test.txt",'r') as f: lines=...
timeout.py
from multiprocessing import Process, Queue import time import sys def _target(queue, function, *args, **kwargs): """ Run a function with arguments and return output via a queue. This is a helper function for the Process created in _Timeout. It runs the function with positional arguments and keyword a...
headset_processor.py
import threading from multiprocessing import Queue from time import sleep import numpy as np from tensorflow import keras class data_stream: def __init__(self): # This is the queue that data will be added to after processing self.buffer_queue = Queue() self.processed_queue = Queue() ...
event_sender.py
import collections import json import threading import time from kafka import KafkaConsumer from kafka import TopicPartition from kafka.errors import NoBrokersAvailable # The following kafka topics are accessible by the management UI topics = ['addOffer', 'buyOffer', 'profit', 'updateOffer', 'updates', 'salesPerMinut...
env_wrappers.py
"""Env wrappers Most common wrappers can be checked from following links for usage: `https://pypi.org/project/gym-vec-env` `https://github.com/openai/baselines/blob/master/baselines/common/*wrappers.py` """ from collections import deque from functools import partial from multiprocessing import Pipe, Process, cpu_count...
test_node_threads.py
from threading import Event, Thread global true_conditions true_conditions = 0 locker = Event() def Node_Thread(locker): locker.clear() # To prevent looping, see manual, link below locker.wait(2.0) # Suspend the thread until woken up, or 2s timeout is reached if not locker.is_set(): # when is_set() f...
process.py
# -*- coding: utf-8 -*- # Import python libs from __future__ import absolute_import, with_statement import copy import os import sys import time import errno import types import signal import logging import threading import contextlib import subprocess import multiprocessing import multiprocessing.util import socket ...
extract.py
import os import re from datetime import datetime from queue import Queue from threading import Thread from webcraw import kuaishoulist as ks import utils from extractor import (acfun, baidutieba, bilibili, changya, douyin, haokan, ku6, kuaishou, kugou, kuwo, lizhiFM, lofter, migu_music, ...
context.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...
async_request.py
# -*- coding: utf-8 -*- import urllib2 from PyQt4.QtCore import * import threading import sys class AsyncRequest(QObject): done = pyqtSignal(int, str) fail = pyqtSignal(str) def __init__(self, url, params): QObject.__init__(self) self.url = url self.params = params def _build...
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...
IAC-with-emoji.py
""" This programme is written and may only be used for educational purposes! Using it for real purposes violates the Instagram guidelines! Consequences are, for example, the blocking of the Instagram account. Please read Instagram's guidelines for more information. DO NOT indicate used program sections as your own. ©20...
runqueue.py
#!/usr/bin/env python # ex:ts=4:sw=4:sts=4:et # -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- """ BitBake 'RunQueue' implementation Handles preparation and execution of a queue of tasks """ # Copyright (C) 2006-2007 Richard Purdie # # This program is free software; you can redistribute it and/or mod...
proxy_oa.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...
client.py
import threading import logging from time import sleep import requests from pycrowdsec.cache import Cache, RedisCache from importlib.metadata import version logger = logging.getLogger(__name__) class QueryClient: def __init__( self, api_key, lapi_url="http://localhost:8080/", use...
thread_safety.py
from threading import Thread, Lock class SingletonMeta(type): """ meta class used to create new singleton classes """ _instances = {} _Lock : Lock = Lock() def __call__(cls, *args, **kwargs): with cls._Lock: if not cls in cls._instances: instance = sup...
snake.py
import math import random import pygame import tkinter as tk from tkinter import messagebox import socket import threading import queue # essa strng vai servir para adicionar os caracteres da direção(e, d, c, b) receber_direcoes = "" ID = "1" # id do snake para o outro snake saber e não mostrar os proprios comandos ...
__init__.py
from nmigen import * from nmigen.lib.fifo import AsyncFIFOBuffered import os, sys, time, random, string, struct import asyncio from threading import Thread from .. import Applet from ...gateware import * from ...host import * SOURCE = "source" SINK = "sink" LOOPBACK = "loopback" _all_modes = [SOURCE, SINK, LOOPBAC...
compare_num_layer_w_multiprocessing_adam.py
import qiskit import numpy as np import sys import multiprocessing sys.path.insert(1, '../') import qtm.base, qtm.constant, qtm.ansatz, qtm.fubini_study, qtm.encoding def run_w(num_layers, num_qubits): thetas = np.ones(num_qubits*num_layers*5) qc = qiskit.QuantumCircuit(num_qubits, num_qubits) loss_values...
thread_specific_data_2.py
import random import threading import logging logging.basicConfig(level=logging.DEBUG, format='(%(threadName)-10s) %(message)s', ) def show_value(data): try: val = data.value except AttributeError: logging.debug('No value yet') else: logging...
main.py
#!/usr/bin/env python3 # coding=utf-8 import sys import time from threading import Thread import serial import serial.tools.list_ports from serial.serialutil import SerialException from PIL import Image import glm from OpenGL.GL import * from OpenGL.GL.shaders import * from OpenGL.GLU import * from OpenGL.GLUT import ...
running.py
# -*- coding: utf-8 -*- """Code for maintaining the background process and for running user programs Commands get executed via shell, this way the command line in the shell becomes kind of title for the execution. """ import collections import logging import os.path import shlex import shutil import signal import...