source stringlengths 3 86 | python stringlengths 75 1.04M |
|---|---|
cleaner.py | from utils.vector_manager import VectorManager
from pattern.en import tokenize
from time import time
import multiprocessing as mp
import os
import re
import sys
import argparse
def cleanhtml(raw_html):
"""
Removes the <doc> tags remaining from wikiExtracted data
:param raw_html: html/text content of a fi... |
app.py | import json
import logging
import multiprocessing as mp
import os
from logging.handlers import QueueHandler
from typing import Dict, List
import sys
import signal
import yaml
from gevent import pywsgi
from geventwebsocket.handler import WebSocketHandler
from peewee_migrate import Router
from playhouse.sqlite_ext impor... |
menubot.py | import base64
import json
import os
import re
import threading
import time
import traceback
from dataclasses import dataclass
from pathlib import Path
import json5
import requests
import schedule as schedule
from bs4 import BeautifulSoup
from telegram import Update
from telegram.ext import Updater, CallbackContext, Di... |
test.py | import cv2
import time
from motion import Motion
from tornado import web, ioloop
import threading
import json
import requests
from config import config
import logging
from motion import Motion
from config import config
import main
def nothing(x):
pass
def ManageMotion():
motion = Motion()
# Param on the... |
socket-preview-progs.py | "Sockets and independent programs"
'''
Although sockets work for threads, the shared memory model of threads often allows
them to employ simpler communication devices such as shared names and objects and
queues. Sockets tend to shine brighter when used for IPC by separate processes and
independently launched programs.
... |
nbsr.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# no unicode literals
import threading
try:
from queue import Queue, Empty
except BaseException:
from Queue import Queue, Empty
# Non-blocking stream reader inspired by:
# https://stackoverflow.com/q... |
conftest.py | import pytest
import time
from context import HGECtx, HGECtxError, ActionsWebhookServer, EvtsWebhookServer, HGECtxGQLServer, GQLWsClient, PytestConf, GraphQLWSClient
import threading
import random
from datetime import datetime
import sys
import os
from collections import OrderedDict
from validate import assert_response... |
test_advanced.py | # coding: utf-8
from concurrent.futures import ThreadPoolExecutor
import json
import logging
import random
import sys
import threading
import time
import numpy as np
import pytest
import ray
import ray.cluster_utils
import ray.test_utils
from ray.test_utils import RayTestTimeoutException
logger = logging.getLogger(... |
WriteGraphDialog.py | # SPDX-License-Identifier: Apache-2.0
# Copyright Contributors to the Rez Project
from Qt import QtCore, QtWidgets, QtGui
from rezgui.util import create_pane
from rez.utils.graph_utils import save_graph, prune_graph
import tempfile
import threading
import os
import os.path
class Writer(QtCore.QObject):
graph_wr... |
run-emu-experiment-sonata copy.py | # import wrappers
# make method which does the following, take mano as parameter
# get start time
# sleep 5 min
# get NS instantiation time
# send instantiation request to osm/sonata
from wrappers import SONATAClient
import time
import json
import requests
from urllib.request import urlopen
import csv
import os
impor... |
test_threaded_import.py | # This is a variant of the very old (early 90's) file
# Demo/threads/bug.py. It simply provokes a number of threads into
# trying to import the same module "at the same time".
# There are no pleasant failure modes -- most likely is that Python
# complains several times about module random having no attribute
# randran... |
core.py | import argparse
import glob
import os
import orjson as json
import ntpath
import pathlib
import queue
import redis
import requests
import shutil
import sys
import threading
import time
import yaml
import pickle
from bmt import Toolkit
from collections import defaultdict
from enum import Enum
from io import StringIO
fro... |
farming.py |
from humpack.farming import Farmer, make_ghost, Replicator, Parallelizer, replicate, Cloner
# import sys, os
# import torch
# import numpy as np
# import torch.multiprocessing as mp
# import itertools
# import traceback
# class ExceptionWrapper(object):
# r"""Wraps an exception plus traceback to communicate across ... |
build_image_data.py | """Converts image data to TFRecords file format with Example protos.
The image data set is expected to reside in JPEG files located in the
following directory structure.
data_dir/label_0/image0.jpeg
data_dir/label_0/image1.jpg
...
data_dir/label_1/weird-image.jpeg
data_dir/label_1/my-image.jpeg
... |
test_cuda.py | from itertools import repeat, chain, product
from typing import NamedTuple
import collections
import contextlib
import ctypes
import gc
import io
import pickle
import queue
import sys
import tempfile
import threading
import unittest
import torch
import torch.cuda
import torch.cuda.comm as comm
from torch.nn.parallel i... |
worker.py | from contextlib import contextmanager
import colorama
import atexit
import faulthandler
import hashlib
import inspect
import io
import json
import logging
import os
import redis
import sys
import threading
import time
import traceback
from typing import Any, Dict, List, Iterator
# Ray modules
from ray.autoscaler._priv... |
vec_env.py | import multiprocessing as mp
from collections import OrderedDict
from typing import Any, Callable, List, Optional, Sequence, Tuple, Type, Union
import numpy as np
import inspect
import warnings
from abc import ABC, abstractmethod
from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple, Type, Union
impor... |
test_signal.py | import unittest
from test import support
from contextlib import closing
import enum
import gc
import pickle
import select
import signal
import struct
import subprocess
import traceback
import sys, os, time, errno
from test.script_helper import assert_python_ok, spawn_python
try:
import threading
except ImportError:... |
server.py | import logging
import queue
import socket
import threading
import select
import config
logging.basicConfig(
format='%(asctime)s.%(msecs)03d %(levelname)s:\t%(message)s',
level=logging.INFO,
datefmt='%H:%M:%S')
class Server:
def __init__(self):
self._socket = None
... |
train_pg_f18.py | """
Original code from John Schulman for CS294 Deep Reinforcement Learning Spring 2017
Adapted for CS294-112 Fall 2017 by Abhishek Gupta and Joshua Achiam
Adapted for CS294-112 Fall 2018 by Michael Chang and Soroush Nasiriany
"""
import numpy as np
import tensorflow as tf
import gym
import logz
import os
import time
im... |
boot1_levenshtein.py | import bitstring
import datetime
import heapq
import multiprocessing
import pylev
import sqlite3
DB_PATH = '/tank/apple2/data/apple2.db'
WORKERS = 2
def main():
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
q = cursor.execute(
"""
select boot1_sha1, boot1.data, count(*) as c fro... |
Lesson12.py | # coding:utf-8
'''
date:2017-11-08
函数,模块和包,面对对象和设计模式,异常处理,正则表达式,系统脚本
'''
# import subprocess
# subprocess.check_output(r'dir')
import os
os.system(r'dir')
import time, threading
def doWork():
name = threading.currentThread().getName()
print "%s start..." % name
time.sleep(3)
print "%s stop..." % ... |
utility.py | import datetime
import math
import os
import time
from multiprocessing import Process
from multiprocessing import Queue
import imageio
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.optim as optim
import torch.optim.lr_scheduler as lrs
matplotlib.use("Agg")
class time... |
main.py | import random
import re
import copy
import socket
import threading
from multiprocessing import Process, Queue
import time
from input_tree_node import Node
from input_tree import InputTree
from input_tree_mutator import Mutator
from helper_functions import _print_exception, _parse_args
class Fuzzer:
def __init__(... |
magicaddon.py | import bpy
from bpy.props import *
import bmesh
import pickle
import math
import mathutils
import json
import requests
from collections import OrderedDict
from scipy.spatial import distance
import threading
import time
import gzip, zlib
import numpy as np
from io import BytesIO
########################################... |
models.py | """App models.
"""
import logging
import threading
import time
import cv2
from configs.general_configs import PRINT_THREAD
from ..cameras.utils import normalize_rtsp, verify_rtsp
from .exceptions import StreamOpenRTSPError
logger = logging.getLogger(__name__)
# Stream
KEEP_ALIVE_THRESHOLD = 10 # Seconds
# Strea... |
batcher.py | # Most of this file is copied form https://github.com/abisee/pointer-generator/blob/master/batcher.py
import queue as Queue
import time
from random import shuffle
from threading import Thread
import numpy as np
import config
import data
import random
random.seed(1234)
class Example(object):
def __ini... |
test_cpp_macro_micro.py | import multiprocessing as mp
from pathlib import Path
import subprocess
import sys
import numpy as np
from libmuscle import Instance, Message
from ymmsl import Operator
from .conftest import skip_if_python_only
def run_macro(instance_id: str):
sys.argv.append('--muscle-instance={}'.format(instance_id))
mac... |
test_local_task_job.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... |
sample_parallel.py | import argparse
parser = argparse.ArgumentParser(description="Sample the distribution across multiple chunks.")
parser.add_argument("run_index", type=int, default=0, help="Which output subdirectory to save this particular run, in the case you may be running multiple concurrently.")
parser.add_argument("--debug", actio... |
files.py | from django.apps import apps
from django.core.exceptions import ObjectDoesNotExist
from django.core.files.base import ContentFile, File
from io import BytesIO, StringIO
import os
from pydub import AudioSegment
import threading
Song = apps.get_model('content', 'Song')
Track = apps.get_model('content', 'Track')
Variabl... |
tracing_test.py | # Copyright 2019, The TensorFlow Federated 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 o... |
safe_bank.py | import datetime
import random
import time
from threading import Thread, RLock
from typing import List
class Account:
def __init__(self, balance=0):
self.balance = balance
def main():
accounts = create_accounts()
total = sum(a.balance for a in accounts)
validate_bank(accounts, total)
pri... |
runCtaTrading.py | # encoding: UTF-8
import multiprocessing
from time import sleep
from datetime import datetime, time
from vnpy.event import EventEngine2
from vnpy.trader.vtEvent import EVENT_LOG
from vnpy.trader.vtEngine import MainEngine, LogEngine
from vnpy.trader.gateway import ctpGateway
from vnpy.trader.app import ctaStrategy
fr... |
main.py | #!/usr/bin/env python
# Copyright (c) PLUMgrid, Inc.
# Licensed under the Apache License, Version 2.0 (the "License")
from builtins import input
from http.server import HTTPServer, SimpleHTTPRequestHandler
from netaddr import IPNetwork
from os import chdir
from pyroute2 import IPRoute, NetNS, IPDB, NSPopen
from random... |
dask.py | # This file is part of the Open Data Cube, see https://opendatacube.org for more information
#
# Copyright (c) 2015-2020 ODC Contributors
# SPDX-License-Identifier: Apache-2.0
""" Dask Distributed Tools
"""
from typing import Any, Iterable, Optional, Union, Tuple
from random import randint
import toolz
import queue
fr... |
index.py | import asyncio
import discord
from discord.ext import commands
import aiohttp
from requests_html import AsyncHTMLSession
import nest_asyncio
import json
import socket
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import threading
import requests
try:
import ... |
tuq_monitoring.py | import json
import logging
import threading
import time
from remote.remote_util import RemoteMachineShellConnection
from .tuq import QueryTests
class QueryMonitoringTests(QueryTests):
def setUp(self):
super(QueryMonitoringTests, self).setUp()
self.threadFailure = False
self.run_cbq_query... |
rm_silence_vid.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 10 17:51:52 2019
@author: Mohammed Al-Rawi
Removing silence segements from videos.
Noise value can be used to control how much noise needs to be remvoed. Lower
'noise' dB value indicates lower noise (keeping in mind that -90 is lower than -30).
... |
Example_MultithreadMultipleSessions.py | .. code-block:: python
"""
Multiple threads are accessing two RsInstrument objects with two separate sessions
"""
import threading
from RsInstrument import *
def execute(session: RsInstrument, session_ix, index) -> None:
"""Executed in a separate thread."""
print(... |
test_start_manager.py | import threading
import time as ttime
import json
from bluesky_queueserver.manager.start_manager import WatchdogProcess
from bluesky_queueserver.tests.common import format_jsonrpc_msg
class ReManagerEmulation(threading.Thread):
"""
Emulation of RE Manager, which is using Thread instead of Process.
The fu... |
monitor.py | # Copyright (C) 2016 Nippon Telegraph and Telephone 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 by appli... |
Day-Test.py | # 每日练习,即用即更
import json
import re
import threading
import time
from queue import Queue
import requests
from bs4 import BeautifulSoup
from lxml import etree
from retrying import retry
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Ch... |
test_bz2.py | from test import support
from test.support import bigmemtest, _4G
import unittest
from io import BytesIO, DEFAULT_BUFFER_SIZE
import os
import pickle
import glob
import tempfile
import pathlib
import random
import shutil
import subprocess
import threading
from test.support import import_helper
from test.support import... |
master.py | # -*- coding: utf-8 -*-
'''
This module contains all of the routines needed to set up a master server, this
involves preparing the three listeners and the workers needed by the master.
'''
# Import python libs
import os
import re
import time
import errno
import signal
import shutil
import logging
import hashlib
import... |
dataset.py | import queue
import time
from multiprocessing import Queue, Process
import cv2
import numpy as np
from joblib import Parallel, delayed
from stable_baselines import logger
class ExpertDataset(object):
"""
Dataset for using behavior cloning or GAIL.
The structure of the expert dataset is a dict, saved as... |
threading_simple.py | #!/usr/bin/env python3
# encoding: utf-8
#
# Copyright (c) 2008 Doug Hellmann All rights reserved.
#
"""Creating and waiting for a thread.
"""
#end_pymotw_header
import threading
def worker():
"""thread worker function"""
print('Worker')
threads = []
for i in range(5):
t = threading.Thread(target=worke... |
PTSApp.py | #macOS
#Kivy
#python3 -m pip install "kivy[base] @ https://github.com/kivy/kivy/archive/master.zip"
#
#KivyMD
#git clone https://github.com/kivymd/KivyMD.git --depth 1
#cd KivyMD
#pip install .
#
#Other
#python3 -m pip install pygame==2.0.1
#python3 -m pip install usbserial4a
#python3 -m pip install python-osc
#python3... |
common.py | """Test the helper method for writing tests."""
import asyncio
import collections
from collections import OrderedDict
from contextlib import contextmanager
from datetime import timedelta
import functools as ft
from io import StringIO
import json
import logging
import os
import sys
import threading
import time
import uu... |
grpc_debug_test_server.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... |
test.py | import json
import pytest
import random
import re
import string
import threading
import time
from multiprocessing.dummy import Pool
from helpers.client import QueryRuntimeException
from helpers.cluster import ClickHouseCluster
from helpers.test_tools import TSV
cluster = ClickHouseCluster(__file__)
node1 = cluster.a... |
mixins.py | # -*- coding: utf-8 -*-
# minin classes.
# use extra resource to enhance original adb device.
# interface class should have raw_cmd method with a signature
# as follows:
#
# def raw_cmd(self, *args, **kwargs):
# ...
# return subprocess.Popen(...)
#
# where `args` is adb command arguments and kwargs are ... |
embed_utils.py | """ Very heavily inspired by the official evaluation script for SQuAD version 2.0 which was
modified by XLNet authors to update `find_best_threshold` scripts for SQuAD V2.0
In addition to basic functionality, we also compute additional statistics and
plot precision-recall curves if an additional na_prob.json file is p... |
remote_executor.py | # Copyright 2019, The TensorFlow Federated 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 o... |
modulewatcher.py | #####################################################################
# #
# modulewatcher.py #
# #
# Copyright 2013, Monash University ... |
PyShell.py | #! /usr/bin/env python
import os
import os.path
import sys
import string
import getopt
import re
import socket
import time
import threading
import traceback
import types
import macosxSupport
import linecache
from code import InteractiveInterpreter
try:
from Tkinter import *
except ImportError:
print>>sys.__s... |
json_process.py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import copy
import hashlib
import json
import os
import subprocess
import sys
import urllib.request
import zipfile
import shutil
import threading
import datetime
from dateutil.parser import parse
from threading import Timer
import wx
from fileIO import ifExist
import time... |
cmd_jshell.py | #!/usr/bin/env python3
import asyncio
import json
import threading
from datetime import datetime
from http import HTTPStatus
from pathlib import Path
from pprint import pprint
from queue import Queue
import click
import websockets
from prompt_toolkit.contrib.completers import WordCompleter
from prompt_toolkit.history... |
event_manage.py | # -*- coding: utf-8 -*-
from queue import Queue, Empty
from threading import Thread
class EventManager:
"""
This is an event manager .
"""
def __init__(self):
self.__eventQueue = Queue()
self.__active = False
self.__thread = Thread(target=self.__run)
# ... |
server.py | ################################################################################
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# ... |
manager.py | import argparse
import ast
import copy
import datetime
from enum import Enum
from mlworkflow import lazyproperty as cached_property
import multiprocessing
import itertools
import logging
import os
import time
import astunparse
from mlworkflow import SideRunner
from experimentator import DummyExperiment
from .utils im... |
engine.py | import logging
import math
import time
import traceback
from threading import Thread
import cv2
from pynput import keyboard, mouse
from fishy.constants import fishyqr, lam2, libgps
from fishy.engine import SemiFisherEngine
from fishy.engine.common.IEngine import IEngine
from fishy.engine.common.window import WindowCl... |
pithon.py | from threading import Thread
from lib.alphabot import AlphaBot2
from lib.buzzer import beep_on, beep_off
from lib.led import led
from lib.ultrasonic import distance
from lib.infrared import get_key
from util.state import State
class Pithon:
def __init__(self):
# drive
self.drive = AlphaBot2()
... |
speed_pc.py | import mbhandler
import getch
import threading
import queue
key = queue.Queue()
RUNNING = True
def keypress():
global RUNNING
while RUNNING:
try:
k = getch.getch()
try:
key.put(k)
except key.Full:
pass
except KeyboardInterrupt... |
static.py | import sqlite3
import zipfile
import datetime
import telegram
import pandas as pd
from threading import Thread
from utility.setting import db_stg, openapi_path
try:
connn = sqlite3.connect(db_stg)
df_tg = pd.read_sql('SELECT * FROM telegram', connn)
connn.close()
except pd.io.sql.DatabaseError:
bot = '... |
ssh.py | from __future__ import absolute_import
from __future__ import division
import inspect
import logging
import os
import re
import shutil
import six
import string
import sys
import tarfile
import tempfile
import threading
import time
import types
from pwnlib import term
from pwnlib.context import context
from pwnlib.log... |
test_datapipe.py | import http.server
import itertools
import os
import os.path
import pickle
import random
import socketserver
import sys
import tarfile
import tempfile
import threading
import time
import unittest
import warnings
import zipfile
from functools import partial
from typing import (
Any,
Awaitable,
Dict,
Gene... |
servers.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
from __future__ import absolute_import, division, print_function, unicode_literals
import functools
import os
import subprocess
import sys
import threading... |
client.py | import time
import threading
import os
import subprocess
import re
import datetime
import logging
import typing
import git
import git.exc
import filelock
from .data import User, Function, Struct, Patch
from .state import State
from .errors import MetadataNotFoundError, ExternalUserCommitError
_l = logging.getLogger(... |
exchange_rate.py | from datetime import datetime
import inspect
import requests
import sys
import os
import json
import pkgutil
from threading import Thread
import time
import csv
import decimal
from decimal import Decimal as PyDecimal # Qt 5.12 also exports Decimal
from collections import defaultdict
from . import networks
from .bitco... |
zeromq.py | # -*- coding: utf-8 -*-
'''
Zeromq transport classes
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import sys
import copy
import errno
import signal
import hashlib
import logging
import weakref
from random import randint
# Import Salt Libs
import salt.auth... |
request.py | import json
import re
import urllib.error
import urllib.parse
import urllib.request
from queue import Queue
from threading import Thread
import numpy as np
ex_query = '''
select *{
STR_TO_SUB
}
'''
q_db_wd_sameAs = '''
select ?db_uri ?wd_uri
where{
values ?db_uri { <STR_TO_SUB> }
?db_uri owl:sameAs ?wd_uri.
filter(c... |
main.py | """
An example demonstrating a stand-alone "notebook".
Copyright (c) Jupyter Development Team.
Distributed under the terms of the Modified BSD License.
Example
-------
To run the example, see the instructions in the README to build it. Then
run ``python main.py`` and navigate your browser to ``localhost:8765``.
Not... |
keepkey.py | from binascii import hexlify, unhexlify
import traceback
import sys
from electrum_axe.util import bfh, bh2u, UserCancelled, UserFacingException
from electrum_axe.bitcoin import TYPE_ADDRESS, TYPE_SCRIPT
from electrum_axe.bip32 import BIP32Node
from electrum_axe import constants
from electrum_axe.axe_tx import to_varby... |
main.py | # -*- coding: utf-8 -*-
"""
Onyx Project
https://onyxlabs.fr
Software under licence Creative Commons 3.0 France
http://creativecommons.org/licenses/by-nc-sa/3.0/fr/
You may not use this software for commercial purposes.
@author :: Cassim Khouani
"""
import onyx, sys, os, time
import threading
from threading import Thr... |
utils.py | import datetime
import errno
import json
import os
import sys
import time
from binascii import hexlify
from threading import Event, Thread
from typing import List
from unittest import TestCase
from unittest.mock import patch
import jupyter_core.paths
import requests
from ipython_genutils.tempdir import TemporaryDirect... |
project.py | import asyncio
from audioled.filtergraph import (FilterGraph, Updateable)
from typing import List, Dict
import audioled.devices
import audioled.audio
import audioled.filtergraph
import time
import multiprocessing as mp
import traceback
import ctypes
import os
from functools import wraps
import numpy as np
def ensur... |
train_ltcn_depth.py | import os
import argparse
import torch
import numpy as np
import pickle
import sys
sys.path.append('./utils')
from torch import optim
from torch import nn
from torch import multiprocessing
from torch.optim import lr_scheduler
from torch.autograd import Variable
from torch.utils.data import DataLoader, ConcatDataset
fr... |
field.py | from __future__ import division
from __future__ import print_function
# still tracking down the last few calls missing the np. prefix,
# leftover from 'from numpy import *'
import numpy as np
import glob,types
import copy
from numpy.random import random
from numpy import ma
from numpy.linalg import norm
import tem... |
updater.py | from http.client import HTTPResponse
from logging import getLogger
from pathlib import Path
from tempfile import gettempdir, gettempprefix
from threading import Thread
from time import time
from typing import Callable, Optional
from urllib.error import HTTPError
from urllib.request import Request, urlopen
try:
fro... |
gcsio.py | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... |
client.py | import socket
import sys
import time
import threading
x=socket.socket()
h_name= input(str("Enter the hostname of the server: "))
port= 1234
x.connect((h_name,port))
print("Connected to chat server")
print("You can now start sending messages")
def recv():
while 1:
incoming_message=x.recv(1024)
print("Se... |
multi_threading_test.py | import threading
import wandb
# Checks if wandb has issues during set up in a multithreaded environment
def thread_test(n):
run = wandb.init(project="threadtest")
run.log({"thread": n})
def main():
try:
threads = []
for i in range(2):
threads.append(threading.Thread(target=t... |
emails.py | import os
from threading import Thread
from flask_mail import Message
from app import app, mail
def send_async_mail(app, msg):
with app.app_context():
mail.send(msg)
def mail_send(subject, recipients, text_body):
msg = Message(
subject, sender=os.environ.get("MAIL_DEFAULT_SENDER"), recipien... |
inference.py | import argparse
import copy
from datetime import datetime
from enum import Enum
import glob
import importlib
import json
import logging
import math
import numpy as np
import os
import pickle
from pointset import PointSet
import pprint
from queue import Queue
import subprocess
import sys
import tempfile
import tensorflo... |
main.py | ##################################################################################
# #
# Copyright (c) 2020 AECgeeks #
# ... |
udpBroadcast.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Main entrypoint for UDP chat test.
'''
'''
MIT License
Copyright (c) 2019 Simon Lövgren
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software witho... |
tools.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, unicode_literals, print_function
"""
This file contains utilities to generate test repositories.
"""
import datetime
import io
import os
import threading
import time
import six
im... |
trainer_utils.py | # coding=utf-8
# Copyright 2020-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ap... |
thread_name.py | import threading
import time
def myThread():
print(f'Thread {threading.current_thread().name} started')
time.sleep(5)
print(f'Thread {threading.current_thread().name} finished')
for i in range(4):
threadName = 'Thread-' + str(i)
thread = threading.Thread(name=threadName, target=myThread)
thr... |
test_consumer.py | # Copyright 2017, Google LLC 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 law or a... |
interface_multiprocessing.py | from multiprocessing import Process
def setup_multiproceesing(target, data_list):
processes = []
for index, data in enumerate(data_list):
print("make process #{}".format(index))
process = Process(target=target, args=(data,))
processes.append(process)
process.start()
return ... |
thread_event.py | #! /usr/bin/env python3
# -*- coding:utf-8 -*-
import threading
import time
# 通过Event来实现两个或多个线程间的交互,下面是一个红绿灯的例子,即起动一个线程做交通指挥灯,生成几个线程做车辆,车辆行驶按红灯停,绿灯行的规则。
def lighter():
count = 0
event.set()
while True:
if 5 < count < 10:
event.clear()
print("This is RED....")
elif... |
server_with_remote_id_test.py | import os
import sys
import pytest
import uvicorn
import asyncio
import requests
from fastapi import FastAPI
from multiprocessing import Process
from fastapi_websocket_rpc.utils import gen_uid
from fastapi_websocket_rpc.logger import get_logger
from fastapi_websocket_rpc.rpc_channel import RpcChannel
# Add parent pat... |
whitney.py | #!/usr/bin/env python
# authored by John Hammond
# edited by babysnoop
import SocketServer
import time
import threading
class Service(SocketServer.BaseRequestHandler):
def handle( self ):
print "someone connected!"
entered = self.receive()
entered_a = entered.split(" ")
... |
log.py | #!/usr/bin/python
#
# Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
#
#
# log
#
# Query log messages from analytics
#
import sys
import ConfigParser
import argparse
import json
import datetime
import logging
import logging.handlers
import time
import re
from multiprocessing import Process
from opser... |
ssh.py | #!/usr/bin/env python3
"""
DMLC submission script by ssh
One need to make sure all slaves machines are ssh-able.
"""
from __future__ import absolute_import
from multiprocessing import Pool, Process
import os, subprocess, logging
from threading import Thread
from . import tracker
def sync_dir(local_dir, slave_node, s... |
word2vec.py | """Multi-threaded word2vec mini-batched skip-gram model.
Trains the model described in:
(Mikolov, et. al.) Efficient Estimation of Word Representations in Vector Space
ICLR 2013.
http://arxiv.org/abs/1301.3781
This model does traditional minibatching.
The key ops used are:
* placeholder for feeding in tensors for eac... |
server.py | """Tcp server module."""
import socket
import threading
from taskmanager.tcp_protocol import const_tcp
from taskmanager.tcp_protocol import message_templates as tmp
from taskmanager.process_management import task_manager as tm
class TCPServer:
"""The class that is responsible for creating the server object."""
... |
test_events.py | """Tests for events.py."""
#TODO: port the Handle and Policy tests
import functools
import gc
import io
import os
import signal
import socket
try:
import ssl
except ImportError:
ssl = None
HAS_SNI = False
else:
from ssl import HAS_SNI
import subprocess
import sys
import threading
import time
import err... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.