source
stringlengths
3
86
python
stringlengths
75
1.04M
scheduler_job.py
# pylint: disable=no-name-in-module # # 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, Versio...
videoCapture.py
from threading import Thread import cv2 class VideoCapture(): """Video capturing with opencv and threads""" def __init__(self, src=0, name="WebcamVideoStream", resolution = (800,600)): # initialize the video camera stream and read the first frame # from the stream self.stream = cv2.Vide...
manager_coexecution_test.py
import subprocess import threading from .test_utils import ( BaseManagerTestCase, ) from pulsar.managers.unqueued import CoexecutionManager class Coexecutor(object): """Mimic shell script in other container of coexecutor pod-like environment.""" def __init__(self, manager): self.manager = manag...
base_mcast_snoop.py
#!/usr/bin/python # Copyright (c) 2019 Dell 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 # # THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITH...
threads.py
import time import threading import dataclasses from tests.case import Case import rich import rich.progress class TestThread(threading.Thread): def __init__(self, *args, **kwargs): self.exc = None threading.Thread.__init__(self, *args, **kwargs) def run(self): try: i...
eval_multiprocess.py
# Copyright 2018 Google. 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 agree...
autoreload.py
# -*- coding: utf-8 -*- # # Copyright (C)2006-2009 Edgewall Software # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://trac.edgewall.org/wiki/TracLicense. # # This software consis...
neuralet-distancing.py
#!/usr/bin/python3 import argparse from multiprocessing import Process import threading from libs.config_engine import ConfigEngine import libs.pubsub import logging logger = logging.getLogger(__name__) def start_engine(config, video_path): from libs.core import Distancing as CvEngine engine = CvEngine(confi...
test_tcp.py
# -*- coding: utf-8 -*- ''' :codeauthor: Thomas Jackson <jacksontj.89@gmail.com> ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import threading import tornado.gen import tornado.ioloop import tornado.concurrent from tornado.testing import AsyncTestCase, gen_test...
winecave.py
#coding: utf-8 import common as com import datetime as dt import json import hashlib import mail import os import requests import sensor as s import threading import time import uptime last_alerted = 0 last_reported = 0 QUEUE = '/opt/winecave/queue/' def enqueue(obj): try: with open('{0}{1}'.format(...
test_websocket_provider.py
import asyncio import pytest import sys from threading import ( Thread, ) import websockets from tests.utils import ( wait_for_ws, ) from platon import Web3 from platon.exceptions import ( ValidationError, ) from platon.providers.websocket import ( WebsocketProvider, ) if sys.version_info >= (3, 8): ...
myrobot.py
#!/usr/bin/python #-*- coding: utf-8 -*- import os from importlib import import_module from flask import Flask, render_template, Response from flask import render_template from flask import request from flask import abort, redirect, url_for from flask import render_template from flask import session, escape from flask ...
train_ctrl_exp.py
""" Trains controller and the explorer, based on --explorer. Calls the RolloutGenerator, which generates rollouts and the asssociated rewards for either controller or explorer. Controller retuurns sum of discounted rewards, explorer returns sum of undiscounted model reconstruction error (see utils.misc) Trains linear ...
test_functional_box.py
#!/usr/bin/env python # -*- coding: UTF-8 -*- # Test files gathered from json.org and yaml.org from __future__ import absolute_import from multiprocessing import Process, Queue import pytest import pickle try: from test.common import * except ImportError: from .common import * class TestBoxFunctional(unitte...
ui.py
import threading import queue from tkinter import * from tkinter import messagebox from config import * CW = 30 R = 10 class Scaler: """坐标变换器 方便对坐标进行放缩 """ def __init__(self, start, end): self.start = start self.end = end def bind(self, start, end): self.new_start = sta...
DataBaseWorker.py
import sqlite3 import queue import threading import time class DataBaseWorker: def __init__(self, database_path): self.database_path = database_path # self.cursor = self.sql_connection.cursor() self.queue = queue.Queue() self.work = True def start(self): thread = thread...
test_random_generator.py
from threading import Thread from subt_world_generation.random_tree_generator import RandomTreeGenerator, plot_random_tree import matplotlib.pyplot as plt from subt_world_generation.tile_tree import save_tree_as_world_file import cProfile def generator_thread(): tree = RandomTreeGenerator(max_tiles = 50) tree....
WtBtMon.py
''' Descripttion: 回测管理模块 version: Author: Wesley Date: 2021-08-11 14:03:33 LastEditors: Wesley LastEditTime: 2021-09-02 14:18:50 ''' import os import json import subprocess import platform import sys import psutil import hashlib import datetime import shutil import json import threading import time ...
web_server.py
import responder import datetime import logging import threading log = logging.getLogger("WebServer") class WebServer: def __init__(self, settings, plugins): self.api = responder.API( title="Solar Wallbox", version="0.0.1", description="See and control your energy data ...
ca_util.py
#!/usr/bin/python3 ''' SPDX-License-Identifier: Apache-2.0 Copyright 2017 Massachusetts Institute of Technology. Tools for creating a CA cert and signed server certs. Divined from http://svn.osafoundation.org/m2crypto/trunk/tests/test_x509.py The mk_temporary_xxx calls return a NamedTemporaryFile with certs. Usage ; ...
train_model.py
import json import random import threading import time import numpy as np import tensorflow.compat.v1 as tf import tensorflow.keras as keras import tensorflow.keras.layers as layers import matplotlib.pyplot as plt label_to_number_dict = None number_to_label_dict = None def load_dictionaries(): global label_to_nu...
models.py
""" models.py ross spicer updated 2015-04-29 contains the database models for the browser """ from django.db import models from django.core.mail import send_mail, mail_admins from django.core.exceptions import ValidationError # #~ from threading import Thread #didn't work on server #~ from time import sleep from ...
stomp.py
import websocket import time from threading import Thread BYTE = { 'LF': '\x0A', 'NULL': '\x00' } VERSIONS = '1.0,1.1' class Stomp: def __init__(self, host, sockjs=False, wss=True,debug=False): """ Initialize STOMP communication. This is the high level API that is exposed to clients. ...
odd.py
import sys import logging import os import optparse import signal import threading PARROT_COMMON = "/Documents/parrot/groundsdk/packages/common" POMP_LIB = os.path.expanduser("~") + PARROT_COMMON + "/libpomp/python" TELEMETRYD_LIB = os.path.expanduser("~") + PARROT_COMMON + "/telemetry/tools" sys.path.append(POMP_LI...
motor.py
#! /usr/bin/env python import os from multiprocessing import Process, Pipe import rospy from std_msgs.msg import String from geometry_msgs.msg import Twist import RPi.GPIO as GPIO import time # RPI 3 PWM motor pins LEFT_FORW = 12 LEFT_BACK = 32 RIGHT_FORW = 33 RIGHT_BACK = 35 def twist2velocity_cb(twist, args): ...
manager.py
# vim: tabstop=4 shiftwidth=4 expandtab # Copyright (c) 2008, Aldo Cortesi. All rights reserved. # # 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 limit...
sholat.py
# sholat # karjok pangesty # created 31, januari 2019 2:18 pm # updated 25 march 2020 9:14 AM #-*-coding : utf-8-*- ''' PLEASE READ FIRST !!! ----------------------- The code is open source. you can use it to study. but I really don't want to copy this script but don't include the source of the script (here the c...
coverage_testIPv6.py
from Queue import Queue import random import threading import unittest from coapclient import HelperClient from coapserver import CoAPServer from coapthon import defines from coapthon.messages.option import Option from coapthon.messages.request import Request from coapthon.messages.response import Response __author__ ...
client.py
import socket import threading nickname = input("Choose Your Nickname:") if nickname == 'admin': password = input("Enter Password for Admin:") client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Connect to a host client.connect(('127.0.0.1',5555)) stop_thread = False def recieve(): while True: ...
network.py
import zmq import threading import numpy as np __author__ = "Ussama Zahid" __email__ = "ussamazahid96@gmail.com" # this file contains the defination for the ZMQ socket connection used to connect to the unity simulator class ZMQPlug: def __init__(self, state_ptr, queue, port=4567): print("[Network Plug] A...
test_lock.py
import os import subprocess import sys import threading import traceback from modelkit.assets.remote import RemoteAssetsStore from tests import TEST_DIR def _start_wait_process(lock_path, duration_s): script_path = os.path.join(TEST_DIR, "assets", "resources", "lock.py") result = None def run(): ...
notification.py
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the Apache 2.0 License. import os import threading import http.server import queue import json from contextlib import contextmanager from loguru import logger as LOG class PostQueueRequestHandler(http.server.BaseHTTPRequestHandler): de...
smsdispatcher.py
from threading import Thread from queue import Queue, Empty from redis import Redis import json, re, time from datetime import datetime from sms import SMS, BALANCE_USSD, NetworkStatus LOGGER="SMSDispatcher" TEN_MEGABYTES=10485760 FIVE_MINUTES=300. PORT="/dev/ttyAMA0" BAUD=9600 def taskWorker(): _redis=Redis() ...
poc-orig.py
#!/usr/bin/env python3 import argparse from colorama import Fore, init import subprocess import threading from pathlib import Path import os from http.server import HTTPServer, SimpleHTTPRequestHandler CUR_FOLDER = Path(__file__).parent.resolve() def generate_payload(userip: str, lport: int) -> None: program = ...
config.py
"""Abstractions for setting up a Galaxy instance.""" from __future__ import absolute_import from __future__ import print_function import abc import contextlib import importlib.util import os import random import shutil import threading from string import Template from tempfile import mkdtemp from galaxy.containers.do...
__init__.py
import socket import threading import ssl from queue import Queue import time q = Queue() max_threads = 100 starting_port = 1 max_port = 445 secure_ports = [22, 443, 465, 993, 995] print_errors = False connection_timeout = 5.0 ports_failed = [] host = input("Enter host to check (example: www.google.com): ") print("C...
floorplanner.py
#!/usr/bin/env python3 """ author: Jianqi Chen """ import sys, os, svgwrite, random, copy, numpy, getopt, re, threading, multiprocessing, json, datetime, itertools from queue import Queue from SlicingTree import STree s_floorplan = None # the slicing tree, just remember it's a global variable PROCESS_MAX = 5 # Maxima...
clone_five_eval_mini_srcgame_add_map_bn.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function USED_DEVICES = "4,5" import os os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"] = USED_DEVICES import sys import threading import time import tensorflow as tf from absl import...
pyminer.py
#!/usr/bin/python # # Copyright (c) 2011 The Bitcoin developers # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # import time import json import pprint import hashlib import struct import re import base64 import httplib import...
SchedulingTutorial.py
import itertools import traceback import fdb import fdb.tuple fdb.api_version(520) #################################### ## Initialization ## #################################### # Data model: # ('attends', student, class) = '' # ('class', class_name) = seats_left db = fdb.open() scheduling = fdb.d...
core.py
""" Core components of Home Assistant. Home Assistant is a Home Automation framework for observing the state of entities and react to changes. """ # pylint: disable=unused-import, too-many-lines import asyncio from concurrent.futures import ThreadPoolExecutor import enum import functools as ft import logging import os...
main-edge-sm-test.py
import time, queue, threading, sys, os import torch, argparse, logging from pvaccess import Channel from pvaccess import PvObject import pvaccess as pva import numpy as np import tensorrt as trt sys.path.insert(1, '/home/nvidia-agx/Inference/') import PtychoNN from framePreProcess import * from tensorrtcode_batc...
Day12-02.py
## 영상 처리 및 데이터 분석 툴 from tkinter import *; import os.path ;import math from tkinter.filedialog import * from tkinter.simpledialog import * ## 함수 선언부 def loadImage(fname) : global window, canvas, paper, filename, inImage, outImage, inW, inH, outW, outH fsize = os.path.getsize(fname) # 파일 크기 확인 inH = inW = ...
static.py
import zipfile import datetime from threading import Thread from utility.setting import openapi_path def thread_decorator(func): def wrapper(*args): Thread(target=func, args=args, daemon=True).start() return wrapper def now(): return datetime.datetime.now() def timedelta_sec(second, std_time=N...
multipro.py
from multiprocessing import Process import time def sub1(txt): for i in range(30): time.sleep(1) print(txt, i) del(i) def main(p): for j in range(4): time.sleep(2) print('main', j) del(j) if p.is_alive(): p.terminate() time.slee...
Confirm.py
from http import HTTPStatus from rest_framework.decorators import api_view,authentication_classes,throttle_classes from rest_framework.throttling import UserRateThrottle,AnonRateThrottle from datetime import datetime as dt from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from hashlib ...
custom.py
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
main.py
import os import random import string import threading import time from queue import Queue import platform import requests from colorama import Fore, init intro = """ ███████╗████████╗██████╗ ███████╗ █████╗ ███╗ ███╗ ██████╗ ██████╗ ████████╗████████╗███████╗██████╗ ██╔════╝╚══██╔══╝██╔══██╗██╔════╝██╔══██╗██...
main.py
import threading from os import path import eventlet import fire from flask import Flask from server.config import Config from server.socket.log_watcher import LogWatcher from server.socket.task_observer import TaskObserver from template_support.file_storage import LocalFileStorage from thumbnail.cache import Thumbna...
TaskManager.py
# coding=utf-8 import threading import time import tool.tools as tool from task import Task from parser.ParserManager import ParserManager from ui.presenter import dbPresenter LOG_TAG = "TaskManager" class TaskQueue(object): """ 任务队列,基类 """ def __init__(self): self._queue = [] def put(sel...
remote_cluster_test.py
# Copyright 2018 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...
btcompletedirgui.py
#!/usr/bin/env python # Written by Bram Cohen # see LICENSE.txt for license information from BitTornado import PSYCO if PSYCO.psyco: try: import psyco assert psyco.__version__ >= 0x010100f0 psyco.full() except: pass from sys import argv, version assert version >= '2', "Install...
ios_helper.py
import os, plistlib, subprocess, threading, codecs, json, time from pathlib import Path import lyrebird from lyrebird import context from lyrebird.mock import logger_helper from .helper import config _log = logger_helper.get_logger() ideviceinstaller = None idevice_id = None idevicescreenshot = None ideviceinfo = Non...
server_japronto_oauth2.py
import os import sys import random import ujson import uuid import uvloop import asyncio import asyncio_redis import calendar try: sys.path.append(os.path.abspath('./')) except Exception as e: print(str(e.args)) exit(1) from datetime import datetime, timedelta from multiprocessing import Process, Queue fr...
multiproc_example.py
"""Multiprocessing. References ---------- http://docs.python.org/library/multiprocessing.html http://blog.doughellmann.com/2009/04/pymotw-multiprocessing-part-1.html http://broadcast.oreilly.com/2009/04/pymotw-multiprocessing-part-2.html """ # STDLIB import multiprocessing import os # THIRD-PARTY import numpy as np ...
test_autograd.py
# Owner(s): ["module: autograd"] import contextlib import gc import io import math import os import random import sys import tempfile import threading import time import unittest import uuid import warnings import operator from copy import deepcopy from collections import OrderedDict from itertools import product from...
filesystem.py
""" A core class for what CloudMan sees as a file system. This means that it is aware of it and can thus manipulate it. """ import os import shutil import commands import threading from datetime import datetime from boto.exception import EC2ResponseError from cm.util import misc from cm.util.misc import run from cm.u...
utility.py
import os import math import time import datetime from multiprocessing import Process from multiprocessing import Queue import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np import imageio import torch import torch.optim as optim import torch.optim.lr_scheduler as lrs class time...
onlineDialog.py
import sys, socket, json, threading from PyQt5.QtWidgets import QDialog, QLabel, QApplication, QGridLayout, QLineEdit, QSpinBox, QPushButton, QHBoxLayout from PyQt5.QtCore import QRect, QBasicTimer from PyQt5.QtGui import QPainter, QColor class OnlineDialog(QDialog): IP = '' host = 1024 table = 1...
runner.py
#!/usr/bin/env python3 # Copyright 2010 The Emscripten Authors. All rights reserved. # Emscripten is available under two separate licenses, the MIT license and the # University of Illinois/NCSA Open Source License. Both these licenses can be # found in the LICENSE file. """This is the Emscripten test runner. To run ...
clean_data.py
# To specifically ignore ConvergenceWarnings: import warnings from collections import defaultdict from functools import partial from json import load from os import path import numpy as np from tsmoothie import ExponentialSmoother, ConvolutionSmoother import datetime import threading from time import sleep from sklear...
publisher.py
import errno import hashlib import os import posixpath import queue import select import shutil import subprocess import tempfile import threading from contextlib import contextmanager from ftplib import Error as FTPError from io import BytesIO from werkzeug import urls from lektor.exception import LektorException fr...
compiler.py
from subprocess import Popen, PIPE, STDOUT, TimeoutExpired from queue import Queue, Empty from threading import Thread import os import re import settings class_pat = re.compile("(public\s+)?class\s+(?P<name>\w+)", re.MULTILINE) java_exe = os.path.join(settings.jdk_path, 'java') javac_exe = os.path.join(settings.jdk...
timer.py
# coding=utf-8 __author__ = 'weiyulan' import threading import time class Timer(object): """这是一个可以不断的重复执行一个函数的定时器。""" def __init__(self, interval, target, args=(), kwargs={}, repeat_times=-1, start_flag=False): """构造函数。 Keyword arguments: interval -- 运行函数的周期。(大于零) target -- 要...
binary_sensor.py
"""Support to use flic buttons as a binary sensor.""" from __future__ import annotations import logging import threading import pyflic import voluptuous as vol from homeassistant.components.binary_sensor import PLATFORM_SCHEMA, BinarySensorEntity from homeassistant.const import ( CONF_DISCOVERY, CONF_HOST, ...
driver_util.py
"""Scripts for drivers of Galaxy functional tests.""" import collections import fcntl import httplib import json import logging import os import random import shutil import socket import struct import sys import tempfile import threading import time import nose.config import nose.core import nose.loader import nose.p...
test_alock.py
## # .test.test_alock - test .alock ## import unittest import threading import time from ..temporal import pg_tmp from .. import alock n_alocks = "select count(*) FROM pg_locks WHERE locktype = 'advisory'" class test_alock(unittest.TestCase): @pg_tmp def testALockWait(self): # sadly, this is primarily used to exe...
file_term_network.py
import os import logging import threading import struct from wxglterm_interface import TermNetwork from multiple_instance_plugin_base import MultipleInstancePluginBase LOGGER = logging.getLogger('term_network') class FileTermNetwork(MultipleInstancePluginBase, TermNetwork): def __init__(self): MultipleI...
pre_train.py
''' ## Train ## # Code to train D4PG Network on OpenAI Gym environments @author: Mark Sinton (msinto93@gmail.com) ''' import threading import random import tensorflow as tf import numpy as np import pickle from params import train_params from prioritised_experience_replay import PrioritizedReplayBuffer...
spotify.py
from selenium import webdriver from multiprocessing import Process, Lock from time import sleep import csv import random import string def getRandomString(length): #Letters and numbers pool=string.ascii_lowercase+string.digits return "".join(random.choice(pool) for i in range(length)) def getRandomText(leng...
TosVis.py
import math import re import sys import os import select from random import random from threading import Thread from TOSSIM import * from topovis import * from topovis.TkPlotter import Plotter ## Stores preconfigured LEDs' positions and colors. # # The configuration is contained in a list. Each of the entries is # co...
child_process_executor.py
'''Facilities for running arbitrary commands in child processes.''' import os import queue import sys from abc import ABCMeta, abstractmethod from collections import namedtuple import six from dagster import check from dagster.seven import multiprocessing from dagster.utils.error import serializable_error_info_from_...
two-tasks.py
#!/usr/bin/env python """ Two progress bars that run in parallel. """ import threading import time import quo def main(): with quo.ProgressBar() as pb: # Two parallal tasks. def task_1(): for i in pb(range(100)): time.sleep(0.05) def task_2(): for i ...
parallelGram.py
__author__ = 'joe' import os import collections import numpy as np import pandas as pd import pickle import gzip from collections import defaultdict from collections import Counter import io import requests import urllib import dill import multiprocessing import sys def getFiles(ngram_path): """ Gets list of ...
spider_http_api.py
from threading import Thread import socket import time from six.moves.urllib.request import urlopen from grab.spider import Spider, Task from tests.util import BaseGrabTestCase, build_spider class BasicSpiderTestCase(BaseGrabTestCase): def setUp(self): self.server.reset() def get_open_port(self): ...
PythonEyePiServer.py
#!/usr/bin/env python import sys import consul import signal from multiprocessing.managers import SyncManager sys.path.append('src/gen-py') from connect.PythonFacePiClient import FacePiThriftClient from connect.GenericThriftClient import GenericThriftClient from connect.LongTermPersonMemoryClient import LongTermP...
utils.py
import logging import subprocess import os import hashlib import tempfile import pycparser import re from struct import unpack import codecs import shutil from math import floor import threading import time class MachineModel(object): def __init__(self, wordsize, name, short_size, int_size, long_size, ...
dist_autograd_test.py
import sys import threading import time from enum import Enum import random import torch import torch.nn as nn from datetime import timedelta import torch.distributed as dist import torch.distributed.autograd as dist_autograd import torch.distributed.rpc as rpc import torch.testing._internal.dist_utils from torch.autog...
threads_queue.py
from queue import Queue from threading import Thread def worker(q, n): while True: item = q.get() if item is None: break print(f"Processing data '{item}' from the queue #{n}") q = Queue(5) t1 = Thread(target=worker, args=(q, 1)) t2 = Thread(target=worker, args=(q, 2)) t1.star...
gui.py
from world import * from bot import Bot import pyglet from pyglet.gl import * import numpy from threading import Thread class GUI: GREEN_GRASS = numpy.array((0.20, 0.67, 0.13)) BROWN_GRASS = numpy.array((0.47, 0.35, 0.10)) SCROLL_SPEED = 5 ZOOM_SPEED = 1.05 def __init__(self, world, windowwidth...
app.py
#import versionCheck #^This fixes a really common problem I'm getting messages about. It checks for #python 2.x from flask import Flask, render_template, request, url_for, redirect, Markup, jsonify, make_response, send_from_directory, session import requests import sys import bs4 import RandomHeaders import re import ...
mpyg321.py
import pexpect from threading import Thread mpg_outs = [ { "mpg_code": "@P 0", "action": "user_stop", "description": "Music has been stopped by the user." }, { "mpg_code": "@P 1", "action": "user_pause", "description": "Music has been paused by the user." ...
metadata_updater.py
import logging import os import time from threading import Thread import elasticsearch from eth_utils import add_0x_prefix from eth_utils import remove_0x_prefix from ocean_lib.models.bfactory import BFactory from ocean_lib.models.bpool import BPool from ocean_lib.models.fixed_rate_exchange import FixedRateExchange fr...
susi_loop.py
""" Processing logic of susi_linux """ import time import os import re import logging import queue from threading import Thread, Timer, current_thread from datetime import datetime from urllib.parse import urljoin import speech_recognition as sr import requests import json_config import speech_recognition from speech_r...
image.py
import numpy as np from PIL import Image import torch import threading _palette = [ 0, 0, 0, 128, 0, 0, 0, 128, 0, 128, 128, 0, 0, 0, 128, 128, 0, 128, 0, 128, 128, 128, 128, 128, 64, 0, 0, 191, 0, 0, 64, 128, 0, 191, 128, 0, 64, 0, 128, 191, 0, 128, 64, 128, 128, 191, 128, 128, 0, 64, 0, 128, 64, 0, 0, ...
decorators.py
from threading import Thread from functools import wraps from flask import g, make_response, jsonify def async(f): def wrapper(*args, **kwargs): thr = Thread(target=f, args=args, kwargs=kwargs) thr.start() return wrapper def auth_required(f): @wraps(f) def decorated_function(*args, *...
findJobs.py
import sys, Queue, re, urllib, urlparse, time, os, sys from threading import Thread dupcheck = set() def saveCareers(link,key,loc): print "job match found at ", link filename="jobs/" filename+=loc filename+="-" filename+=key if os.path.exists(filename): append_write='a' else: append_write='w' outfile=open...
util.py
#!/usr/bin/env python # -*- encoding: utf-8 -*- import base64 import copy import datetime import functools import hashlib import ipaddr import json import logging import math import re import six import time import types import urllib import uuid from six import iteritems logger = logging.getLogger('threathunter_com...
performance.py
# -*- coding: utf-8 -*- import numpy as np import warnings import multiprocessing as mp def pmap(function, *arguments, **kwargs): """ Parallelized version of map. It calls function on arguments using numprocesses threads. Also try the numexpr package or numba, which are easy to use and may give you bette...
__init__.py
from os import truncate import signal import threading import traceback from datetime import datetime, timedelta from functools import lru_cache from typing import Any, Callable, Dict from pathlib import Path import zmq # Achieve Ctrl-c interrupt recv signal.signal(signal.SIGINT, signal.SIG_DFL) KEEP_ALIVE_TOPIC: str...
execution_scheduling.py
''' Este snipet tienei como propósito realiar un estudio de el agendamiento delas creación de threads. ''' #!/usr/bin/env python3 """ Two threads chopping vegetables """ import threading import time chopping = True def vegetable_chopper(): name = threading.current_thread().getName() vegetable_count = 0 ...
AcimdesTrainingServer.py
import random from typing import List import NeuralNetwork as nn import os import multiprocessing as mp import threading as thrd import pickle import time class Cards: def __init__(self): self.cards = [] for _ in range(4): temp = random.sample(range(8), 8) for ...
messaging.py
""" Abstraction for communicating between Debussy's processes: the main CLI, the OpenFlow manager, and the database triggers. """ import os import pickle import threading import time import xmlrpclib import sysv_ipc from SimpleXMLRPCServer import SimpleXMLRPCServer import debussy.profiling from debussy.log import log...
moto_server.py
"""moto server for pytesting aws services.""" # pylint: disable=too-many-instance-attributes # pylint: disable=unused-variable import asyncio import functools import logging import os import socket import threading import time # Third Party import aiohttp import moto.server import werkzeug.serving HOST = '127.0.0.1...
seasonscreen.py
import cfg from kivy.uix.screenmanager import Screen from kivy.lang import Builder from kivy.properties import * from kivy.metrics import dp import ytvApi as ytv from threading import Thread Builder.load_string(''' <SeasonScreen>: name:'season_screen' MDBoxLayout: orientation:'vertical' Recyc...
spatialreasoner.py
import os import logging import queue import subprocess import threading from . import ccl as cclmod # Term names TERMS = [ 'square', 'triangle', 'circle', 'line', 'cross', 'ell', 'vee', 'star', 'ess', ] class SpatialReasoner(): def __init__(self, ccl): self.logger = ...
dataPreProcessing.py
# -*- coding: utf-8 -*- """ Created on Wed Jan 13 19:02:19 2021 @author: Jacob Salminen @version: 1.0 """ #%% IMPORTS import os import sys SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.dirname(SCRIPT_DIR)) import multiprocessing as mp from datetime import date from localPkg.preproc i...
handlers.py
# Copyright 2001-2016 by Vinay Sajip. All Rights Reserved. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose and without fee is hereby granted, # provided that the above copyright notice appear in all copies and that # both that copyright notice and this permissio...
vagrant_benchmark.py
#!/usr/bin/env python import os, sys sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir)) sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)) import argparse import datetime import socket import traceback import time import logging import json from multiprocessing import Proce...
xweb.py
import asyncio import multiprocessing import os import socket import ujson as json from email.utils import formatdate from functools import partial from http import HTTPStatus import httptools from jsonschema import Draft4Validator, ErrorTree __version__ = '3.0.1' class HTTPException(Exception): def __init__(se...