source stringlengths 3 86 | python stringlengths 75 1.04M |
|---|---|
my_chatbot (1).py | from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
from tkinter import *
import pyttsx3 as pp
import speech_recognition as s
import threading
engine = pp.init()
voices = engine.getProperty('voices')
print(voices)
engine.setProperty('voice', voices[0].id)
def speak(word):
... |
server.py | import datetime, mysql.connector, config, os, requests, json, telepot, ast, utils, datetime, uuid, requests, io, base64, asyncio, traceback
from PIL import Image
from telepot.namedtuple import InlineKeyboardMarkup, InlineKeyboardButton
from telepot.loop import MessageLoop
from flask import Flask, render_template, r... |
test_state.py | # -*- coding: utf-8 -*-
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import shutil
import tempfile
import textwrap
import threading
import time
# Import Salt Testing libs
from tests.support.case import ModuleCase
from tests.support.helpers import with_tempdir... |
shortcuts.py | import base64
import logging
import json
import operator
import requests
import time
import multiprocessing
import typing
import numpy as np
from astropy.io import fits
from cloud_fits.auth import aws as aws_auth
from cloud_fits.data_types import utils
from datetime import datetime
logger = logging.getLogger(__nam... |
delete.py | from telegram.ext import CommandHandler
import threading
from telegram import Update
from bot import dispatcher, LOGGER
from bot.helper.telegram_helper.message_utils import auto_delete_message, sendMessage
from bot.helper.telegram_helper.filters import CustomFilters
from bot.helper.telegram_helper.bot_commands import B... |
jd_openCard.py | #!/bin/env python3
# -*- coding: utf-8 -*
'''
项目名称: JD_OpenCard
Author: Curtin
功能:JD入会开卡领取京豆
CreateDate: 2021/5/4 下午1:47
UpdateTime: 2021/6/19
建议cron:
cron "2 8,15 * * *" jd_OpenCard.py, tag=开卡有礼, enabled=true
new Env('开卡有礼');
'''
version = 'v1.2.2'
readmes = """
# JD入会领豆小程序
## 使用方法
#### [手机用户(参考) https://mp.weixin.q... |
downloader.py | from selenium.common.exceptions import (
TimeoutException,
ElementNotInteractableException,
ElementClickInterceptedException,
NoSuchElementException,
)
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdr... |
trezor.py | import traceback
import sys
from typing import NamedTuple, Any, Optional, Dict, Union, List, Tuple, TYPE_CHECKING
from electrum_bynd.util import bfh, bh2u, versiontuple, UserCancelled, UserFacingException
from electrum_bynd.bip32 import BIP32Node, convert_bip32_path_to_list_of_uint32 as parse_path
from electrum_bynd i... |
MouseJitter.py | import Tkinter
import threading
import time
import random
import sys
import ctypes
from functools import partial
class MouseJitter(object):
MOUSEEVENTF_MOVE = 0x0001 # mouse move
MOUSEEVENTF_LEFTDOWN = 0x0002 # left button down
MOUSEEVENTF_LEFTUP = 0x0004 # left button up
MOUSEEVENTF_RIGHTDOWN = 0x0008... |
session_test.py | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
hogwild_trainer.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from typing import Any, Tuple
import torch
import torch.multiprocessing as mp
from pytext.common.constants import Stage
from pytext.config import PyTextConfig
from pytext.config.pytext_config import ConfigBase
from pytext.met... |
public2.py | # -*- coding: utf-8 -*-
import PEPEN
from PEPEN.lib.curve.ttypes import *
from datetime import datetime
import time, random, sys, ast, re, os, io, json, subprocess, threading, string, codecs, requests, ctypes, urllib, urllib2, urllib3, wikipedia, tempfile
from bs4 import BeautifulSoup
from urllib import urlopen
import... |
gera_vector.py | import random
import multiprocessing
def gera_vector(int_range, count, return_dict=None, cpu_id=None):
vector = []
if return_dict != None:
return_dict[cpu_id] = [random.randint(int_range[0], int_range[1]) for x in range(count)]
else:
vector = [random.randint(int_range[0], int_range[1]) for ... |
eval_cd_nc_f1_ecd_ef1.py | import numpy as np
import os
import h5py
from multiprocessing import Process, Queue
import queue
import time
import trimesh
from sklearn.neighbors import KDTree
sample_num = 100000
pred_dir = "samples/"
gt_dir = "../../objs/"
f1_threshold = 0.003
ef1_radius = 0.004
ef1_dotproduct_threshold = 0.2
ef1_threshold = 0.005... |
zeromq_test.py | # -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Thomas Jackson <jacksontj.89@gmail.com>`
'''
# Import python libs
from __future__ import absolute_import
import os
import time
import threading
import platform
import zmq.eventloop.ioloop
# support pyzmq 13.0.x, TODO: remove once we force people to 14.0.x
if not ha... |
backtester_tickm.py | import os
import sys
import sqlite3
import pandas as pd
from matplotlib import pyplot as plt
from multiprocessing import Process, Queue
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
from utility.setting import db_tick, db_stg, db_backtest
from utility.static import now, timedelta_sec, str... |
main_ui.py | import eel
import json
import cv2
import base64
import numpy as np
from PIL import Image as PILlib
import io
import re
import sys, os
from threading import Thread
class Images:
@staticmethod
def read(im_path):
return cv2.imread(im_path)
@staticmethod
def unpack_im(pack, image_type):
... |
test_bootstrap.py | """Test the bootstrapping."""
# pylint: disable=too-many-public-methods,protected-access
import tempfile
from unittest import mock
import threading
import voluptuous as vol
from homeassistant import bootstrap, loader
import homeassistant.util.dt as dt_util
from homeassistant.helpers.config_validation import PLATFORM_... |
peinjector_interceptor.py | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Interceptor - reference implementation of a Interceptor based on libmproxy with a connection to a peinjector-server
"""
__author__ = 'W.L.'
from threading import Thread
from libmproxy import controller, proxy
from libmproxy.proxy.server import ProxyServer
from ... |
line_detector_node.py | #!/usr/bin/env python
from anti_instagram.AntiInstagram import *
from cv_bridge import CvBridge, CvBridgeError
from duckietown_msgs.msg import (AntiInstagramTransform, BoolStamped, Segment,
SegmentList, Vector2D)
from duckietown_utils.instantiate_utils import instantiate
from duckietown_utils.jpg import image_cv_fr... |
test_connections.py | import logging
import pytest
import mock
import random
import threading
from milvus import Milvus
from mishards.connections import (
ConnectionTopology,
ConnectionGroup
)
from mishards.topology import StatusType
from mishards import exceptions
logger = logging.getLogger(__name__)
@pytest.mark.usefixtures('a... |
test_end2end.py | """End to end tests for Selenium Wire."""
import json
import os
import shutil
import threading
from pathlib import Path
from unittest.mock import patch
import pytest
from selenium.common.exceptions import TimeoutException
import seleniumwire
from seleniumwire import webdriver
from seleniumwire.thirdparty.mitmproxy.e... |
services.py | import datetime
import logging
import random
import threading
import requests
from time import sleep
import json
from smshandling.models import SMS
from smshandling.smsService import SmsService
class ApiPublisher:
def __init__(self, API_URL: str, API_ID: str, API_KEY: str, smsService: SmsService, logger):
... |
run_k_truss_karypis.py | import socket
from exec_utilities import time_out_util
from config import *
from exec_utilities.exec_utils import *
from multiprocessing import Process
def run_exp(env_tag=knl_tag, with_c_group=True, data_path_tag=karypis_k_truss_exec_path_tag):
hostname = socket.gethostname()
with open('config.json') as if... |
test_writer.py | import os
import socket
import tempfile
import threading
import time
import mock
import msgpack
import pytest
from ddtrace.compat import PY3
from ddtrace.compat import get_connection_response
from ddtrace.compat import httplib
from ddtrace.constants import KEEP_SPANS_RATE_KEY
from ddtrace.internal.uds import UDSHTTPC... |
sensor.py | #!/usr/bin/env python3
# pylint: bad-whitespace
import argparse
import asyncio
import datetime
import io
import json
import logging
import os
import platform
from queue import Queue, Empty, Full
import signal
import subprocess
import socket
import sys
from threading import Thread
import time
import uuid
import Adafru... |
worker.py | import logging, os, sys, time, requests, json
from datetime import datetime
from multiprocessing import Process, Queue
from urllib.parse import urlparse
import pandas as pd
import sqlalchemy as s
from sqlalchemy import MetaData
from sqlalchemy.ext.automap import automap_base
from workers.standard_methods import registe... |
safe_t.py | from binascii import hexlify, unhexlify
import traceback
import sys
from typing import NamedTuple, Any, Optional, Dict, Union, List, Tuple, TYPE_CHECKING
from electrum_spero.util import bfh, bh2u, versiontuple, UserCancelled, UserFacingException
from electrum_spero.bip32 import BIP32Node
from electrum_spero import con... |
topology_test.py | import re
import time
import pytest
import logging
from threading import Thread
from cassandra import ConsistencyLevel
from ccmlib.node import TimeoutError, ToolError
from dtest import Tester, create_ks, create_cf
from tools.assertions import assert_almost_equal, assert_all, assert_none
from tools.data import insert... |
bridge.py | #!/usr/bin/env python3
import argparse
import math
import os
import signal
import threading
import time
from multiprocessing import Process, Queue
from typing import Any
import carla # pylint: disable=import-error
import numpy as np
import pyopencl as cl
import pyopencl.array as cl_array
import cereal.messaging as m... |
threading_daemon.py | import logging
import threading
import time
logging.basicConfig(level=logging.DEBUG, format='(%(threadName)-10s) %(message)s')
logger = logging.getLogger(__name__)
def some_func(delay, repeat):
logger.debug('started')
for _ in range(repeat):
time.sleep(delay)
logger.debug(time.ctime())
lo... |
plotting.py | """
pyvista plotting module
"""
import collections
import logging
import os
import time
from threading import Thread
import imageio
import numpy as np
import scooby
import vtk
from vtk.util import numpy_support as VN
import pyvista
from pyvista.utilities import (convert_array, get_scalar, is_pyvista_obj,
... |
test.py | import logging
import random
import threading
import time
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... |
manager.py | # -*- coding: utf-8 -*-
"""
:copyright: (C) 2010-2013 by Contrail Consortium.
"""
from threading import Thread
from conpaas.core.expose import expose
from conpaas.core.manager import BaseManager
from conpaas.core.https.server import HttpJsonResponse, HttpErrorResponse
from conpaas.services.htcondor.agent impor... |
infeed_test.py | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
eftepede_daemon.py | #! /usr/bin/python
import os
import sys
import eftepede_server
import threading
if os.fork() == 0:
os.setsid()
sys.stdout = open("/dev/null","w")
sys.stdin = open("/dev/null","r")
threading.Thread( target = eftepede_server.main ).start()
# that was easy, right?
|
tf_util.py | import numpy as np
import tensorflow as tf # pylint: ignore-module
import copy
def switch(condition, then_expression, else_expression):
"""Switches between two operations depending on a scalar value (int or bool).
Note that both `then_expression` and `else_expression`
should be symbolic tensors of the *sa... |
__main__.py | # -*- coding: utf-8 -*-
#
# king_phisher/server/__main__.py
#
# 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 condition... |
arp_spoof.py | """
Based on ARP packets received, sends out spoofed ARP packets.
"""
import scapy.all as sc
import threading
import time
from host_state import HostState
import utils
# Min seconds between successive spoofed packets
MIN_ARP_SPOOF_INTERVAL = 0.01
class ArpSpoof(object):
def __init__(self, host_state):
... |
event_objects_02.py | import threading
TIMEOUT_EVENT: float = 4
event = threading.Event()
def target_wait_for_event() -> None:
print(f'\n{threading.current_thread().name} -> waiting for the event')
print('\nevent.is_set(): ', event.is_set())
event.wait(timeout=TIMEOUT_EVENT)
print(f'\n{threading.current_thread().name} -> event oc... |
pmap.py | # Copyright 2017-2020 typed_python Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
core.py | import abc
import logging
import threading
from queue import Empty, Full
from typing import Any, Callable, Generic, List, NamedTuple, Optional, Tuple, TypeVar, Union
logger = logging.getLogger(__name__)
Empty = Empty
Full = Full
QItem = TypeVar("QItem")
class Queue(abc.ABC, Generic[QItem]):
@property
def n... |
latrd_pcap_dump_packet.py | """
LATRDProducer - load LATRD packets from packet capture file and send via UDP.
Tim Nicholls, STFC Application Engineering Group.
"""
import struct
import logging
import argparse
import os
import socket
import time
import random
import dpkt
import threading
class LATRDPacket(object):
IDLE_PACKET_MASK = ... |
wallet_multiwallet.py | #!/usr/bin/env python3
# Copyright (c) 2017-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 multiwallet.
Verify that a bitcoind node can load multiple wallet files
"""
from decimal import D... |
testOne.py | import threading
def hello_world():
print("hello world")
def function1():
for x in range(10):
print('One')
def function2():
for x in range(10):
print('Two')
t1 = threading.Thread(target=function1)
t2 = threading.Thread(target=function2)
t2.start()
t2.join()
t1.start()
|
leds.py | """Blinky things
Classes to control the LEDs on the chessboard
"""
# Uses rpi_ws281x-python
# Example code at
# https://github.com/rpi-ws281x/rpi-ws281x-python/blob/master/examples/strandtest.py
from time import sleep
import rpi_ws281x as neopixel
from rpi_ws281x import Color
from threading import Thread
colors = {'... |
publisher.py | '''
* publisher
*
* Copyright (c) 2020-2021, Magik-Eye Inc.
* author: Jigar Patel, jigar@magik-eye.com
'''
import rospy
from sensor_msgs.msg import PointCloud2, PointField
import threading
import time
import pymkeapi
import numpy as np
from pymkeros.device_info import DeviceInfo
# ====================================... |
test_flight.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... |
test_channel.py | #!/usr/bin/python
#
# Server that will accept connections from a Vim channel.
# Used by test_channel.vim.
#
# This requires Python 2.6 or later.
from __future__ import print_function
import json
import socket
import sys
import time
import threading
try:
# Python 3
import socketserver
except ImportError:
#... |
status.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author:rachpt
from random import random
from threading import Thread
from functools import partial
from datetime import date, timedelta
from time import sleep, strftime, localtime
from tkinter import (
StringVar,
E,
W,
Label,
Button,
Radiobutton,... |
daq_client.py | """Module to send gRPC requests to DAQ and manage test sessions"""
from __future__ import absolute_import
import grpc
import threading
import traceback
from device_coupler.utils import get_logger
from device_coupler.ovs_helper import OvsHelper
from daq.proto.session_server_pb2 import SessionParams, SessionResult
fr... |
sensor.py | """
Use serial protocol of EMU2 meter to obtain state of the connected meter.
For more details about this component, please refer to the documentation
at https://github.com/jrhorrisberger/home-assistant/blob/master/custom_components/rainforest/readme.md
"""
from homeassistant.helpers.entity import Entity
import homeas... |
contextutil.py | # coding=utf-8
# Copyright 2014 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 logging
import os
import shutil
import signal
import sys
import tempfile
import th... |
index.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2013 Vinay Sajip.
# Licensed to the Python Software Foundation under a contributor agreement.
# See LICENSE.txt and CONTRIBUTORS.txt.
#
import hashlib
import logging
import os
import shutil
import subprocess
import tempfile
try:
from threading import Thread
except ImportErr... |
transfer_function.py | import numpy as np
import trans_vp
from scipy.special import jv,jn_zeros
from scipy import special
import matplotlib.pyplot as plt
from multiprocessing import Pool, Pipe, Process
import json
from scipy import special
def frozen(f, KKs, muus, rho1, phiw1, phii1, n1, layer, r, rmax, th):
def aimf(ss):
... |
main_window.py | import re
import os
import sys
import time
import datetime
import traceback
from decimal import Decimal
import threading
import asyncio
from typing import TYPE_CHECKING, Optional, Union, Callable, Sequence
from electrum.storage import WalletStorage, StorageReadWriteError
from electrum.wallet_db import WalletDB
from el... |
server.py | #!/usr/bin/env python
#
# Copyright 2007 Google 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 o... |
frames.py | """Frame module for ReBook application"""
from threading import Thread
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
from tkinter import messagebox
from tkinter import scrolledtext
import asyncio
import json
import os
import webbrowser
from PIL import Image, ImageTk
import tools
import a... |
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... |
runfuzzer.py | import subprocess
import shlex
import time
import threading
from threading import Timer
import config
import pickle
import os
import operators
import random
from operator import itemgetter
import shutil
import inspect
import glob
import sys
from collections import Counter
from datetime import datetime
import binascii a... |
main_window.py | import re
import os
import sys
import time
import datetime
import traceback
from decimal import Decimal
import threading
import electrum_zcash
from electrum_zcash.bitcoin import TYPE_ADDRESS
from electrum_zcash import WalletStorage, Wallet
from electrum_zcash_gui.kivy.i18n import _
from electrum_zcash.paymentrequest i... |
roll_paillier_tensor.py | import uuid
from concurrent.futures.thread import ThreadPoolExecutor
from threading import Thread
from eggroll.core.aspects import _method_profile_logger
from eggroll.core.command.command_model import ErCommandRequest
from eggroll.core.constants import StoreTypes
from eggroll.core.io.kv_adapter import RocksdbSortedKvA... |
get_download_counts.py | # Generates npm_download_counts.csv
import requests
import threading
import sys
import time
import os
import json
n_threads = 16
lock = threading.Lock()
def chunks(lst, n):
"""Yield successive n-sized chunks from lst."""
for i in range(0, len(lst), n):
yield lst[i:i + n]
if os.path.... |
scratch_multiprocesstest.py | import multiprocessing as mp
import time
def testfunc(a):
b = [2,3,4,a]
time.sleep(30)
return b
jobs = []
for i in range(4):
p = mp.Process(target = testfunc, args=('a'))
print('process',i,'started')
jobs.append(p)
time.sleep(0.1)
p.start()
#wait for jobs to finish before continuin... |
speculos.py | import os.path
import threading
import socket
import atexit
import logging
from time import sleep
import docker
from . import dongle
CommException = dongle.CommException
logger = logging.getLogger('speculos')
class SpeculosContainer:
"""
`SpeculosContainer` handles running the Bolos App under test within
... |
test_threading.py | from unittest import TestCase
from embit.ec import PrivateKey
from embit.liquid.pset import PSET
from embit.hashes import tagged_hash
from embit.liquid import slip77
import threading
mbkey = PrivateKey.from_string("L2U2zGBgimb2vNee3bTw2y936PDJZXq3p7nMXEWuPP5MmpE1nCfv")
B64PSET = "cHNldP8BAgQCAAAAAQMEAAAAAAEEAQIBBQEEAf... |
dns_v3.py | #
# Credit to:
# Troy Fawkes for his primer on using queues with Multithreading
# > https://www.troyfawkes.com/learn-python-multithreading-queues-basics/
#
# The Python3 queue documentation
# > https://docs.python.org/3/library/queue.html#queue.Empty
#
import threading
import socket
import datetime
from queue import Q... |
02_countdown.py | # -*- encoding = utf-8 -*-
import multiprocessing
cnt = 100000000
def countdown():
global cnt
while cnt > 0:
cnt -= 1
if __name__ == '__main__':
countdown()
# p1 = multiprocessing.Process(target = countdown)
# p2 = multiprocessing.Process(target = countdown)
# p1.start()
# p2.st... |
multiThread.py | import time, threading
from fredapi import Fred
import pandas as pd
from tqdm import tqdm
import numpy as np
fred = Fred(api_key='APIkey')
treeDF = pd.read_csv('cateTree.csv', index_col=0)
treeDF.index = range(treeDF.shape[0])
# Divide the task into multi threads
totalWork = treeDF.shape[0]
threadNum = 10
# How many d... |
utils.py | """Miscellaneous utilities for running the docbuilder."""
import errno
import os
import traceback
from typing import Optional
class RemoteException(Exception):
"""
Raised if an exception occurred in one of the child processes.
"""
tb: str
def __init__(self, tb: str):
"""
Initial... |
local.py | # Copyright 2017 Carnegie Mellon University. See LICENSE.md file for terms.
import textwrap
import threading
import time
import api
import config
from communication import common
import tasks
class LocalCommunication(object):
def __init__(self, feedback_queue, file_name):
self._feedback_queue = feedback... |
test.py | import json
import os.path as p
import random
import socket
import subprocess
import threading
import time
import logging
import io
import string
import avro.schema
import avro.io
import avro.datafile
from confluent_kafka.avro.cached_schema_registry_client import CachedSchemaRegistryClient
from confluent_kafka.avro.se... |
email.py | """
This file email.py contains functions for sending
text and html rendered emails asynchronously
"""
from threading import Thread
from flask import current_app
from flask import render_template
from flask_mailman import EmailMultiAlternatives
def _send_email_helper(app, msg):
"""
Helper function used for s... |
btlejack.py | from threading import Lock
from queue import Queue
import time
from serial.tools.list_ports import comports
from serial import Serial,SerialException
from mirage.libs.ble_utils.constants import *
from mirage.libs.ble_utils.scapy_btlejack_layers import *
from mirage.libs import io,utils,wireless
class BTLEJackDevice(wi... |
federated_thzdata_sample_CNN_CFA.py | from __future__ import absolute_import, division, print_function, unicode_literals
from keras.utils import to_categorical
import numpy as np
import tensorflow as tf
import datetime
import scipy.io as sio
import multiprocessing
import math
from matplotlib.pyplot import pause
import os
import glob
import argparse
parser... |
walk_sftp.py | import os
import pickle
import pysftp
from base64 import decodebytes
import paramiko
import numpy as np
import datetime as dt
import warnings
from time import sleep
import multiprocessing as mp
from threading import Thread
import pandas as pd
import tempfile
from time import sleep
from socket import error as socket_err... |
bandit_server.py | import socket
from bandit.multi_armed_bandit import MultiArmedBandit
def worker(socket, params, lock, address, root_dir):
import datetime
import traceback
mab = MultiArmedBandit(params, lock, address, root_dir)
while True:
try:
client, address = socket.accept()
data = c... |
gtudp.py | from __future__ import print_function
import socket, threading, select, zlib, struct, binascii
try:
import queue
except ImportError:
import Queue as queue
import random, time # kek
class GTUDP:
def __init__(self, sock, debug=False, magic_numbers=b'', recv_from_any=False):
self.magic_numbers = magic_numbers
... |
test_pysnooper.py | # Copyright 2019 Ram Rachum and collaborators.
# This program is distributed under the MIT license.
import io
import textwrap
import threading
import types
import sys
from pysnooper.utils import truncate
from python_toolbox import sys_tools, temp_file_tools
import pytest
import pysnooper
from pysnooper.variables imp... |
discord.py | # coding: utf-8
# Simple module to send messages through a Discord WebHook
# post a message to discord api via a bot
# bot must be added to the server and have write access to the channel
import json
from threading import Thread, Event
import time
import requests
import websocket
import logging
import re
# Constant... |
test_tools.py | # Copyright 2015-2017, Damian Johnson and The Tor Project
# See LICENSE for licensing information
"""
Helper functions for testing.
Our **stylistic_issues**, **pyflakes_issues**, and **type_check_issues**
respect a 'exclude_paths' in our test config, excluding any absolute paths
matching those regexes. Issue strings ... |
memo_test.py | # Copyright 2018-2021 Streamlit 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 to in wr... |
test_failure.py | import json
import logging
import os
import sys
import tempfile
import threading
import time
import numpy as np
import pytest
import redis
import ray
import ray.ray_constants as ray_constants
from ray.cluster_utils import Cluster
from ray.test_utils import (
relevant_errors,
wait_for_condition,
wait_for_e... |
application.py | import asyncio
import os
import re
import signal
import sys
import threading
import time
from asyncio import (
AbstractEventLoop,
CancelledError,
Future,
Task,
ensure_future,
get_event_loop,
new_event_loop,
set_event_loop,
sleep,
)
from contextlib import contextmanager
from subproces... |
application_test.py | # Copyright 2017 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... |
MapManager.py | #!/usr/bin/python
# -*- utf-8 -*-
# Panda3D imoprts
from direct.task import Task
from direct.interval.IntervalGlobal import *
from direct.showbase.DirectObject import DirectObject
from direct.actor.Actor import Actor
from direct.fsm.FSM import FSM
from panda3d.core import (
CollisionSegment,
Collis... |
ssh.py | from __future__ import print_function, division, absolute_import
from time import sleep
import socket
import os
import sys
import traceback
try:
from queue import Queue
except ImportError: # Python 2.7 fix
from Queue import Queue
from threading import Thread
from toolz import merge
from tornado import gen... |
u_run.py | #!/usr/bin/env python
'''Run an instance of ubxlib automation and report results.'''
import sys # For exit() and stdout
import argparse
from multiprocessing import Process, freeze_support # Needed to make Windows behave
# when doing multiprocessing,
from signal impo... |
HEAT.py | from threading import Thread
from time import sleep
import queue
from statistics import mean
from counterdown import CounterDown
import random
import Pins as pins
import RPi.GPIO as GPIO
class HEAT(object):
__instance = None
def __init__(self, master_):
if HEAT.__instance is not None:
r... |
test_enum.py | import enum
import doctest
import inspect
import os
import pydoc
import sys
import unittest
import threading
from collections import OrderedDict
from enum import Enum, IntEnum, StrEnum, EnumType, Flag, IntFlag, unique, auto
from enum import STRICT, CONFORM, EJECT, KEEP, _simple_enum, _test_simple_enum
from io import St... |
mpv.py | # -*- coding: utf-8 -*-
# vim: ts=4 sw=4 et
#
# Python MPV library module
# Copyright (C) 2017-2020 Sebastian Götte <code@jaseg.net>
#
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General
# Public License as published by the Free Software Foundation, either... |
book_keeper.py | # encoding: utf-8
#
# book_keeper.py
#
# Copyright (c) 2010 René Köcher <shirk@bitspin.org>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modifica-
# tion, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain... |
ex_2.py |
"""
Example 2:
How do I manage memory during multiprocessing?
"""
# Imports
import numpy as np
import multiprocessing as mp
import tracemalloc
from time import sleep
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def forked_processes():
### What's happening to the memory (forking)?
tracemalloc.sta... |
Logger.py | import logging
import threading
import multiprocessing as mp
class CustomQueueHandler(logging.Handler):
def __init__(self, queue):
logging.Handler.__init__(self)
self.queue = queue
def prepare(self, record):
msg = self.format(record)
record.message = msg
record.msg = msg... |
test_chunkstore_s3.py | ################################################################################
# Copyright (c) 2017-2019, National Research Foundation (Square Kilometre Array)
#
# Licensed under the BSD 3-Clause License (the "License"); you may not use
# this file except in compliance with the License. You may obtain a copy
# of the... |
fleet_adapter_mir.py | from rmf_fleet_msgs.msg import Location, RobotMode, RobotState
import rmf_adapter as adpt
from mir100_client.rest import ApiException
from mir100_client.models import PostMissionQueues, PostMissions, \
PostMissionActions, PutStatus
from collections import namedtuple
import threading
import urllib3
import copy
im... |
main.py | from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.graphics import Rectangle, Color
from kivy.uix.floatlayout import FloatLayout
from kivy.core.window import Window
from kivy.clock import Clock
import socket
import threading
import socketserver
from kivy.utils import ... |
server.py | import logging
import random
import time
import requests
from threading import Thread
from websocket_server import WebsocketServer
current_milli_time = lambda: int(round(time.time() * 1000))
def bomb_in_progress(time_limit):
global running
running = True
print('running thread')
end_time = current_milli_time() + (... |
email.py | from threading import Thread
from flask import current_app, render_template
from flask_mail import Message
from . import mail
def send_async_email(app, msg):
with app.app_context():
mail.send(msg)
def send_email(to, subject, template, **kwargs):
app = current_app._get_current_object()
msg = Messa... |
test_jwt_token_manager.py | # pylint: disable=missing-docstring,protected-access
import time
import threading
from typing import Optional
import jwt
import pytest
from ibm_cloud_sdk_core import JWTTokenManager, DetailedResponse
class JWTTokenManagerMockImpl(JWTTokenManager):
def __init__(self, url: Optional[str] = None, access_token: Option... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.