source stringlengths 3 86 | python stringlengths 75 1.04M |
|---|---|
statsd-agent.py | import statsd
import time
import psutil
import multiprocessing
import socket
import os
import subprocess
import pyudev
STATSD_HOST='10.20.2.108'
PREFIX='%s.' % socket.gethostname()
GRANULARITY = 10 # seconds
PATHS = [('/', 'root'), ('/data', 'data')]
def smart():
c = statsd.StatsClient(STATSD_HOST, 8125, prefix... |
gui.py | """SAMPLE GUI launcher"""
from chromatictools import cli
import multiprocessing
import argparse
import sys
def launch(args):
"""Launch the GUI main loop
Args:
args (Namespace): Command-line arguments namespace"""
from sample.widgets import main, logging # pylint: disable=C0415
import logging as _logging... |
unknowdock.py | #!/usr/bin/env python3
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, GObject, Gdk
import datetime
#import gobject
import threading
import cairo
from config import *
class DockWindow(Gtk.Window):
def __init__(self, left=[], centr=[], right=[]):
Gtk.Window.__init__(self, title="Unknown... |
Scrape.py | from googlesearch import search
from htmldate import find_date
import pandas as pd
import numpy as np
# to search
query = ['Tuskegee,AL', 'West Kentucky Cooperative', 'ACE Power,MS', 'Albertville,AL', 'Benson,NC', 'Benton County,TN', 'Blakely,GA', 'Blue Ridge Mountain,GA', 'Bolivar,TN', 'Caney Fork EC,TN', 'Cleveland ... |
server.py | #!/usr/bin/env python3
import time
import queue
import rpyc
rpyc.core.channel.Channel.COMPRESSION_LEVEL = 0
rpyc.core.stream.SocketStream.MAX_IO_CHUNK = 65355*10
import argparse
from threading import Thread
from multiprocessing import Event
from fid.fid import SyncFID
class FIDService(rpyc.Service):
class FID... |
audio.py |
"""
core/__audio.py
helpful with development of programs
that work with audio
author: @alexzander
"""
# python
import os
import threading
import subprocess
# 3rd party
import pyttsx3 # pip install pyttsx3
# import sounddevice # pip install sounddevice
from gtts import gTTS # p... |
HiwinRA605_socket_ros_test_20190626115244.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... |
GeneSet_EnrichmentServer.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... |
connection.py | # Copyright (c) 2020 DeNA Co., Ltd.
# Licensed under The MIT License [see LICENSE for details]
# https://github.com/DeNA/HandyRL/blob/master/handyrl/connection.py
'''
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to de... |
dnschef.py | #!/usr/bin/env python3
#
# DNSChef is a highly configurable DNS Proxy for Penetration Testers
# and Malware Analysts. Please visit http://thesprawl.org/projects/dnschef/
# for the latest version and documentation. Please forward all issues and
# concerns to iphelix [at] thesprawl.org.
DNSCHEF_VERSION = "0.4"
# Copy... |
example_test.py | # This example code is in the Public Domain (or CC0 licensed, at your option.)
# Unless required by applicable law or agreed to in writing, this
# software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
# CONDITIONS OF ANY KIND, either express or implied.
# -*- coding: utf-8 -*-
from __future__ import pri... |
test_threading.py | import sys
import time
from pathlib import Path
from queue import Queue
from multiprocessing.dummy import Pool
import threading
import asyncio
from examinator import *
log = setup_logging()
log.debug('test')
q = Queue()
num_worker_threads = 4
basepaths = ['..']
def worker():
while True:
item = q.get()
... |
test_operator_gpu.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... |
train.py | """Train models."""
import os
import signal
import torch
import onmt.opts as opts
import onmt.utils.distributed
from onmt.utils.misc import set_random_seed
from onmt.utils.logging import init_logger, logger
#from onmt.train_single import main as single_main
'''single train'''
from programmingalpha.models.... |
cfimport.py | import os
import sys
import threading
import traceback
NLOOPS = 50
NTHREADS = 30
def t1():
try:
from concurrent.futures import ThreadPoolExecutor
except Exception:
traceback.print_exc()
os._exit(1)
def t2():
try:
from concurrent.futures.thread import T... |
main.py | import os
import sys
import time
from datetime import datetime
import pdb
import argparse
import logging
import traceback
from multiprocessing import Process
from queue import Queue
from logging import handlers
from yaml import full_load, dump
from local_runner import LocalRunner
from docker_runner import DockerRunner
... |
threaded.py | import queue, threading, sys
def threaded_reader(project=None, bucket=None, blobs=[], max_threads=4, chunk_size=16*1024*1024):
"""
Speed up reading sets of files - such as multiple days worth
of log-per-day files.
If you care about the order of the records, don't use this.
Each file is i... |
main.py | """Main loop for radio subsystem."""
from shared import config
from shared.controller import Controller
from radio.radio import Radio
from flask import Flask, request, jsonify
from flask_htpasswd import HtPasswdAuth
from flask_cors import CORS
import threading
from shared.streamtologger import StreamToLogger
import lo... |
executor.py | import os, sys
import string, cgi, time, socket, traceback
from subprocess import Popen, PIPE, STDOUT
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from CGIHTTPServer import CGIHTTPRequestHandler
import fcntl
import posix
def CheckXineramaEnabled():
# grep -i \""Xinerama\"" /var/log/Xorg.0.log
... |
ina219_pi.py | #!/usr/bin/python3
from ina219 import INA219
from ina219 import DeviceRangeError
import os
import time
from datetime import datetime
import threading
SHUNT_OHMS = 0.025
MAX_EXPECTED_AMPS = 1.0
ADDRESS = 0x40
class ina219_pi(object):
def __init__(self, address=ADDRESS, shunt_ohms=SHUNT_OHMS,
... |
ice_utils3.py | '''
synbiochem (c) University of Manchester 2015
synbiochem is licensed under the MIT License.
To view a copy of this license, visit <http://opensource.org/licenses/MIT/>.
@author: pablocarbonell / neilswainston / alanwilliams
'''
# pylint: disable=bad-option-value
# pylint: disable=superfluous-parens
# pylint: dis... |
custom.py | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
run.py | import json
import logging
import random
import sys
import deterministic_network
import member_replicated
import client
from statemachine import sequence_generator
import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
import os
class TimeLogger(logging.Logger):
def makeRecord(self, name, lvl... |
models.py | # -*- coding: utf-8 -*-
"""
Data models for the Deis API.
"""
from __future__ import unicode_literals
import etcd
import importlib
import logging
import os
import re
import subprocess
import time
import threading
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.excepti... |
server.py | import socket
import threading
HEADER = 64
PORT = 5050
# for window socket
# SERVER = socket.gethostbyname(socket.gethostname())
SERVER = "YOUR IP ADDRESS"
ADDR = (SERVER, PORT)
FORMAT = "utf-8"
DISCONNECT_MESSAGE = "!DISCONNECT"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
def ha... |
flow.py | import curses
import logging
import socket
import struct
import threading
import time
from scapy import all as scapy
from flowtop.window import WindowManager
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
RENDER_INTERVAL = 1
class Option:
def __init__(self, text):
self.__text = text
d... |
cacheserver.py | import logging
import pathlib
import threading
from http.server import SimpleHTTPRequestHandler
from robotpy_installer.sshcontroller import SshController
logger = logging.getLogger("cacheserver")
class HTTPHandler(SimpleHTTPRequestHandler):
def __init__(self, mapped_files, *args, **kwargs):
self.mapped_... |
process.py | # -*- coding: utf-8 -*-
import ansicolor
from contextlib import contextmanager
from json import JSONDecodeError
import os
import psycopg2
import re
import redis
import requests
import pathlib
import pexpect
import platform
import signal
import socket
import subprocess
import sys
import threading
import time
from typin... |
test_socket.py | import unittest
from test import support
from test.support import socket_helper
import errno
import io
import itertools
import socket
import select
import tempfile
import time
import traceback
import queue
import sys
import os
import platform
import array
import contextlib
from weakref import proxy
import signal
impor... |
main.py |
import time
import threading
from threading import Timer
from threading import Event, Thread
import socket
import sys
import struct
from djitellopy import Tello
import cv2
import signal
import sys
import os, signal, subprocess
import json
from ovb import OpenVibeBuffer
def signal_handler(signal, frame):
g... |
server.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# ClientからOpenCV画像データを受け取り、ライン検出して制御命令を送る
# Server: Jetson TX2
# Client: Jetson TX2/Raspberry Pi3 Docker
# 1. FFMPEG UDP StreamingをClientで実行する。AWS向け10FPS,Jetson TX2向け1FPS
# 2. Serverを起動する
# 3. Clientを起動する
# コード修正
# lib/camera.py: vid = cv2.VideoCapture()を環境に合わせて修正する必要がある
# ... |
listener.py | # -*- coding: utf-8 -*-
# This file is part of the Rocket Web Server
# Copyright (c) 2010 Timothy Farrell
# Import System Modules
import os
import socket
import logging
import traceback
from threading import Thread
try:
import ssl
from ssl import SSLError
has_ssl = True
except ImportError:
has_ssl = ... |
swarmer.py | #!/usr/bin/env python3
'''
Swarm main
Author: Patrick Kelly
Email: patrickyunen@gmail.com
Last revised: March 20, 2020
'''
import sys
import socket
import random
import time
import threading
class Swarm:
def __init__(self, occupied_ports):
self.occupied_ports = occupied_ports
#Start up a server at... |
test_background_thread.py | from yellowdog_client.object_store.utils import BackgroundThreadFactory
from yellowdog_client.object_store.utils import BackgroundThread
class TestBackgroundThreadFactory(object):
def test(self):
res = BackgroundThreadFactory().new_thread(target=TestBackgroundThreadFactory.test)
assert ty... |
batcher.py | #Most of this file is copied form https://github.com/abisee/pointer-generator/blob/master/batcher.py
import Queue
import time
from random import shuffle
from threading import Thread
import numpy as np
import tensorflow as tf
import config
import data
import random
random.seed(1234)
class Example(object):
def _... |
camera_share.py | """
# sudo modprobe bcm2835-v4l2
# python3 controller.py > logs/controller.txt &
# python3 autopilot_web_server.py > logs/autopilot_web_server.txt &
# python3 recorder.py > logs/recorder.txt &
cd training_data;
#python3 -m http.server > ../logs/webserver.txt &
"""
import threading
import time
import sys
from ... |
core.py | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
#... |
test_database_forking.py | import unittest
import multiprocessing
from kgextractiontoolbox.backend.database import Session
from kgextractiontoolbox.backend.models import Tagger
class TestDatabaseForking(unittest.TestCase):
def test_database_forking(self):
def process_run():
s2 = Session.get()
for r in s2.... |
mthread.py | # System modules
from queue import Queue
from threading import Thread
import time
import threading
import random
class AtomicCounter(object):
"""An atomic, thread-safe counter"""
def __init__(self, initial=0):
"""Initialize a new atomic counter to given initial value"""
self._value = initial
... |
SentenceTransformer.py | import json
import logging
import os
import shutil
from collections import OrderedDict
from typing import List, Dict, Tuple, Iterable, Type, Union, Callable
from zipfile import ZipFile
import requests
import numpy as np
from numpy import ndarray
import transformers
import torch
from torch import nn, Tensor, device
from... |
qark.py | '''Copyright 2015 LinkedIn Corp. 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, software
dist... |
pipeline-readonly-replicas.py | from rediscluster import RedisCluster
import threading
from time import sleep
"""
This file will show the difference and how to use the READONLY feature to offload READ specific commands
to replica nodes in your cluster. The script will do two runs with 10 sets of commands each in a threaded environment
both with read... |
SentenceTransformer.py | import json
import logging
import os
import shutil
from collections import OrderedDict
from typing import List, Dict, Tuple, Iterable, Type, Union, Callable
from zipfile import ZipFile
import requests
import numpy as np
from numpy import ndarray
import transformers
import torch
from torch import nn, Tensor, device
from... |
test_ssl.py | import pytest
import threading
import socket as stdlib_socket
import ssl as stdlib_ssl
from contextlib import contextmanager
from functools import partial
from OpenSSL import SSL
import trustme
from async_generator import async_generator, yield_, asynccontextmanager
import trio
from .. import _core
from .._highlevel... |
video_in_odo_out.py | from control.js_linux import Joystick
from control.odometry_control import OdoControl
import threading
import communication.socket_comm as sc
import socket
import cv2
from video.frame_grabber import FrameGrabber
from multiprocessing import Process
import time
def odo_out(odo_port=8000):
# set up the server
s ... |
dimse.py | """
Implementation of the DIMSE service provider.
"""
from io import BytesIO
import logging
import queue
import threading
from typing import TYPE_CHECKING, Tuple, Optional, Dict, Union, cast
from pynetdicom import evt
# pylint: disable=no-name-in-module
from pynetdicom.dimse_messages import (
C_STORE_RQ, C_STORE_R... |
Utils.py | """
Cython -- Things that don't belong
anywhere else in particular
"""
from __future__ import absolute_import
try:
from __builtin__ import basestring
except ImportError:
basestring = str
try:
FileNotFoundError
except NameError:
FileNotFoundError = OSError
import os
import sys
import re
imp... |
monitor.py | #!/usr/bin/env python
import datetime
import dateutil.parser
import http.server
import json
import logging
import os
import threading
import time
import urllib.parse
import pika
import psycopg2
import requests
# parameters to connect to RabbitMQ
rabbitmq_uri = os.getenv('RABBITMQ_URI', 'amqp://guest:guest@localhost/... |
backTCP.py | import os
import socket
import time
import threading
from utils import log
class BTcpConnection:
def __init__(self, mode, addr, port):
# Create a TCP socket
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.conn = None
self.remote_addr = None
if mode == '... |
subprocess42.py | # Copyright 2013 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
"""subprocess42 is the answer to life the universe and everything.
It has the particularity of having a Popen implementation that can yield output... |
p7x4m2.py | ## p7.py - parallel processing microframework
## (c) 2017 by mobarski (at) gmail (dot) com
## licence: MIT
## version: ex4 (simple fan-in of subprocess outputs)
## mod2 (cmd line options)
from __future__ import print_function
# CMD LINE OPTIONS #################################################################... |
transports.py | from .logging import exception_log, debug
from .types import ClientConfig
from .typing import Dict, Any, Optional, IO, Protocol, List, Callable, Tuple
from abc import ABCMeta, abstractmethod
from contextlib import closing
from functools import partial
from queue import Queue
import http
import json
import os
import shu... |
server.py | import socket
import threading
# Trying to select a port that's not usually used
PORT = 5050
SERVER = socket.gethostbyname(socket.gethostname()) # fetch the local ip address of the system
ADDR = (SERVER, PORT) # Address of a system is determined by the ip address and the port number
HEADER = 64 ... |
utils.py | from flask import jsonify
from models.mongo import Document
from bs4 import BeautifulSoup
import bs4
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.ex... |
test_from_thread.py | import sys
import threading
import time
from concurrent.futures import CancelledError
from contextlib import suppress
from contextvars import ContextVar
from typing import Any, AsyncGenerator, Dict, List, NoReturn, Optional
import pytest
from _pytest.logging import LogCaptureFixture
from anyio import (
Event,
... |
booster.py | import time
import multiprocessing
import threading
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
# Import Libraries
# Import song list from videos.txt and push it into ... |
bootstrap_test.py | import os
import random
import re
import shutil
import tempfile
import threading
import time
import logging
import signal
from cassandra import ConsistencyLevel
from cassandra.concurrent import execute_concurrent_with_args
from ccmlib.node import NodeError, TimeoutError, ToolError, Node
import pytest
from distutils.... |
recording_gui.py | import cv2
from cv2 import *
from tkinter import *
from PIL import Image, ImageTk
import io
import threading
import sys
import os
def resize(image):
im = image
new_siz = siz
im.thumbnail(new_siz)
return im
def size(event):
global siz
if siz == screenWH:
siz = (500, 500)
else:
... |
test_syncasync.py | import asyncio
import threading
import time
from concurrent.futures import ThreadPoolExecutor
import pytest
from syncasync import async_to_sync, sync_to_async
@pytest.mark.asyncio
async def test_sync_to_async():
"""
Tests we can call sync functions from an async thread
(even if the number of thread work... |
multi3.py | "Shared memory and globals"
"""
Use multiprocess shared memory objects to communicate.
Passed objects are shared, but globals are not on Windows.
Last test here reflects common use case: distributing work.
"""
import os
from multiprocessing import Process, Value, Array
procs = 3
count = 0 # ... |
crdt_local_client.py | import threading
import tkinter as Tk
from crdt.ops import OpAddRightLocal, OpDeleteLocal, OpUndo, OpRedo
class CRDTLocalClient(object):
def __init__(self, title, op_queue, move_cursor, toggle_connect, start_ops):
self.op_q = op_queue
self.move_cursor = move_cursor
self.toggle_connect = t... |
promise.py |
#
# Promise package for Python 2.7+. Node has such a wonderful way to handle server side. With all of the debates
# on what to do with Python around GIL, I decided to support both GIL via threads and also multicore in the same
# API structure.
#
# Threads version (default) uses GIL and therefore all your data is thr... |
runner.py | #!/usr/bin/env python
import multiprocessing as mp
import sys
import time
# strikers
from aigent.agent_1 import Agent as A1
# defenders
from aigent.agent_2 import Agent as A2
# goalie
from aigent.agent_3 import Agent as A3
def run(team_name: str, number_of_players: int):
# return type of agent: midfield, strik... |
onvifAgent.py | #! /usr/bin/env python3
# -*- coding: UTF-8 -*-
import threading, types
from queue import Queue
from wsdiscovery import WSDiscovery, QName
from onvif import ONVIFCamera, ONVIFError
from urllib.parse import urlparse
ONVIF_TYPE_NVT = QName('http://www.onvif.org/ver10/network/wsdl', 'NetworkVideoTransmitter')
DEF_AUTHS ... |
dataengine_configure.py | #!/usr/bin/python
# *****************************************************************************
#
# Copyright (c) 2016, EPAM SYSTEMS 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
#
#... |
feature_shutdown.py | #!/usr/bin/env python3
# Copyright (c) 2018-2020 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test bitcoind shutdown."""
from test_framework.test_framework import BitcoinTestFramework
from test_fr... |
main_05_Conv3D.py | import Redes.Red_Conv3D as Interface
import Auxiliary.preprocessingData as Data
import Auxiliary.GPUtil as GPU
import os
from threading import Thread
import pickle
import numpy as np
import tensorflow as tf
###################################
os.environ["CUDA_VISIBLE_DEVICES"] = "0, 1, 2, 3" # To force tensorflow ... |
video.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2020 by Murray Altheim. All rights reserved. This file is part of
# the Robot Operating System project and is released under the "Apache Licence,
# Version 2.0". Please see the LICENSE file included as part of this package.
#
# author: Murray Altheim
# crea... |
main.py | import os
import sys
import json
import importlib
import threading
from logger.logger import set_size_based_rotating_log
set_size_based_rotating_log()
import logging
from fastapi import FastAPI
from database.db import Base, engine
from config.config import DEFAULT_USER_SCOPES
from flags import get_flags
flags = ge... |
dev.py | #!/usr/bin/env python3
"""
Execute the app & restart it when there are source file changes.
This is totally overbuilt. Deal with it.
"""
import sys
import threading
import time
from pathlib import Path
import docker
from dotenv import dotenv_values
from pyrate_limiter import BucketFullException, Duration, Limiter, Re... |
monte_carlo_posterior_parallel.py | # Parallel posterior computations for the binomial model.
import numpy as np
import multiprocessing as mp
from numba import jit, prange
from time import time
def mc_multi(chunk_len, parameters, delta_out):
"""
Inner function for multiprocessing call.
Draws from a beta posterior.
"""
delta = np.... |
QueueAsyncDriver.py | import threading
from masonite.contracts.QueueContract import QueueContract
from masonite.drivers.BaseDriver import BaseDriver
class QueueAsyncDriver(QueueContract, BaseDriver):
"""
Queue Aysnc Driver
"""
def __init__(self, Container):
self.container = Container
def push(self, *objects):... |
host.py | # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# Copyright (c) 2010 Citrix Systems, Inc.
# Copyright (c) 2011 Piston Cloud Computing, Inc
# Copyright (c) 2012 University Of Minho
# (c) Copyright 2013 Hewlett-Pa... |
env.py | # Microsoft Azure Linux Agent
#
# Copyright 2018 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... |
main.py | import json
import random
import re
import string
import sys
import threading
from datetime import datetime, timedelta
from .google_maps.info import GoogleMaps
from .ifoodie.ifoodie import Ifoodie
sys.path.append(".")
import config
import MongoDB.operation as database
class RestaurantInfo:
def __init__(
... |
MessageQueue.py | # -*- coding: utf-8 -*-
"""
pip_services3_messaging.queues.MessageQeueue
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Abstract message queue implementation.
:copyright: Conceptual Vision Consulting LLC 2018-2019, see AUTHORS for more details.
:license: MIT, see LICENSE for more details.
"""
... |
thermos_observer.py | #
# 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, software
# distributed under ... |
util.py | import logging
import os
import threading
import time
from datetime import datetime
from pathlib import Path
import psutil
import config
# import plot_metrics #TODO edit here
def GetCpuUsage(p: psutil.Process):
return p.cpu_percent(interval=0.1)/psutil.cpu_count()
def GetMemUsage(p: psutil.Process):
return p... |
mockserver.py | import http.server
from contextlib import contextmanager
import threading
import random
def is_port_in_use(port):
import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
return s.connect_ex(('localhost', port)) == 0
def any_free_port():
port = random.randint(4001, 7999)
w... |
skeletonAppiumRealTSC.py | ###################################################################
# Skeleton for Appium tests on Sauce Labs RDC
####################################################################
###################################################################
# Imports that are good to use
####################################... |
oes_td.py | import time
from copy import copy
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from gettext import gettext as _
from threading import Lock, Thread
# noinspection PyUnresolvedReferences
from typing import Any, Callable, Dict
from vnpy.api.oes.vnoes import OesApiClientEnvT, OesApi... |
presupuesto.py | # -*- coding: utf-8 -*-
# @Author: Manuel Rodriguez <valle>
# @Date: 28-Aug-2017
# @Email: valle.mrv@gmail.com
# @Filename: views.py
# @Last modified by: valle
# @Last modified time: 16-Jan-2018
# @License: Apache license vesion 2.0
from django.forms.models import model_to_dict
from django.db.models import Q
fro... |
server.py | import os
import socket,random,time
import colorama
from platform import system
from threading import Thread
from modules.ConnectionsHandler import Handler
class Server:
def __init__(self):
if system() == 'Windows':
colorama.init(convert=True)
self.CLEAR = 'cls'
els... |
Hiwin_RT605_ArmCommand_Socket_20190627161038.py | #!/usr/bin/env python3
# license removed for brevity
import rospy
import os
import numpy as np
from std_msgs.msg import String
from ROS_Socket.srv import *
from ROS_Socket.msg import *
import math
import enum
pos_feedback_times = 0
mode_feedback_times = 0
msg_feedback = 1
#接收策略端命令 用Socket傳輸至控制端電腦
import socket
##多執行序
i... |
context_and_start_methods_02_fork_03.py | import multiprocessing as mp
import os
def processes_info() -> None:
print(f'\nprocess id \t\t-> {os.getpid()}')
print(f'\nparent process id \t-> {os.getppid()}')
def target_function() -> None:
processes_info()
if __name__ == '__main__':
# should not be used more than once in the program.
context = mp.get... |
ReceiveDictTcp.py | import socket
import threading
import json
from Queue import Queue
import sys
class ReceiveDictTcp(object):
def __init__(self, host, port, verbose=False):
self.host = host
self.port = port
self.verbose = verbose
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s... |
moxi.py | import logger
import time
from threading import Thread
import unittest
import random
import exceptions
import socket
from TestInput import TestInputSingleton
from membase.api.rest_client import RestConnection
from membase.helper.bucket_helper import BucketOperationHelper
from membase.helper.cluster_helper import Clust... |
commands.py | # coding: utf-8
#
# commands.py
# Part of SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ryan Hileman and Aparajita Fishman
#
# Project: https://github.com/SublimeLinter/SublimeLinter3
# License: MIT
#
"""This module implements the Sublime Text commands provided by SublimeLinter."""
impor... |
websocket_client.py | # cbpro/WebsocketClient.py
# original author: Daniel Paquin
# mongo "support" added by Drew Rice
#
#
# Template object to receive messages from the Coinbase Websocket Feed
from __future__ import print_function
import json
import base64
import hmac
import hashlib
import time
from threading import Thread
from websocket ... |
cli.py | # -*- coding: utf-8 -*-
from __future__ import print_function
import click
import copy
from functools import wraps
import glob
import io
import json
import logging
import netrc
import os
import random
import re
import requests
import shlex
import signal
import socket
import stat
import subprocess
import sys
import tex... |
corenlp.py | """
Wrapper around the CoreNLP parser
The module expects CORENLP_HOME to point to the CoreNLP installation dir.
If run with all annotators, it requires around 3G of memory,
and it will keep the process in memory indefinitely.
See: http://nlp.stanford.edu/software/corenlp.shtml#Download
Tested with
http://nlp.stanford.e... |
test_element.py | """
This module tests element_agent.py
"""
import numpy as np
import sys
# Check the version of Python
is_py2 = sys.version[0] == '2'
if is_py2:
import Queue as queue
else:
import queue as queue
import threading
import unittest
# agent and stream and helper_control are in ../core
from IoTPy.core.agent import... |
sss.py | from inputs import get_gamepad
import time
import threading
#import serial
#from pyserial import Serial
#rom numpy import interp
#def rangeMap(num):
# return int(interp(num,[-32768,32768],[0,255]))
#global ser
#ser = serial.Serial('/dev/ttyACM0', 9600)
#ser = serial.Serial('COM17', 9600)
def readGP()... |
main.py | import cv2
import numpy as np
import tcp_streamer
import threading
image = np.zeros((100, 100, 4), dtype=np.uint8)
actorinfo = ""
def img_thread():
streamer = tcp_streamer.TCPStreamer()
server_address = ('localhost', 8999)
streamer.listen(server_address)
while True:
message = streamer.recv... |
jenkinspoll.py | import time
import requests
import os
import jenkins
import threading
import signal
import atexit
jenkins_server = None
threading_event = None
jenkins_jobs_run = []
def main():
global threading_event
initialize_jenkins()
threading_event = threading.Event()
jenkins_poll = threading.Thread(target=get_cu... |
base_cache_test.py | """Common tests to run for all backends (BaseCache subclasses)"""
import json
from datetime import datetime
from io import BytesIO
from threading import Thread
from time import sleep, time
from typing import Dict, Type
from unittest.mock import MagicMock, patch
from urllib.parse import parse_qs, urlparse
import pytest... |
webchat_robot.py | # -*- coding: utf-8 -*-
import codecs
import http.client
import http.cookiejar
import json
import logging
import logging.handlers
import multiprocessing
import os
import random
import re
import subprocess
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import xml.dom.minidom
from co... |
main.py | import argparse
import numpy as np
import sounddevice as sd
import soundfile as sf
from utils.audio_loop import AudioLoop
from lib.btrack import BeatTracker # pylint: disable=import-error,no-name-in-module
import librosa
import pickle
import time
from utils.circular_buffer import CircularBuffer
from lib.rubberband imp... |
network_listener.py | from tqdm import tqdm
import csv
from serial import Serial
import threading
import time
from .listener import Listener
class SerialListener(Listener):
filename = ''
ser = None
sample_size = 0
captured = 0
pbar = None
is_stopped = False
def __init__(self, i: int, filename: str, ser: Serial... |
test_request.py | import asyncio
import threading
from urllib import request
from ddtrace import config
from ddtrace.contrib.aiohttp.middlewares import trace_app
from ddtrace.contrib.aiohttp.patch import patch
from ddtrace.contrib.aiohttp.patch import unpatch
from tests.utils import assert_is_measured
from tests.utils import override_g... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.