source
stringlengths
3
86
python
stringlengths
75
1.04M
measurePerformance.py
#!/usr/bin/env python # ############################################################################# # Copyright (c) 2013 - present Advanced Micro Devices, Inc. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (t...
coordinator_test.py
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
test_client.py
import asyncio import gc import inspect import logging import os import pickle import random import subprocess import sys import threading import traceback import warnings import weakref import zipfile from collections import deque from contextlib import suppress from functools import partial from operator import add f...
bartender.py
import gaugette.ssd1306 import gaugette.platform import gaugette.gpio import time import sys import RPi.GPIO as GPIO import json import threading import traceback import board import neopixel from menu import MenuItem, Menu, Back, MenuContext, MenuDelegate from drinks import drink_list, drink_options GPIO.setmode(GPI...
main2.py
# encoding: utf-8 #这里放置主程序以及IO from numpy import * from utils.tools import loadvoc from keras.models import Sequential,load_model,Model from keras.layers import Input, Reshape,Embedding, LSTM, Dense, merge, RepeatVector,TimeDistributed,Masking,Activation from keras.optimizers import SGD,Adam from keras.utils.np_utils i...
generate_dataset.py
""" ********************************************************************** ********************************************************************** ** author: ZSAIm ** email: zzsaim@163.com ** github: https://github.com/ZSAIm/CNN-Get-Captcha ** ** programming by py...
find_spots_server.py
from __future__ import absolute_import, division, print_function from future import standard_library standard_library.install_aliases() import http.server as server_base import json import logging import sys import time import urllib.parse from multiprocessing import Process import libtbx.phil from dials.util impo...
test_mainwindow.py
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright © Spyder Project Contributors # # Licensed under the terms of the MIT License # (see spyder/__init__.py for details) # ----------------------------------------------------------------------------- """ Te...
main.py
import time import npyscreen from encode import encode_c480, encode_c720 from multiprocessing import Process, Queue, Manager PROCESS_NUM = 10 def encode(task_q, messages, id): while True: messages[id] = 'waiting task' filename = task_q.get() parsed = filename.split('.') fout_480p = "".join(parsed[:-1]) + "_4...
socket_server.py
import socket import threading def process_request(conn, addr): print("connected client:", addr) with conn: while True: data = conn.recv(1024) if not data: break print(data.decode("utf8")) if __name__ == "__main__": with socket.socket() as soc...
test_events.py
"""Tests for events.py.""" import collections.abc import concurrent.futures import functools import io import os import platform import re import signal import socket try: import ssl except ImportError: ssl = None import subprocess import sys import threading import time import errno import unittest from unitt...
threadRecoder.py
from utils.singleton import singleton from utils.log import Log import threading import time logger = Log()() @singleton class threadRecorder(): def __init__(self): self.threads = {} self._lock = threading.Lock() logger.info('threadRecoder 初始化完成') def add(self,tname,func,args,daemon):...
client.py
import socket import threading from sys import argv text_colour_dict = {'green': '\033[0;32m', 'red':'\033[0;31m', 'yellow':'\033[0;33m', 'light_cyan':'\033[96m', 'light_yellow':'\033[93m', 'bright_magenta':'\033[1;35;40m'} local_host = argv[1] port = int(argv[2]) colour = ...
test_state.py
# -*- coding: utf-8 -*- ''' Tests for the state runner ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import errno import logging import os import re import shutil import signal import tempfile import time import textwrap import threading # Import Salt Testing Libs f...
ca.py
import ssl import socket import OpenSSL import sqlite3 import signal from functools import wraps from numpy.core.numeric import count_nonzero import requests from multiprocessing import Process, Value TIMEOUT = Value('i', 5) cMax = Value('i', 2) ca_num = Value('i', 0) class TimeoutException(Exception): pass def ...
serving.py
"""Socket server.""" import logging import socketserver import threading import animation _PORT = 7829 _logger = logging.getLogger('subway_board.serving') class _TCPServer(socketserver.TCPServer): allow_reuse_address = True class Server: """Socket server that sends current frame from ETA image on every con...
tfoo.py
import threading import pub_foo def say_hello(msg): print('Say hello from %s' % msg) def test(): threading.Thread(target=pub_foo.proxy_say_hello, args=('function',)).start() if __name__ == '__main__': threading.Thread(target=pub_foo.proxy_say_hello, args=('module',)).start() test()
presubmit_support.py
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Enables directory-specific presubmit checks to run at upload and/or commit. """ __version__ = '1.8.0' # TODO(joi) Add caching ...
threading_test.py
import threading def calc_square(number, iter): for _ in range(iter): print('Square:' , number * number) def calc_quad(number, iter): for _ in range(iter): print('Quad:' , number * number * number * number) if __name__ == "__main__": number = 7 thread1 = threading.Thread(target=calc_quad, args=(number, 100...
test_cli.py
#!/usr/bin/python """ (C) 2018,2019 Jack Lloyd Botan is released under the Simplified BSD License (see license.txt) """ import subprocess import sys import os import logging import optparse # pylint: disable=deprecated-module import time import shutil import tempfile import re import random import json import binasc...
ansible.py
from multiprocessing import Process, Queue from Queue import Empty from ansible_server import ansible_server # DON'T USE THIS UNLESS YOU KNOW WHAT YOU'RE DOING # Low level message sending. For high level messaging, use send_msg. def send(msg): send_queue.put_nowait(msg) # Use this one instead of send def send_mes...
gerenciador_de_manager.py
import threading from requests import get, post from time import sleep TEMPO_POR_companhia_EM_S = 5 #quantidade de tempo que será destinada a cada companhia class Gerenciador_de_manager: def __init__(self, companhias:dict, trajetos_para_reservar:list, who_am_i:str, semaphore_de_liberação_resolver_pedidos:threadin...
rosbag_cli_recording_1_generate_output.py
#!/usr/bin/env python import roslib import rospy import smach import smach_ros from geometry_msgs.msg import Point from geometry_msgs.msg import Point32 from geometry_msgs.msg import PointStamped from geometry_msgs.msg import Pose from geometry_msgs.msg import PoseStamped from geometry_msgs.msg import Quate...
find_stable.py
import argparse #for getting command line arguments import os #for various things from selenium import webdriver, common #for getting html source of channel from time import sleep #to prevent errors import re ...
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...
test_reducer.py
import itertools import logging import threading import traceback from collections import namedtuple from typing import Any, Callable, List import numpy as np import pytest from determined import _core from determined.pytorch import Reducer, _PyTorchReducerContext, _simple_reduce_metrics logger = logging.getLogger(_...
tasks.py
# -*- coding: utf-8 -*- # Copyright (c) 2015 Ansible, Inc. # All Rights Reserved. # Python from collections import OrderedDict, namedtuple, deque import errno import functools import importlib import json import logging import os import shutil import stat import tempfile import time import traceback from distutils.di...
server.py
# -*- coding: utf-8 -*- # MegEngine is Licensed under the Apache License, Version 2.0 (the "License") # # Copyright (c) 2014-2021 Megvii Inc. All rights reserved. # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTI...
remind.py
""" remind.py - Willie Reminder Module Copyright 2011, Sean B. Palmer, inamidst.com Licensed under the Eiffel Forum License 2. http://willie.dftba.net """ import os import re import time import threading import collections import codecs from datetime import datetime from willie.module import commands, example, NOLIMI...
hooks.py
# Based on: # https://stackoverflow.com/a/31396340 from ctypes import * from ctypes.wintypes import * user32 = WinDLL('user32', use_last_error=True) HC_ACTION = 0 WH_MOUSE_LL = 14 WM_QUIT = 0x0012 WM_MOUSEMOVE = 0x0200 WM_LBUTTONDOWN = 0x0201 WM_LBUTTONUP = 0x0202 WM_RBUTTONDOWN = 0x0204 WM_RBUTTONUP ...
app.py
""" A REST API for Salt =================== .. py:currentmodule:: salt.netapi.rest_cherrypy.app .. note:: This module is Experimental on Windows platforms and supports limited configurations: - doesn't support PAM authentication (i.e. external_auth: auto) - doesn't support SSL (i.e. disable_ssl: Tru...
batocera_safeshutdown.py
#!/usr/bin/python # -*- coding: utf-8 -*- import RPi.GPIO as GPIO import os import time import subprocess from multiprocessing import Process #initialize pins powerPin = 3 #pin 5 ledPin = 14 #TXD - pin 8 resetPin = 2 #pin 3 powerenPin = 4 #pin 7 #initialize GPIO settings def init(): GPIO.setwarnings(False) GPIO.se...
conftest.py
import os import json from multiprocessing import Process from indexd import default_settings, get_app as get_indexd_app from indexclient.client import IndexClient import pytest import requests import requests_mock from mock import patch from psqlgraph import PsqlGraphDriver from dictionaryutils import DataDictionary,...
utils.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import cv2 import os import numpy as np import threading __all__ = [ 'load_image', 'save_image', 'load_images', 'save_images', ] def load_image(path): '''Load an image Parameters ---------- path : str path of the image. Retu...
automation.py
# TODO: Trigger refresh on variable configuration update # TODO: Watch multiple folders if not all under parent folder # TODO: Consider whether to send partial updates for variables # TODO: Precompile notebook scripts import logging import subprocess from invisibleroads_macros_disk import is_path_in_folder, make_folder...
alexa.py
# -*- coding: utf-8 -*- import base64 import cgi import json import logging import os import signal import sys import tempfile import threading import uuid if sys.version_info < (3, 0): import Queue as queue else: import queue import requests import datetime import hyper from avs.mic import Audio from avs...
main.py
# ============================================================================================ # MIT License # Copyright (c) 2020 Konstantinos Bourantas # 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 th...
GAParallel.py
# this is the parallelized version of GA.py. Parallelized by Matteo Bjornsson, original code written by Nick Stone ################################################################################ import random import Performance from NeuralNetwork import NeuralNetwork import DataUtility import numpy as np import copy ...
support.py
""" Assorted utilities for use in tests. """ import cmath import contextlib import enum import errno import gc import math import platform import os import shutil import subprocess import sys import tempfile import time import io import ctypes import multiprocessing as mp import warnings import traceback from contextl...
BoMbEr.py
# -*- coding: utf-8 -*- #!/usr/bin/env python """ ╔═════════════════════════════════════════════════════════════════════════════════╗ ║ ║ ║ BoMbEr ║ ║ Author:...
smart_alarm.py
""" This module is a program that simulates a Smart Alarm as a Web Sever. """ import os from datetime import datetime, timedelta import calendar import sched import time import json import threading import logging.config import pyttsx3 import requests from flask import Flask, render_template, request, redirect, url_for...
tests.py
#!/usr/bin/python # -*- coding: utf-8 -*- from subprocess import call import os import shutil import time import unittest import errno import random import uuid import threading import stat import subprocess import shlex import datetime LOCAL_TEST = 0 ADLS_TEST = 0 print ("Local Testing Enabled : " + str(LOCAL_TEST)) ...
train.py
#!/usr/bin/env python """ Main training workflow """ from __future__ import division import argparse import os import random import signal import torch import distributed import numpy as np from transformers import BertTokenizer from models import data_loader from models.data_loader import load_dataset from model...
circuit_design V2.py
# python3 #https://www.geeksforgeeks.org/2-satisfiability-2-sat-problem/ #https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm #https://stackoverflow.com/questions/4664050/iterative-depth-first-tree-traversal-with-pre-and-post-visit-at-each-node/60803684#60803684 import sys import threadin...
sleep_sort.py
# !/usr/bin/env python3 from time import sleep from random import randint from threading import Thread def target(n, value): global sorted_list sleep(n) sorted_list.append(value) unsort_list, sorted_list = [randint(-100, 100) for _ in range(randint(10, 20))], [] max_value, min_value = unsort_list[0], unsort_list[0...
s3.py
""" Object Store plugin for the Amazon Simple Storage Service (S3) """ import logging import multiprocessing import os import shutil import subprocess import threading import time from datetime import datetime from galaxy.exceptions import ObjectNotFound, ObjectInvalid from galaxy.util import string_as_bool, umask_f...
train_vqa.py
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import h5py import time import argparse import numpy as np import os, sys, json import torch from torch.autograd...
demo.py
import argparse import os import sys import time from dataclasses import dataclass from PIL import Image, ImageChops, ImageDraw, ImageFont from typing import List, Tuple, Iterator import cv2 from PyQt5.QtCore import pyqtSignal, QThread, QObject from PyQt5.QtWidgets import QApplication import core as pr import numpy a...
local_executor.py
"""Local based implementation of the executor using multiprocessing""" import signal from multiprocessing import Process, Queue try: from queue import Empty except ImportError: from Queue import Empty try: import psutil except ImportError: psutil = None from . import executor def kill_child_proces...
ssh.py
from __future__ import absolute_import from __future__ import division import inspect import logging import os import re import shutil 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 import Log...
runner.py
#!/usr/bin/env python3 # Copyright 2016 The Kubernetes 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...
miniterm.py
#!/usr/bin/python # Very simple serial terminal # (C)2002-2011 Chris Liechti <cliechti@gmx.net> # Input characters are sent directly (only LF -> CR/LF/CRLF translation is # done), received characters are displayed as is (or escaped trough pythons # repr, useful for debug purposes) import sys, os, serial, threading ...
server.py
# SERVER try: import socket import ssl import os import errno import time import datetime import json import subprocess import threading import glob import shutil except ImportError: raise ImportError("You need to do 'pip install -r requirements.txt' to be a...
grpc_comm_manager.py
import logging from typing import List from concurrent import futures import threading import grpc from ..gRPC import grpc_comm_manager_pb2_grpc, grpc_comm_manager_pb2 lock = threading.Lock() from FedML.fedml_core.distributed.communication.base_com_manager import BaseCommunicationManager from FedML.fedml_core.dist...
process_id.py
#!/usr/bin/python from multiprocessing import Process import os # getting parent and child process Ids def fun(): print('--------------------------') print('calling fun') print('parent process id:', os.getppid()) print('process id:', os.getpid()) def main(): print('main fun') print('proc...
background_caching_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 us...
helpers.py
"""Supporting functions for polydata and grid objects.""" import collections.abc import ctypes import enum import logging import signal import warnings from threading import Thread import threading import numpy as np import scooby import vtk import vtk.util.numpy_support as nps import pyvista from .fileio import fro...
Library.py
# pylint: skip-file # -*- coding: utf-8 -*- # Module: LibraryExporter # Created on: 13.01.2017 import os import re import time import threading import xbmc import xbmcgui import xbmcvfs import requests from utils import noop from KodiHelper import KodiHelper try: import cPickle as pickle except: import pickle ...
movo_arm_jtas.py
"""-------------------------------------------------------------------- Copyright (c) 2017, Kinova Robotics inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code mus...
coglib.py
import json from threading import Thread from typing import Optional, Callable, Union from discord.ext.commands import Context from discord_slash import SlashContext from flask import Flask, jsonify, request, Response from requests import post from .classes import CogPlus, BotPlus from .database.translation import Tr...
Client2.py
import socket import threading from queue import Queue NUMBER_OF_THREAD = 2 JOBS = [1, 2] queue = Queue() s = socket.socket() host = '127.0.0.1' #write host server IP port = 5000 s.connect((host, port)) def send_message(): while True: try: #print("Yeah im coming here") messa...
test_utils_test.py
import asyncio import os import pathlib import signal import socket import threading from contextlib import contextmanager from time import sleep import pytest import yaml from tornado import gen import dask.config from distributed import Client, Nanny, Scheduler, Worker, config, default_client from distributed.comp...
monobeast.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 ...
minion.py
# -*- coding: utf-8 -*- ''' Routines to set up a minion ''' # Import python libs from __future__ import absolute_import, print_function import os import re import sys import copy import time import errno import types import signal import fnmatch import hashlib import logging import threading import traceback import mul...
work_simulator.py
''' Copyright (C) 2021 S[&]T, The Netherlands. ''' import multiprocessing import os import sys import tempfile import time _MB = 2**20 class WorkSimulator: ''' This class is responsible for consuming memory, CPU cycles and disk space. It allocates memory and launches additional processes for each next C...
mudpi.py
import RPi.GPIO as GPIO import threading import datetime import socket import time import json import sys sys.path.append('..') from action import Action from config_load import loadConfigJson from server.mudpi_server import MudpiServer from workers.lcd_worker import LCDWorker from workers.relay_worker import RelayWork...
market_price.py
#|----------------------------------------------------------------------------- #| This source code is provided under the Apache 2.0 license -- #| and is provided AS IS with no warranty or guarantee of fit for purpose. -- #| See the project's LICENSE.md for details. -- ...
ddp.py
# DDP galicaster plugin # # Source: # github SussexLearningSystems/peakaboo # /docs/capture_agent_plugins/examples/galicaster_2_manchester/ddp.py # Commit: 484abe9 # # Copyright (c) 2016 University of Sussex # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and as...
sandbox.py
#!/usr/bin/python from __future__ import print_function import os import shlex import signal import subprocess import sys import time from optparse import OptionParser from threading import Thread try: from Queue import Queue, Empty except ImportError: from queue import Queue, Empty # make python 3.x compatible with...
thread_test.py
import threading import time from threading import current_thread def myThread(arg1, arg2): print(current_thread().getName, 'start') print('%s %s'%(arg1, arg2)) time.sleep(1) print(current_thread().getName, 'stop') for i in range(1, 6, 1): t1 = threading.Thread(target=myThread, args=(i, i+1)) ...
gui.py
from __future__ import unicode_literals import Queue import datetime import errno import gettext import itertools import json import locale import os import subprocess import sys import threading import wx import openslides from openslides.utils.main import ( detect_openslides_type, filesystem2unicode, ...
__init__.py
# package is named tests, not test, so it won't be confused with test in stdlib from __future__ import print_function import contextlib import errno import functools import gc import json import os try: import resource except ImportError: resource = None import signal try: import subprocess32 as subprocess...
graphicsCrawlerDisplay.py
# graphicsCrawlerDisplay.py # ------------------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link t...
pcwbot.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ pcwbot - An automated game server bot http://www.spunkybot.de/pcwbot Author: Alexander Kress This program is released under the MIT License. See LICENSE for more details. ## About ## pcwbot is a scaled down version of Spunky Bot, the lightweight game server administr...
client.py
import socket import select import threading import json import sys import traceback import os import random from clientInterface import ClientInterface from constants import CREATE_CHANNEL, SUBSCRIBE_CHANNEL, UNSUBSCRIBE_CHANNEL, SHOW_MY_SUBS, PUBLISH_CHANNEL, SHOW_MY_CHANNELS, SHOW_ALL_CHANNELS from constants import...
calypso_server.py
import socket import threading import logging logger = logging.getLogger(__name__) TARGET_SOCK_ADDR = ('127.0.0.1', 8080) client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.bind(TARGET_SOCK_ADDR) clients = [] def send_data(): threading.Timer(20.0, send_data).start() for c in...
host_callback_test.py
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
web_10.py
from web_06 import WSGIApplication app = WSGIApplication() class RestController: def __call__(self, req, resp): method = req.environ['REQUEST_METHOD'] action = getattr(self, method, self._not_found) return action(req, resp) def _not_found(self, environ, resp): resp.status = ...
variable_scope.py
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
utils.py
import concurrent.futures import logging import os import re import shutil import subprocess as sp import threading import time from urllib.request import urlretrieve import anndata import ngs_tools as ngs import pandas as pd import scipy.io from scipy import sparse from tqdm import tqdm from .config import ( get...
client.py
""" ScopeOut GUI Defines GUI client that instantiates and controls widgets and threads. """ # Set matplotlib to call PyQt5 from matplotlib import rcParams rcParams['backend'] = 'Qt5Agg' import threading import os import logging from datetime import date, datetime from functools import partial from PyQt5 import QtWi...
infinite-image-scroller.py
#!/usr/bin/env python3 import itertools as it, operator as op, functools as ft import pathlib as pl, collections as cs, dataclasses as dc import os, sys, re, logging, enum, textwrap, random, signal import gi gi.require_version('Gtk', '3.0') gi.require_version('Gdk', '3.0') gi.require_version('GLib', '2.0') gi.require...
panelMain.py
# Qt from PyQt5.Qt import pyqtSlot # Basics from threading import Thread, ThreadError # Dependencies from panel.workstations.panel_common import CommonWorkstation from panel.workstations.panel_router import RouterConfiguration from panel.workstations.panel_networks import NetworksConfiguration from panel.common.Comm...
utils.py
# Copyright 2016-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import torch, glob, os, numpy as np, math from .sparseConvNetTensor import SparseConvNetTensor from .metadata import Metada...
gui.py
#!/usr/bin/env python3 import os import json import time import threading import multiprocessing from PyQt5 import QtCore, QtWidgets, uic from PyQt5.QtGui import QIcon from tools.exceptions import ValidationError, MissingValuesError from tools.gui import oeffne_file_dialog_select from tools.gui.qtzeiten import QtZeit...
physical_input.py
from threading import Thread import os import time from time import sleep import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) # use board pin number (consecutive) instead of GPIO numbers. def safe_shutdown(): PRE_SHUTDOWN_CMDS= [ "pkill -e --signal SIGINT gst-launch-1.0", # send SIGINT will trigger End of...
thread.py
from threading import Event, Thread from febo.algorithms import Algorithm import sys class ThreadAlgorithm(Algorithm): """ This algorithms runs a minimize route in a separate thread. Using this base class, one can easily adapt existing `minimize` (like scipy's optimize.minimize), which by ...
processor.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
_server.py
# Copyright 2016 gRPC 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 or agreed to in writing...
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...
test_sock.py
""" * Test whether multiple recvs on the same connection (non-blocking) will eventually have the connection closed (use another net instance.) * Test whether multiple sends on the same connection (non-blocking) will eventually lead to the connection being closed (use a net instance with no recvs! and loop over the ...
main.py
import os import time import sys from itertools import chain from core.db import Db from core.util import sha256sum, scale, progress, sum_n from core.thread import StartThread from core.extractor import get_all_features, get_distance class Main: def __init__(self, db_name): """ Constructor for M...
astra.py
import argparse import base64 import json import requests import time import ast import utils.logger as logger import utils.logs as logs import urlparse from core.zapscan import * from core.parsers import * from utils.logger import * from core.login import APILogin from utils.logger import logger from utils.config im...
views.py
from django.shortcuts import render from django.http import HttpResponse import os import time import threading #def detached(argc, argv): def show(request): #argc = 22 #argv = 10 #t = threading.Thread(target = detached, args = (argc, argv)) #t.daemon = True #t.start() return render(request, 'notepad/index.html...
mp.py
# coding: utf8 """ 并行计算模块 原理: 并行版本的实现说明: 1 标准生产者\消费者模型 2 生产者处于线程中, 将任务迭代器的内容写入任务队列中,并置结束标志 3 消费者多个进程, 读取task_queue的内容, 并返回result到done_queue中 4 主线程监控done_queue的内容, 并插入数据库(保持gInst的事务), 直到整个任务结束 """ from multiprocessing import Process, Queue, current_process, cpu_count im...
client.py
import socket import threading class Client: server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) userName = input("Username: ") def sendMsg(self): while True: self.server.send(bytes(f"[{self.userName}] " + input(""), 'utf-8')) def __init__(self, ip, port): self.ser...
base.py
# Copyright 2017 D-Wave Systems Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
output.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 codecs import os import sys import threading from debugpy impor...
exercise7.py
#!/usr/bin/env python from net_system.models import NetworkDevice, Credentials from netmiko import ConnectHandler from datetime import datetime from multiprocessing import Process, current_process import django def show_ver(device): creds = device.credentials conn_dev = ConnectHandler( device_type=d...
parallel.py
# coding: utf-8 # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License...