source stringlengths 3 86 | python stringlengths 75 1.04M |
|---|---|
stream.py | """ Orlov Plugins : Minicap Stream Utility. """
from typing import Union, Optional
import os
import sys
import socket
import logging
import threading
from queue import Queue
PATH = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
if PATH not in sys.path:
sys.path.insert... |
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... |
utils.py | import queue
import threading
from django.contrib.auth.models import AnonymousUser
from django.db import connection
from django.contrib.messages.storage.fallback import FallbackStorage
from django.contrib.sessions.backends.db import SessionStore
from django.core.signing import Signer
from django.test import RequestFac... |
cluster_monitor_3_test.py | # Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... |
manager.py | #!/usr/bin/env python2.7
import os
import sys
import time
import fcntl
import errno
import signal
if __name__ == "__main__":
if os.path.isfile("/init.qcom.rc") \
and (not os.path.isfile("/VERSION") or int(open("/VERSION").read()) < 4):
raise Exception("NEOS outdated")
# get a non-blocking stdout
chil... |
validate_urb.py | #!/usr/bin/env python3
import argparse
import os, atexit
import textwrap
import time
import tempfile
import threading, subprocess
import barrier, finishedSignal
import signal
import random
import time
from enum import Enum
from collections import defaultdict, OrderedDict
BARRIER_IP = 'localhost'
BARRIER_PORT = 10... |
custom.py | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
interface_io.py | __all__ = ['sei']
import multiprocessing
from src.BusinessCentralLayer.setting import *
from src.BusinessLogicLayer.plugins.noticer import send_email
from src.BusinessViewLayer.myapp.forms import app
if 'win' in sys.platform:
multiprocessing.freeze_support()
class _SystemEngine(object):
def __init__(self):... |
multiplexer.py | from __future__ import absolute_import
from __future__ import unicode_literals
from threading import Thread
from six.moves import _thread as thread
try:
from Queue import Queue, Empty
except ImportError:
from queue import Queue, Empty # Python 3.x
STOP = object()
class Multiplexer(object):
"""
C... |
simulator.py | __author__ = 'gkour'
from universe import Universe
from statistics import Stats
import printing
from configsimulator import ConfigSimulator
import time
import threading
from enum import Enum
class SimState(Enum):
IDLE = "Simulation Idle"
INITIALIZING = "Simulation Initialized"
RUNNING = "Si... |
stomp.py | import websocket
import time
from threading import Thread
BYTE = {
'LF': '\x0A',
'NULL': '\x00'
}
VERSIONS = '1.0,1.1'
class Stomp:
def __init__(self, host, sockjs=False, wss=True):
"""
Initialize STOMP communication. This is the high level API that is exposed to clients.
Args:
... |
pulse.py | from functools import partial
from threading import Thread
import wx
from wx.lib import filebrowsebutton
from wx.lib.scrolledpanel import ScrolledPanel
from spacq.interface.pulse.parser import PulseError, PulseSyntaxError
from spacq.interface.pulse.program import Program
from spacq.interface.resources import Resource
... |
GUI_queues_put_get_loop_endless_threaded.py | '''
Created on May 28, 2019
Ch06
@author: Burkhard A. Meier
'''
#======================
# imports
#======================
import tkinter as tk
from tkinter import ttk
from tkinter import scrolledtext
from tkinter import Menu
from tkinter import messagebox as msg
from tkinter import Spinbox
from time impor... |
email.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2016-04-23 11:46:46
# @Author : Bluethon (j5088794@gmail.com)
# @Link : http://github.com/bluethon
from threading import Thread
from flask import current_app, render_template
from flask_mail import Message
from . import mail
def send_async_email(app, ... |
main.py | import torch.multiprocessing as mp
import gym
from agent import Agent
from test_process import test_process
from torch.utils.tensorboard import SummaryWriter
import time
# -----------------------PARAMETERS---------------------------------
HYPERPARAMETERS = {
'learning_rate_actor': 0.007,
'learning_rate... |
test_asyncprocess.py | from datetime import timedelta
import gc
import os
import signal
import sys
import threading
from time import sleep
import weakref
import pytest
from tornado import gen
from tornado.locks import Event
from distributed.metrics import time
from distributed.process import AsyncProcess
from distributed.utils import mp_co... |
tracker.py | """RPC Tracker, tracks and distributes the TVM RPC resources.
This folder implemements the tracker server logic.
Note
----
Tracker is a TCP based rest api with the following protocol:
- Initial handshake to the peer
- RPC_TRACKER_MAGIC
- Normal message: [size(int32), json-data]
- Each message is initiated by the cl... |
test_xmlrpc.py | import base64
import datetime
import decimal
import sys
import time
import unittest
from unittest import mock
import xmlrpc.client as xmlrpclib
import xmlrpc.server
import http.client
import http, http.server
import socket
import threading
import re
import io
import contextlib
from test import support
from test.support... |
utils.py | #!/usr/bin/env python
"""This file contains various utility classes used by GRR."""
from __future__ import print_function
from __future__ import unicode_literals
import array
import base64
import collections
import copy
import csv
import errno
import functools
import getpass
import io
import os
import pipes
import pl... |
core.py | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 17 14:13:39 2018
@author: bella
Foreground core for 21cmmc
"""
import logging
from os import path
import numpy as np
import py21cmmc as p21
from astropy import constants as const
from astropy import units as un
from powerbox import LogNormalPowerBox
from powerbox.dft i... |
decorator_utils.py | #! /usr/bin/env python
# Standard Imports
from threading import Thread
from functools import wraps
import collections
import functools
# irtools Imports
from irtools import *
# logging
log = logging.getLogger('irtools.utils.decorator')
class Memoized(object):
"""
Decorator. Caches a function's return value... |
runner.py | """A simple runner for Python-only models.
Starting instances is out of scope for MUSCLE 3, but is also very
useful for testing and prototyping. So we have a little bit of
support for it in this module.
"""
import multiprocessing as mp
import sys
from typing import Callable, Dict, List, Tuple, cast
from ymmsl import ... |
task2.py | """
Basic thread handling exercise:
Use the Thread class to create and run more than 10 threads which print their name and a random
number they receive as argument. The number of threads must be received from the command line.
e.g. Hello, I'm Thread-96 and I received the number 42
"""
import sys
imp... |
conftest.py | import logging
import os
import sys
from pathlib import Path
from threading import Thread
from time import sleep
from typing import Callable, List, Set, Tuple
import pytest
@pytest.fixture
def tmp_work_path(tmp_path: Path):
"""
Create a temporary working directory.
"""
previous_cwd = Path.cwd()
o... |
app.py | from flask import Flask, request, jsonify, render_template
from flask_cors import CORS
from src.serve import get_model_api
import os
from time import sleep
from multiprocessing import Process
app = Flask(__name__)
CORS(app) # needed for cross-domain requests, allow everything by default
model_api = get_model_api()
#... |
ATMClientCLI.py | # Echo client program
import socket, select, sys, threading
from Tkinter import *
HOST = 'localhost' # The remote host
PORT = 54321 # The same port as used by the server
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST, PORT))
def sending():
while 1:
sock.sendall(raw... |
jaeeun.py | import LED_display as LED
import threading
import time
import numpy as np
import random
#import pygame, pygcurse
#from pygame.locals import *
import copy
import os
import sys
iScreen = [[0 for x in range(32)] for x in range(16)]
#win = pygcurse.PygcurseWindow(32,16, fullscreen=False)
class Card:
coord = None
... |
supervisor.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... |
contentArranger.py | import magic
import re
import pickle
from multiprocessing import Process
import sys
import os
import shutil
import datetime
UserDefinedTypes, DefaultTypes = os.path.expanduser('~/Documents/ContentArranger/UserDefinedTypes'), os.path.expanduser('~/Documents/ContentArranger/DefaultTypes')
class fileOpenError(IOError)... |
dns_server.py | #!/usr/bin/env python2.7
# Copyright 2015 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 la... |
executor.py | import os
import json
import time
import uuid
import signal
import logging
from threading import Thread
from addict import Dict
from six.moves.http_client import HTTPConnection
from .process import Process
from .interface import ExecutorDriver
from .utils import DAY, parse_duration, encode_data, decode_data
logger = l... |
test_io.py | import sys
import gc
import gzip
import os
import threading
import time
import warnings
import io
import re
import pytest
from pathlib import Path
from tempfile import NamedTemporaryFile
from io import BytesIO, StringIO
from datetime import datetime
import locale
from multiprocessing import Process, Value
from ctypes i... |
exact_manager.py | from pathlib import Path
import os
import requests
import json
from requests.auth import HTTPBasicAuth
import time
import datetime
import re
import sys
from functools import partial
import threading
import queue
from tqdm import tqdm
from requests_toolbelt.multipart import encoder
from exact_sync.exact_enums import *
... |
webcam_demo_ava.py | import argparse
import time
from collections import deque
from operator import itemgetter
from threading import Thread
import mmcv
import cv2
import numpy as np
import torch
from mmcv.parallel import collate, scatter
from mmcv.runner import load_checkpoint
from mmaction.apis import init_recognizer
from mmaction.dataset... |
Packet.py | import threading
import struct
import math
import time
import RNS
class Packet:
"""
The Packet class is used to create packet instances that can be sent
over a Reticulum network. Packets to will automatically be encrypted if
they are adressed to a ``RNS.Destination.SINGLE`` destination,
``RNS.Desti... |
test_rdd.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_test.py | # Copyright 2020 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 applicable ... |
test_threading.py | """
Tests for the threading module.
"""
import test.support
from test.support import threading_helper
from test.support import verbose, cpython_only
from test.support.import_helper import import_module
from test.support.script_helper import assert_python_ok, assert_python_failure
import random
import sys
import _thre... |
main.py | import inspect
import logging
import logging.config
import os.path
import threading
import time
from functools import wraps
import yaml
import psutil
class Log:
"""
This class manages all the logging responsibilities of the library.
This class will also be used by the user to decorate their function with ... |
filewatcher.py | #####################################################################
# #
# filewatcher.py #
# #
# Copyright 2013, Monash University ... |
ViberWebhook.py |
from flask import Flask, request, Response
from viberbot import Api
from viberbot.api.bot_configuration import BotConfiguration
from viberbot.api.messages.text_message import TextMessage
from viberbot.api.viber_requests import ViberConversationStartedRequest
from viberbot.api.viber_requests import ViberFailedRequest... |
base.py | import abc
import socket
import weakref
from typing import Tuple
from typing import List
from typing import MutableMapping
from threading import Thread
from threading import Event
from threading import RLock
Addr = Tuple[str, int]
class BaseEchoServer(abc.ABC):
def __init__(self, port: int = 42069):
se... |
loop.py | import asyncio
import threading
class LoopInNewThread:
def __init__(self):
self.loop = self.start_async()
def start_async(self):
loop = asyncio.new_event_loop()
threading.Thread(target=loop.run_forever).start()
return loop
# Submits awaitable to the event loop, but *doesn... |
clientDriver.py | import serial
import platform
import cv2
import time
import online
import offline
import threading
import http.client as httplib
CURRENT_PLATFORM = platform.system()
SERIAL_PORT = ''
camera = cv2.VideoCapture(0)
if (CURRENT_PLATFORM == 'Linux'):
SERIAL_PORT = '/dev/ttyACM0'
elif (CURRENT_PLATFORM == 'Windows')... |
process_pty_test.py | import threading
import unittest
from execution.process_pty import PtyProcessWrapper
from react.observable import read_until_closed
from tests import test_utils
class TestPtyProcessWrapper(unittest.TestCase):
def test_many_unicode_characters(self):
long_unicode_text = ('ΩΨΔ\n' * 100000)
test_util... |
CtpMdApi.py | # -*- coding: utf-8 -*-
import hashlib
import os
import sys
import tempfile
import time
from dHydra.core.Vendor import Vendor
import dHydra.core.util as util
import threading
from ctp.futures import ApiStruct, MdApi
class CtpMdApi(MdApi, Vendor):
def __init__(
self,
account="ctp.json",
in... |
emake.py | #! /usr/bin/env python2
# -*- coding: utf-8 -*-
#======================================================================
#
# emake.py - emake version 3.6.9
#
# history of this file:
# 2009.08.20 skywind create this file
# 2009.11.14 skywind new install() method
# 2009.12.22 skywind implementation execute int... |
advanced_builder.py | # License:
#
# Copyright (c) 2013, Paul Schulze
# 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 condit... |
vision_receiver.py | import socket
import queue
import threading
import logging
from ipaddress import ip_address
import struct
from tracker.observations import DetectionFrame, BallObservation, RobotObservation
from tracker.proto.messages_robocup_ssl_wrapper_pb2 import SSL_WrapperPacket
class VisionReceiver:
def __init__(self, serv... |
pyshell.py | #! /usr/bin/env python3
import sys
if __name__ == "__main__":
sys.modules['idlelib.pyshell'] = sys.modules['__main__']
try:
from tkinter import *
except ImportError:
print("** IDLE can't import Tkinter.\n"
"Your Python may not be configured for Tk. **", file=sys.__stderr__)
raise ... |
installwizard.py | # Copyright (C) 2018 The Electrum developers
# Distributed under the MIT software license, see the accompanying
# file LICENCE or http://www.opensource.org/licenses/mit-license.php
import os
import json
import sys
import threading
import traceback
from typing import Tuple, List, Callable, NamedTuple, Optional, TYPE_CH... |
util.py | import asyncio
import atexit
from threading import Thread
from typing import Optional, Union
from annotypes import Anno, Array
from tornado.ioloop import IOLoop
from malcolm.core import Table
class IOLoopHelper:
_loop: Optional[IOLoop] = None
_thread: Optional[Thread] = None
@classmethod
def loop(c... |
etherscan_py.py | import requests
import copy
from threading import Thread, Lock
import itertools
class EtherscanEvent:
def __init__(self, event):
self.address = event['address']
self.topics = event['topics']
self.data = event['data']
self.block_height = int(event['blockNumber'], 16)
self.tim... |
receivers.py | import datetime
import os
from django.db.models import Q
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from pygal import Pie, StackedLine
from pygal.style import CleanStyle as pygal_CleanStyle
from CW_Portal import access_cache, settings
from studentportal.models imp... |
server.py | # -*- coding: utf-8 -*-
import base64
import threading
import tornado.ioloop
import tornado.web
import tornado.websocket
from tornado import httpserver
from ..config import config as cfg
from ..device.client import InstrumentManager
from ..device.protocol import DEFAULT_PORT, Transport
from .handlers impo... |
spinner.py | import sys
import time
import threading
class Spinner:
"""https://www.codenong.com/4995733/
with Spinner():
sleep(10)
"""
busy = False
delay = 0.3
@staticmethod
def spinning_cursor():
while 1:
for cursor in "|/-\\":
yield cursor
def __ini... |
views.py | import datetime
import logging
import os
import re
import smtplib
import sys
import tempfile
import threading
import time
import traceback
import xml.sax
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from time import sleep
from validate_email import validate_email
import numpy as n... |
vnokcoin.py | # encoding: UTF-8
import hashlib
import zlib
import json
from time import sleep
from threading import Thread
import websocket
# OKCOIN网站
OKCOIN_CNY = 'wss://real.okcoin.cn:10440/websocket/okcoinapi'
OKCOIN_USD = 'wss://real.okcoin.com:10440/websocket/okcoinapi'
# 账户货币代码
CURRENCY_CNY = 'cny'
CURRENCY_USD = 'usd... |
_tests.py | # 测试新建任务,分发任务,查询任务状态
import bilibili_meter.routes as routes
import time,random
import orm
task = routes.task
def test_set_tasks():
task.set_task('test_type1','param1',1800,30)
task.set_task('test_type2','param2',1800,30)
task.set_task('test_type3','param3',1800,30)
task.set_task('test_type4','param4',1... |
cld_migrate_thread.py | import threading
from cloud_accounts import cld_get, cld_add, cld_keys, cld_compare
def migrate(tenant_sessions: list, logger: object):
'''
Accepts a list of tenant session objects.
Migrates all cloud accounts from the first tenant, (source tenant)
to all other tenants (clone tenants).
'''
#... |
heartbeat.py | import socket
import logging
import threading
from typing import Callable
import amqp
logger = logging.getLogger(__name__)
class Heartbeat:
def __init__(self, connection: amqp.Connection, on_error: Callable[[Exception], None]) -> None:
self._connection = connection
self._on_error = on_error
... |
main.py | # KidsCanCode - Game Development with Pygame video series
# Jumpy! (a platform game) - Part 4
# Video link: https://youtu.be/G8pYfkIajE8
# Jumping
import pygame as pg
import random
from settings import *
from game_objects import *
import numpy as np
import cv2
import pipeline
import itertools
from threading import Thr... |
asyncio.py | # flake8: noqa
# Copyright 2019 Confluent Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
server.py | import socket
import threading
PORT = 7000
HOST = '127.0.0.1'
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.bind((HOST, PORT))
except socket.error as e:
print(str(e))
print("........")
sock.listen(5)
clients = []
names = []
def send_mess(message):
for client in clients:
cli... |
ParallelScraper.py | import newspaper
import csv
import pandas as pd
import re
import os
import time
import pdb
from multiprocessing import Pool, Process, Lock, Queue
CREDIBLE = './credible.csv'
NONCREDIBLE = './noncredible.csv'
OUTPUT = './new_articles_threading.csv'
class ParallelScraper:
def __init__(self, credible=CREDIBLE, nonc... |
async_dataloader.py | from queue import Queue
from threading import Thread
import torch
from torch.utils.data import DataLoader
from torch.utils.data import Dataset
class AsynchronousLoader(object):
"""
Class for asynchronously loading from CPU memory to device memory with DataLoader.
Note that this only works for single GPU... |
proxier.py | import atexit
from concurrent import futures
from dataclasses import dataclass
import grpc
import logging
from itertools import chain
import json
import os
import socket
import sys
from threading import Lock, Thread, RLock
import time
import traceback
from typing import Any, Callable, Dict, List, Optional, Tuple
impor... |
tests.py | import os
import signal
import sys
import threading
import time
from unittest import skipIf, skipUnless
from django.db import (
DatabaseError, Error, IntegrityError, OperationalError, connection,
transaction,
)
from django.test import (
TransactionTestCase, skipIfDBFeature, skipUnlessDBFeature,
)
from .mo... |
test_pantsd_integration.py | # coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
import datetime
import itertools
import os
import re
import signal
import sys
import thre... |
createdbs.py | import logging
from threading import Thread
from typing import List
from tornado.options import options as opts
from connman import ReDBConnection
from constants import re as re
from rethinkdb_tools import db_classes
import rethinkdb
from xenadapter.xenobject import XenObject
from xenadapter import * # for metacla... |
application.py |
import json
import logging
import multiprocessing
import os
import socket
import sys
import bokeh
import distributed.bokeh
from ..utils import ignoring
dirname = os.path.dirname(distributed.__file__)
paths = [os.path.join(dirname, 'bokeh', name)
for name in ['status', 'tasks']]
binname = 'bokeh.exe' if sys... |
test_client.py | # test_client.py -- Compatibilty tests for git client.
# Copyright (C) 2010 Google, Inc.
#
# Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
# General Public License as public by the Free Software Foundation; version 2.0
# or (at your option) any later version. You can redistribute it and/or
... |
test_utility.py | import threading
import pytest
from base.client_base import TestcaseBase
from base.utility_wrapper import ApiUtilityWrapper
from utils.util_log import test_log as log
from common import common_func as cf
from common import common_type as ct
from common.common_type import CaseLabel, CheckTasks
prefix = "utility"
defau... |
test_tee.py | from __future__ import unicode_literals
import atexit
import errno
import multiprocessing
import io
import os
import re
import select
import sys
import ctypes
import traceback
import signal
import tempfile
import subprocess
import threading
import queue
from threading import Thread
from contextlib import contextmanage... |
bot.py | # -*- coding: utf-8 -*-
# AIOGRAM
import aiogram.utils.markdown as md
from aiogram import Bot, Dispatcher, types, filters
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters import Text
from aiogram.utils.exceptions import Throttled
fro... |
download_kegg_various_databases.py | import sys, re, os
from urllib.request import urlopen
from threading import Thread
import queue
import json
from threading import Semaphore
writeLock = Semaphore(value=1)
database = sys.argv[1]
output_folder = sys.argv[2]
rx_prefix_catch = re.compile(r'(\w+):\w+')
ko_list_url = "http://rest.kegg.jp/list/" + databa... |
utils.py | # Copyright 2012-2019 CERN for the benefit of the ATLAS collaboration.
#
# 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... |
pattern_executor.py | # ===============================================================================
# Copyright 2012 Jake Ross
#
# 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/licens... |
labels.py | import hashlib
import requests
import threading
import json
import sys
import traceback
import base64
import electrum_vtc
from electrum_vtc.plugins import BasePlugin, hook
from electrum_vtc.i18n import _
class LabelsPlugin(BasePlugin):
def __init__(self, parent, config, name):
BasePlugin.__init__(self,... |
joinable_queue.py | from cloudbutton.multiprocessing import Process, JoinableQueue
def worker(q):
working = True
while working:
x = q.get()
# Do work that may fail
assert x < 10
# Confirm task
q.task_done()
if x == -1:
working = False
if __name__ == '__main__':
... |
GantryController.py | #! /usr/bin/env python
import sys
import argparse
import serial
import threading
import time
import math
''' Interactive testing code:
from GantryController import *
gantry = GantryController()
gantry = GantryController(device='/dev/ttyUSB0', force_calibrate=True)
gantry.write('SPEED 40\r')
#gantry.moveRel(0, 0, 0, ... |
youtube-dl-server.py | from __future__ import unicode_literals
import json
import os
import subprocess
from queue import Queue
from bottle import route, run, Bottle, request, static_file
from threading import Thread
import youtube_dl
from pathlib import Path
from collections import ChainMap
app = Bottle()
app_defaults = {
'YDL_FORMAT'... |
resource_sharer.py | import os
import signal
import socket
import sys
import threading
from . import process
from .context import reduction
from . import util
__all__ = ['stop']
if sys.platform == 'win32':
__all__ += ['DupSocket']
class DupSocket(object):
"""Picklable wrapper for a socket."""
def __init__(self, s... |
datasets.py | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
"""
Dataloaders and dataset utils
"""
import glob
import hashlib
import json
import logging
import os
import random
import shutil
import time
from itertools import repeat
from multiprocessing.pool import ThreadPool, Pool
from pathlib import Path
from threading import Thread
... |
example_demo.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# File: example_demo.py
#
# Part of ‘UNICORN Binance WebSocket API’
# Project website: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api
# Documentation: https://oliver-zehentleitner.github.io/unicorn-binance-websocket-api
# PyPI: https://pypi.org/pro... |
GenerateFlows.py | from P2P_CONSTANTS import *
from Packet import *
from Flow import *
import multiprocessing as MP
import socket
## module to read all the files in the data folder of the
## project, build flow data and store it in a file
def generateFlow(filename):
sem.acquire()
inputfile = open(filename)
data = [line.strip() fo... |
run_adv_train.py | import sys
sys.path.append('..')
import parameters as param
from utils import get_available_gpus
import multiprocessing
from multiprocessing import Pool, Process, Queue, Manager
import os
import tensorflow as tf
def train(gpu_id):
while True:
if not q.empty():
attack_name, dataset, model_n... |
test_sampler.py | import multiprocessing
import random
from typing import Callable
from typing import Dict
from typing import List
from typing import Optional
from typing import Union
from unittest.mock import Mock
from unittest.mock import patch
import warnings
import _pytest.capture
import numpy as np
import pytest
import optuna
fro... |
server_test.py | import time
from multiprocessing import Process
from zero import ZeroServer
from zero.common import get_next_available_port
async def echo(msg: str) -> str:
return msg
def server1():
app = ZeroServer(port=4344)
app.register_rpc(echo)
app.run()
def server2():
app = ZeroServer(port=4345)
ap... |
load.py | import multiprocessing
from time import sleep
import random
import requests
from datetime import datetime
import yaml
import math
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
def make_request(request_url, ssl_verify):
"""Make a request."""
return requests.get(request_url, ... |
test_statestore.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... |
web_profile_test_helpers.py | import time
import threading
from ...extern.six.moves import xmlrpc_client as xmlrpc
from ..hub import WebProfileDialog
from ..hub_proxy import SAMPHubProxy
from ..client import SAMPClient
from ..integrated_client import SAMPIntegratedClient
from ..utils import ServerProxyPool
from ..errors import SAMPClientError, SA... |
fll.py | from pybricks.parameters import Button
from pybricks.tools import wait
from threading import Thread
from time import time
from pybricks.parameters import Stop
from math import pi
class FLL:
def __init__(self, robot):
self.robot = robot
# Δείχνει τον αριθμό του τρέχοντος run
self.current_run ... |
test_threading_local.py | import unittest
from doctest import DocTestSuite
from test import test_support
import threading
import weakref
import gc
class Weak(object):
pass
def target(local, weaklist):
weak = Weak()
local.weak = weak
weaklist.append(weakref.ref(weak))
class ThreadingLocalTest(unittest.TestCase):
def test_... |
get_ibm_asr_results.py | # This is a modified copy of
# https://github.com/watson-developer-cloud/speech-to-text-websockets-python
# (Daniel Bolanos)
# Please follow the top of the original README for the installation
# coding: utf-8
# In[ ]:
"""
#
# Copyright IBM Corp. 2014
#
# Licensed under the Apache License, Version 2.0 (the "License")... |
gnupg.py | """ A wrapper for the 'gpg' command::
Portions of this module are derived from A.M. Kuchling's well-designed
GPG.py, using Richard Jones' updated version 1.3, which can be found
in the pycrypto CVS repository on Sourceforge:
http://pycrypto.cvs.sourceforge.net/viewvc/pycrypto/gpg/GPG.py
This module is *not* forward-... |
thread_util.py | import logging
import threading
import typing as t
from functools import partial, wraps
logger = logging.getLogger(__name__)
F = t.TypeVar("F", bound=t.Callable[..., t.Any])
def wrap_lock(lock: threading.Lock, func: F, max_waiting: int = None) -> F:
if max_waiting is None:
@wraps(func)
def w(*a... |
environment.py | # Adapted from
# https://github.com/pekaalto/sc2aibot/blob/master/common/multienv.py
import os
from multiprocessing import Process, Pipe
from pysc2.env import sc2_env, available_actions_printer
class SingleEnv:
"""Same interface as SubprocVecEnv, but runs only one environment in the
main process.
"""
... |
process_replay.py | #!/usr/bin/env python3
import capnp
import os
import sys
import threading
import importlib
import time
if "CI" in os.environ:
def tqdm(x):
return x
else:
from tqdm import tqdm # type: ignore
from cereal import car, log
from selfdrive.car.car_helpers import get_car
import selfdrive.manager as manager
import ... |
test_idle.py | #!/usr/bin/env python
#
# test_idle.py -
#
# Author: Paul McCarthy <pauldmccarthy@gmail.com>
#
import gc
import time
import threading
import random
from six.moves import reload_module
import pytest
import mock
import fsl.utils.idle as idle
from fsl.utils.platform import platform as fslplatform
def _run_with_wx(fu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.