source
stringlengths
3
86
python
stringlengths
75
1.04M
utils.py
import asyncio import threading import uuid import multiprocessing as mp from subprocess import PIPE from tornado.testing import AsyncTestCase, gen_test from unittest import TestCase from jupyter_client import KernelManager, AsyncKernelManager from jupyter_client.ioloop import IOLoopKernelManager from jupyter_client...
dummy_follower.py
import init import zmq from dummy_params1 import raftParams import threading from core import Log import logger import msgpack import random import _globals import time class Follower: def __init__(self, servers, leaderID): self.servers = servers self.sockets = {} self.leaderID = leaderID...
spinner.py
# Copyright 2020 The Pigweed 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
im2rec.py
# -*- coding: utf-8 -*- from __future__ import print_function import os import sys curr_path = os.path.abspath(os.path.dirname(__file__)) sys.path.append(os.path.join(curr_path, "../python")) import mxnet as mx import random import argparse import cv2 import time import traceback def list_image(root, ...
test_capi.py
# Run the _testcapi module tests (tests for the Python/C API): by defn, # these are all functions _testcapi exports whose name begins with 'test_'. from collections import OrderedDict import _thread import importlib.machinery import importlib.util import os import pickle import random import re import subprocess impo...
eval.py
""" Copyright 2017-2018 Fizyr (https://fizyr.com) 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 w...
controller.py
#!/usr/bin/env impala-python # # 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 (...
pod.py
""" Pod related functionalities and context info Each pod in the openshift cluster will have a corresponding pod object """ import logging import os import re import yaml import tempfile import time import calendar from threading import Thread import base64 from ocs_ci.ocs.ocp import OCP, verify_images_upgraded from ...
multithread_dataiter_for_cross_entropy_v1.py
# -*- coding: utf-8 -*- import random import math import threading import time import logging import queue import cv2 import numpy from ChasingTrainFramework_GeneralOneClassDetection.image_augmentation.augmentor import Augmentor from ChasingTrainFramework_GeneralOneClassDetection.data_iterator_base.data_batch import D...
Main.py
#!/usr/bin/python3 # Importing modules print("[PROGRAM] Importing modules...") import subprocess import sys import os import platform import json import stat import time from multiprocessing import Process # These variables are used to see what libraries are or aren't installed cv2_error = False pygui_error = False ...
redis_semaphore.py
import time import uuid from threading import Thread from typing import Any, Callable, List, NamedTuple, Optional from redis import Redis from redis.exceptions import LockError class ParamsNT(NamedTuple): capacity: int timeoutms: int sleepms: int decay: float ParamsNT.capacity.__doc__ = "bool (fiel...
eventserver.py
"""Event sending common code""" import socket, queue, threading, logging, os, json log = logging.getLogger(__name__) def create_sending_threads(sockname='/tmp/dspipe/events'): """Create a simple threaded server serving events at sockname""" outputs = [] out_queue = queue.Queue() t = threading.Thread(...
logged_in.py
from client.states import invited, inviting, logged_out from client.states.base import State from client.commands import Command from client.opponent_adapter import OpponentAdapter from client.exceptions import ( Unauthenticated, UserIsInvalid, UserNotActive, WrongPassword, ) from threading import Thre...
base.py
import argparse import base64 import copy import itertools import json import multiprocessing import os import re import sys import threading import time import uuid from collections import OrderedDict from contextlib import ExitStack from typing import ( Optional, Union, Tuple, List, Set, Dict,...
cachingFileStore.py
# Copyright (C) 2015-2021 Regents of the University of California # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
run_experiment.py
import atexit import sacred import argparse import time import math import subprocess import shutil import os import json import threading import requests import glob from configs import fetch_model_params import socket import subprocess import queue import sys import signal from pyfra import * from parse import parse ...
replay.py
from __future__ import print_function from future import standard_library standard_library.install_aliases() from builtins import zip from builtins import str from builtins import object # Copyright 2018 The TensorFlow Authors All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # y...
superSpider.py
# coding:utf-8 from simple_spider.spider_lib.requestSite import RequestSite from simple_spider.spider_lib.dataExtractCenter import DataExtractCenter from simple_spider.spider_lib.dataHandleCenter import DataHandleCenter from simple_spider.sys_func.numberautochange import NumAutoChange from simple_spider.sys_func.filetx...
benchmark_parallel_smbo_lightgbm.py
""" example cmdline: test time: python test/reproduction/so/benchmark_parallel_smbo_lightgbm.py --datasets optdigits --n 100 --n_jobs 2 --batch_size 1 --rep 1 --start_id 0 run serial: python test/reproduction/so/benchmark_parallel_smbo_lightgbm.py --datasets optdigits --runtime_limit 1200 --n_jobs 2 --batch_size 1 --...
app.py
import os import multiprocessing as mp import sys from os import environ import json from flask import Flask from flask import render_template from flask import request from flaskr.db_query.query_angkot_sekolah import get_kebutuhan_per_km2 from flaskr.db_query.query_angkot import get_trayek, get_angkot_total, get_an...
los_alumnos_y_el_asesor.py
import threading, queue import time # El problema es parecido al productor-consumidor, # sin embargo, en este caso una vez que se atienda a un # alumno, se enviará a la cola de nuevo en caso de que # aún tenga preguntas disponibles (tiene y inicialmente) buf = queue.Queue() # Máximo número de alumnos en el salón de c...
testing.py
from os.path import dirname, basename, abspath from collections import defaultdict, Counter, OrderedDict from multiprocessing import Process, Manager from subprocess import Popen, PIPE from xml.sax import make_parser from xml.sax.handler import ContentHandler from io import StringIO from glob import glob from datetime ...
mqtt_wss_example_test.py
from __future__ import unicode_literals from __future__ import unicode_literals from builtins import str import re import os import sys import ssl import paho.mqtt.client as mqtt from threading import Thread, Event from tiny_test_fw import DUT import ttfw_idf event_client_connected = Event() event_stop_client = Even...
singleton.py
#! /usr/bin/env python """ Copyright (c) 2017 Andrew Azarov 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 the rights to use, copy, modify, merge,...
test_behaviours.py
# TODO: rename fixture files to express the actual behavior and not the test intent from datetime import datetime from datetime import timedelta from itertools import zip_longest, count import hashlib import json import os import pickle import shlex import signal import stat import string import subprocess import temp...
devicelistener.py
''' Listens for network messages signaling the presence of a device ''' import socket import threading import simplejson from Server.devicecontroller import DeviceController import sys import traceback PORT=2050 class DeviceListener(object): def __init__(self, device_controller: DeviceController, logger): ...
main.py
import time import torch.multiprocessing as mp import torch import os from torch.optim.lr_scheduler import MultiStepLR,StepLR import datetime from train import train_combined,train_dual,train_batch,generate_trajectories,dual_learning_update,combined_learning_update from poker_env.config import Config import poker_env...
ioc.py
import glob import json import numpy import os import re import textwrap import time import gepics from queue import Queue from datetime import datetime from enum import Enum from devioc import models, log from threading import Thread from twisted.internet import reactor from . import isara, msgs PUCK_LIST = [ '...
libfibre.py
#!/bin/python from ctypes import * import asyncio import os from itertools import count, takewhile import struct from types import MethodType import concurrent import threading import time import platform from .utils import Logger, Event import sys # Enable this for better tracebacks in some cases #import tracemalloc...
test_zmq_node.py
#!/usr/bin/env python3 # Copyright 2004-present Facebook. All Rights Reserved. import asyncio import os import time from multiprocessing import Process from typing import List, Sequence import pytest import zmq from ...graphs import ( AsyncPublisher, Config, Connections, Graph, Module, Node, ...
pygletExample.py
import math import sys import threading import IPython import numpy from PIL import Image import vault from easyrenderer import VDKEasyRenderer import pyglet.window.key as keyboard import pyglet from camera import * from os.path import abspath import numpy as np from sys import argv import logging class VDKViewPor...
common.py
# Copyright 2021 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. from enum import Enum from functools import wraps from pathlib import...
trade.py
#!/usr/bin/python # -*- coding: utf-8 -*- """ __title__ = '' __author__ = 'HaiFeng' __mtime__ = '2016/9/22' """ import threading import itertools import time import os import platform from QACTP.enums import OrderType, InstrumentStatus, DirectType, OffsetType, HedgeType, TradeTypeType from QACTP.structs import InfoFi...
main.py
from spotify import DOWNLOADMP3 as SONGDOWNLOADER import telepot import spotify import requests import threading token = '1613133198:AAF5-yAUKzFiptkmrTGw7qNp5OhY-91144s' bot = telepot.Bot(token) sort = {} def txtfinder(txt): a = txt.find("https://open.spotify.com") txt = txt[a:] return txt def do...
holoros_viewer.py
from multiprocessing.connection import wait import sys import argparse import socket import struct from collections import namedtuple import cv2 import numpy as np import multiprocessing def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("--host", help="Host address to...
download_manager_test.py
# coding=utf-8 # Copyright 2019 The TensorFlow Datasets 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 appl...
deploy.py
# Copyright (c) OpenMMLab. All rights reserved. import argparse import logging import os.path as osp from functools import partial import mmcv import torch.multiprocessing as mp from torch.multiprocessing import Process, set_start_method from mmdeploy.apis import (create_calib_table, extract_model, ...
main.py
from flask import Flask,jsonify,render_template from threading import Thread import data app = Flask(__name__) # to prevent keys from being sorted app.config['JSON_SORT_KEYS'] = False app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True @app.route('/') def home(): return render_template("home.html") @app.route('/cryp...
main.py
# # main.py # TunesControllerServer # # Created by CoreCode on 30.10.07. # Copyright © 2018 CoreCode Limited #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 with...
client.py
# -*- coding:utf-8 -*- import pickle import zlib from multiprocessing import Process import numpy as np import zmq def handle(id, host="127.0.0.1", port=7902): c = zmq.Context() s = c.socket(zmq.REQ) s.connect('tcp://%s:%d' % (host, port)) i = 0 while i < 100: msg = np.asarray([id, i] * i...
competitive_worker_id_generator.py
from abc import abstractmethod from datetime import datetime from enum import Enum from logging import getLogger from os import getpid from random import randrange from socket import AF_INET, SOCK_DGRAM, socket from threading import Thread from typing import Callable, List, Optional from time import sleep from watchm...
bootstrap_test.py
import os import random import re import shutil import tempfile import threading import time import logging import signal from cassandra import ConsistencyLevel from cassandra.concurrent import execute_concurrent_with_args from ccmlib.node import NodeError, TimeoutError, ToolError from ccmlib.node import TimeoutError ...
writers.py
from abc import ABCMeta, abstractmethod from queue import Queue from threading import Thread from typing import Any, Optional from wsgi_lineprof.formatter import BaseFormatter from wsgi_lineprof.stats import LineProfilerStats from wsgi_lineprof.types import Stream class BaseStreamWriter(metaclass=ABCMeta): def _...
logger.py
#!/usr/bin/env python """ Class for dealing with logger-function used across all TOBIAS tools @author: Mette Bentsen @contact: mette.bentsen (at) mpi-bn.mpg.de @license: MIT """ import sys import os from datetime import datetime import logging import logging.handlers import multiprocessing as mp im...
lisp-rtr.py
# ----------------------------------------------------------------------------- # # Copyright 2013-2019 lispers.net - Dino Farinacci <farinacci@gmail.com> # # 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...
WorkerThreadManager.py
#!/usr/bin/env python """ _WorkerThreadManager_ A class used to manage regularly running worker threads. """ from __future__ import print_function from builtins import object import logging import threading import time from WMCore.Agent.HeartbeatAPI import HeartbeatAPI from WMCore.WorkerThreads.BaseWorkerThread impo...
zjsfb_grabno_2018.py
#! /usr/bin/env python # -*- coding: utf-8 -*- # # Copyright: error.d # Date : 2018-02-24 # Create by: error.d<error.d@gmail.com> # import re import time import json import requests import threading from lxml import etree from ying import * #from ding import * """ todolist: * 退出机制完善 """ am_str = u'\xe4\xb8\x8a\xe...
multiprocess1.py
""" 使用Process类创建多个进程 Version: 0.1 Author: BDFD Date: 2018-03-20 """ # 通过下面程序的执行结果可以证实 父进程在创建子进程时复制了进程及其数据结构 # 每个进程都有自己独立的内存空间 所以进程之间共享数据只能通过IPC的方式 from multiprocessing import Process, Queue, current_process from time import sleep def sub_task(content, counts): print(f'PID: {current_process().pid}') counte...
process-lock.py
### # Multiprocessing lock test. # # License - MIT. ### import os from multiprocessing import Process, Lock # process_function - Process test function. def process_function(id, lock): # { lock.acquire() print('Process id: %d.' % id) lock.release() # } # Main function. def main(): # { # Creat...
main.py
from flask import Flask, send_from_directory, render_template, Response, request from flask_socketio import SocketIO, emit import json import asyncio from redis import Redis from threading import Thread from datetime import datetime messages = [] message_limit_sec = {} bans = {} app = Flask('python_simple_chat_server...
bot.py
# -*- coding: utf-8 -*- import LineAlpha from LineAlpha.lib.curve.ttypes import * from datetime import datetime #from imgurpython import ImgurClient import time,random,sys,json,codecs,threading,glob,os,subprocess,multiprocessing cl = LineAlpha.LINE() cl.login(token=" ") cl.loginResult() kk = LineAlpha.LINE() kk.login...
test_ae.py
"""Tests for the ae module.""" import logging import os import signal import threading import time import pytest from pydicom import read_file from pydicom.dataset import Dataset from pydicom.uid import UID, ImplicitVRLittleEndian from pynetdicom import ( AE, build_context, _config, debug_logger, ...
mainwindow.py
# -*- coding: utf-8 -*- # # Copyright © Spyder Project Contributors # Licensed under the terms of the MIT License # (see spyder/__init__.py for details) """ Spyder, the Scientific Python Development Environment ===================================================== Developped and maintained by the Spyder Pro...
controller.py
# Controller.py # author: Matthew P. Burruss # Adapted from Jason R. Coombs' code here: http://pydoc.net/Python/jaraco.input/1.0.1/jaraco.input.win32.xinput/ under the MIT licence terms # last update: 8/14/2018 # Description: # Provides XBOX controller interface to communicate with DeepNNCar # BUTTON LAYOUT # Ri...
bleak_wrapper.py
# bleak_wrapper.py/Open GoPro, Version 2.0 (C) Copyright 2021 GoPro, Inc. (http://gopro.com/OpenGoPro). # This copyright was auto-generated on Tue Sep 7 21:35:53 UTC 2021 """Manage a Bluetooth connection using bleak.""" import asyncio import logging import threading from typing import Pattern, Dict, Any, Callable, O...
cbgen.py
import itertools import json from random import choice, randint, shuffle from threading import Thread from time import sleep, time import requests import urllib3 from couchbase import experimental, subdocument from couchbase.bucket import Bucket from couchbase.exceptions import ( ConnectError, CouchbaseError, ...
parasol.py
#!/usr/bin/env python #Copyright (C) 2011 by Benedict Paten (benedictpaten@gmail.com) # #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 the rig...
upnp.py
import logging import threading from queue import Queue from typing import Optional try: import miniupnpc except ImportError: pass log = logging.getLogger(__name__) class UPnP: thread: Optional[threading.Thread] = None queue: Queue = Queue() def __init__(self): def run(): t...
adm_server.py
import os import json import hashlib import datetime import time import zipfile import shutil import traceback import sqlite3 import zlib import base64 from threading import Thread, Lock from operator import itemgetter from esprima import parseScript, nodes import jam.common as common from jam.common import error_mess...
DarkFB.py
# -*- coding: utf-8 -*- import os, sys, time, datetime, random, hashlib, re, threading, json, getpass, urllib, requests, mechanize from multiprocessing.pool import ThreadPool try: import mechanize except ImportError: os.system('pip2 install mechanize') else: try: import requests except ImportEr...
sensor.py
"""Sensor to monitor incoming/outgoing phone calls on a Fritz!Box router.""" import logging import socket import threading import datetime import time import re import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( CONF_HOST, CONF_PORT, CONF...
azure_cloud_api.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This module creates API for getting reported property from azure device twin and updating desired property in device twin. Copyright (c) 2019, Wipro Technology License: Proprietary """ __author__ = 'Chetan Gomase' __version__ = '0.1' __credits__ = ["Chetan Gomase"] _...
websockets.py
#!/usr/bin/env python # # Electrum - lightweight Bitcoin client # Copyright (C) 2015 Thomas Voegtlin # # 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...
test_tcp.py
# Copied from the uvloop project. If you add a new unittest here, # please consider contributing it to the uvloop project. # # Portions copyright (c) 2015-present MagicStack Inc. http://magic.io import asyncio import socket import sys import threading import pytest import uvloop import _testbase as tb class MyBa...
views.py
import os import threading from django.contrib.auth.decorators import login_required from django.http import HttpResponse, Http404, JsonResponse from django.shortcuts import render, redirect from django.conf import settings from django.utils.datastructures import MultiValueDictKeyError from core import utilities as c...
test_command.py
from .. import * import unittest import threading import time class CommandTests(unittest.TestCase): """Test suite for the command module""" def testCommand(self): c = Command(-1, -2, -3, [-1]) self.assertEquals(-1, c.delta) self.assertEquals(-2, c.decision) self.assertEquals(...
metlinkpid_http.py
""" Usage: metlinkpid-http [--serial=PORT] [--http=HOST:PORT] metlinkpid-http (-h | --help) Options: --serial=PORT The PID serial port [default: /dev/ttyUSB0]. Can be set using environment variable METLINKPID_SERIAL. --http=HOST:PORT The hostname/IP address and port to listen on [default: 12...
check_gas_collateral.py
# -*- coding:utf-8 -*- from PythonMiddleware.notify import Notify from PythonMiddleware.graphene import Graphene from PythonMiddlewarebase.operationids import operations import sys import pymongo import datetime from time import sleep from collections import deque from threading import Thread, Lock from config import...
proxy2.py
# -*- coding: utf-8 -*- # # # This code originated from the project https://github.com/inaz2/proxy2 but has since # been modified extensively. # # import base64 import re import socket import ssl import threading import urllib.parse from http.client import HTTPConnection, HTTPSConnection from http.server import BaseH...
pyrebase.py
import requests from requests import Session from requests.exceptions import HTTPError try: from urllib.parse import urlencode, quote except: from urllib import urlencode, quote import json import math from random import uniform import time from collections import OrderedDict from pyre_sseclient import SSEClie...
test_auth.py
############################################################################## # Copyright 2018 Rigetti Computing # # 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://ww...
inference_images.py
""" Inference images: Extract matting on images. Example: python inference_images.py \ --model-type mattingrefine \ --model-backbone resnet50 \ --model-backbone-scale 0.25 \ --model-refine-mode sampling \ --model-refine-sample-pixels 80000 \ --model-checkpoint "PATH...
TCppServerTestManager.py
# Copyright (c) Facebook, Inc. and its affiliates. # # 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 ...
subscriber.py
#!/usr/bin/env python # Copyright 2016 Google Inc. 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...
controller_manager.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Software License Agreement (BSD License) # # Copyright (c) 2010, Antons Rebguns, Cody Jorgensen, Cara Slutter # 2010-2011, Antons Rebguns # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are perm...
rabbitmq_monitor.py
#!/usr/bin/env python #-*-coding:utf-8-*- ''' @summary: RabbitMQ Monitor @author: Hom @version: 1.0 @since: 2020-07-16 @note: linux backend run: nohup python rabbitmq_monitor.py > /dev/null 2>&1 & ''' import sys # validate python version if sys.version_info[0] < 2 or (sys.version_info[2] == 2 and sys.ver...
test__xxsubinterpreters.py
from collections import namedtuple import contextlib import itertools import os import pickle import sys from textwrap import dedent import threading import time import unittest from test import support from test.support import import_helper from test.support import script_helper interpreters = import_helper.import_...
mock_httpd.py
#!/usr/bin/env python # Using BaseHTTPServer for mocking servers from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler from threading import Thread from time import sleep, time from urllib import urlopen import httplib import re def wait_for_server(url, timeout=5): '''Wait for server to become available....
synflood.py
import sys,random,socket,time from scapy.all import * from threading import Thread def randInt(): x = random.randint(1,65535) # TCP ports return x def sendPacket(target,port,zombie_ip): sport = randInt() # RANDOM SOURCE PORT seq = randInt() window = randInt() IP_PACKET = IP()...
sttConverter.py
#import argparse from ws4py.client.threadedclient import WebSocketClient import threading import sys import urllib.request, urllib.parse, urllib.error import queue import json import time import os import utils import requests if sys.version_info[0] < 3: raise Exception("Python 3 is required to execute.") def rat...
server.py
#Hakan Reşit YALÇIN - 160401036 import os import socket import sys from threading import Thread HOST = "127.0.0.1" PORT=int(input("PORT NUMARASINI GİRİNİZ : ")) def SOCKET_OLUSTUR(): try: global HOST global PORT global sd sd = socket.socket(socket.AF_INET, socket.SOCK_ST...
test_grammar.py
import math import re import threading import time from typing import Any, Callable, List, Optional, Set, Tuple import antlr4 from pytest import mark, param, raises, warns from omegaconf import ( AnyNode, Container, DictConfig, ListConfig, OmegaConf, _utils, grammar_parser, grammar_vis...
tpu_estimator.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...
executorwebdriver.py
import json import os import socket import threading import time import traceback import urlparse import uuid from .base import (CallbackHandler, RefTestExecutor, RefTestImplementation, TestharnessExecutor, extra_timeout, st...
models.py
import threading import time from django.db import models from django.db import transaction class Item(models.Model): stock = models.IntegerField(default=0) price = models.PositiveIntegerField(default=0) last_modify_date = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_ad...
get_rmp_comments_all.py
#! /usr/bin/env python # -*- coding: utf-8 -*- # >> # Copyright (c) 2016, Blake VandeMerwe - Vivint, inc. # # 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 restr...
7_candy.py
# 使用锁和信号量来模拟一个糖果机 from atexit import register from random import randrange from threading import BoundedSemaphore, Lock, Thread from time import sleep, ctime lock = Lock() MAX = 5 candytray = BoundedSemaphore(MAX) def refill(): lock.acquire() print("Refilling candy...", end=" ") try: candytray.re...
pydoc.py
#!/usr/bin/env python # -*- coding: latin-1 -*- """Generate Python documentation in HTML or text for interactive use. In the Python interpreter, do "from pydoc import help" to provide online help. Calling help(thing) on a Python object documents the object. Or, at the shell command line outside of Python: ...
nightminer.py
# The MIT License (MIT) # # Copyright (c) 2014 Richard Moore # # 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 the rights # to use, copy, mod...
scheduler.py
""" SleekXMPP: The Sleek XMPP Library Copyright (C) 2010 Nathanael C. Fritz This file is part of SleekXMPP. See the file LICENSE for copying permission. """ import time import threading import logging try: import queue except ImportError: import Queue as queue log = logging.getLogger(__name...
views.py
from django.shortcuts import render, reverse, get_object_or_404, redirect from django.http import HttpResponse, HttpResponseRedirect from .forms import UserForm, AbstractForm, PaperForm, AbstractReviewForm, PaperReviewForm, ParticipantProfileForm, AssignProfessorForm, AbstractReUploadForm, PaperAbstractNewForm from dja...
thread.py
#!/usr/bin/env python3 import threading import time import config import eblocbroker.Contract as Contract import PySimpleGUI as sg """ DESIGN PATTERN - Multithreaded Long Tasks GUI using shared global variables Presents one method for running long-running operations in a PySimpleGUI environment. The PyS...
downloadclient.py
# Copyright 2018 CERN for the benefit of the ATLAS collaboration. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
usage_statistics.py
import atexit import datetime import json import logging import platform import signal import sys import threading from functools import wraps from queue import Queue import jsonschema import requests from great_expectations import __version__ as ge_version from great_expectations.core import nested_update from great...
sshbf.py
import paramiko,os,sys,socket #Final import threading,time def ssh_connect(passw,code=0): global stop_flag global idpass ssh=paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: ssh.connect(host,port=22,username=username,password=passw) stop_flag=1 ...
stress-test.py
# A stress test program to perform repeated operations in multiple processes. # # 1. Write data between 0 and BATCH_SIZE blocks at a random offset # 2. Read data between 0 and BATCH_SIZE blocks at a random offset # 3. Remove a replica and add it back, causing a rebuild # # Test patterns are stored in shared memory for...
base_events.py
"""Base implementation of event loop. The event loop can be broken up into a multiplexer (the part responsible for notifying us of I/O events) and the event loop proper, which wraps a multiplexer with functionality for scheduling callbacks, immediately or at a given time in the future. Whenever a public API takes a c...
callbacks_test.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...
GthenOneT.py
# SISO program GthenOneT.py # Returns 'yes' if the input string is a member of the language # GthenOneT, and 'no' otherwise. The language GthenOneT consists of # strings s with the following property: there is at least one G # character (say at index n) such that s contains exactly one T # character after n or exactly...
bucket.py
""" Methods for managing S3 Buckets and making them available as local file systems. """ import os import urllib2 import threading from cm.util import misc from cm.services import service_states from cm.util.misc import _if_not_installed from cm.util.decorators import TestFlag import logging log = logging.getLogger('...