source stringlengths 3 86 | python stringlengths 75 1.04M |
|---|---|
speaker.py | # noinspection PyUnresolvedReferences
"""Module for speaker and voice options.
>>> Speaker
"""
import os.path
import re
import sys
from datetime import datetime
from threading import Thread
from typing import NoReturn, Union
import pyttsx3
import requests
import yaml
from playsound import playsound
from executors.logger import logger
from modules.conditions import conversation, keywords
from modules.models import models
from modules.utils import shared
fileio = models.FileIO()
env = models.env
audio_driver = pyttsx3.init()
KEYWORDS = [__keyword for __keyword in dir(keywords) if not __keyword.startswith('__')]
CONVERSATION = [__conversation for __conversation in dir(conversation) if not __conversation.startswith('__')]
FUNCTIONS_TO_TRACK = KEYWORDS + CONVERSATION
def speech_synthesizer(text: str, timeout: Union[int, float] = env.speech_synthesis_timeout,
quality: str = "high", voice: str = "en-us_northern_english_male-glow_tts") -> bool:
"""Makes a post call to docker container for speech synthesis.
Args:
text: Takes the text that has to be spoken as an argument.
timeout: Time to wait for the docker image to process text-to-speech request.
quality: Quality at which the conversion is to be done.
voice: Voice for speech synthesis.
Returns:
bool:
A boolean flag to indicate whether speech synthesis has worked.
"""
logger.info(f"Request for speech synthesis: {text}")
if time_in_str := re.findall(r'(\d+:\d+\s?(?:AM|PM|am|pm:?))', text):
for t_12 in time_in_str:
t_24 = datetime.strftime(datetime.strptime(t_12, "%I:%M %p"), "%H:%M")
logger.info(f"Converted {t_12} -> {t_24}")
text = text.replace(t_12, t_24)
if 'IP' in text.split():
ip_new = '-'.join([i for i in text.split(' ')[-1]]).replace('-.-', ', ') # 192.168.1.1 -> 1-9-2, 1-6-8, 1, 1
text = text.replace(text.split(' ')[-1], ip_new).replace(' IP ', ' I.P. ')
try:
response = requests.post(url=f"http://{env.speech_synthesis_host}:{env.speech_synthesis_port}/api/tts",
headers={"Content-Type": "text/plain"},
params={"voice": voice, "quality": quality},
data=text, verify=False, timeout=timeout)
if response.ok:
with open(file=fileio.speech_synthesis_wav, mode="wb") as file:
file.write(response.content)
return True
logger.error(f"{response.status_code}::http://{env.speech_synthesis_host}:{env.speech_synthesis_port}/api/tts")
return False
except (requests.exceptions.ConnectionError, requests.exceptions.Timeout, UnicodeError) as error:
# Timeout exception covers both connection timeout and read timeout
logger.error(error)
def speak(text: str = None, run: bool = False, block: bool = True) -> NoReturn:
"""Calls ``audio_driver.say`` to speak a statement from the received text.
Args:
text: Takes the text that has to be spoken as an argument.
run: Takes a boolean flag to choose whether to run the ``audio_driver.say`` loop.
block: Takes a boolean flag to wait other tasks while speaking. [Applies only for larynx running on docker]
"""
caller = sys._getframe(1).f_code.co_name # noqa
if text:
text = text.replace('\n', '\t').strip()
logger.info(f'Speaker called by: {caller}')
shared.text_spoken = text
if shared.called_by_offline:
shared.offline_caller = caller
return
logger.info(f'Response: {text}')
sys.stdout.write(f"\r{text}")
if env.speech_synthesis_timeout and \
speech_synthesizer(text=text) and \
os.path.isfile(fileio.speech_synthesis_wav):
playsound(sound=fileio.speech_synthesis_wav, block=block)
os.remove(fileio.speech_synthesis_wav)
else:
audio_driver.say(text=text)
if run:
audio_driver.runAndWait()
Thread(target=frequently_used, kwargs={"function_name": caller}).start() if caller in FUNCTIONS_TO_TRACK else None
def frequently_used(function_name: str) -> NoReturn:
"""Writes the function called and the number of times into a yaml file.
Args:
function_name: Name of the function that called the speaker.
See Also:
- This function does not have purpose, but to analyze and re-order the conditions' module at a later time.
"""
if os.path.isfile(fileio.frequent):
try:
with open(fileio.frequent) as file:
data = yaml.load(stream=file, Loader=yaml.FullLoader) or {}
except yaml.YAMLError as error:
data = {}
logger.error(error)
if data.get(function_name):
data[function_name] += 1
else:
data[function_name] = 1
else:
data = {function_name: 1}
with open(fileio.frequent, 'w') as file:
yaml.dump(data={k: v for k, v in sorted(data.items(), key=lambda x: x[1], reverse=True)},
stream=file, sort_keys=False)
|
worker.py | import os
import argparse
import pickle
import time
import zmq
from legacypipe.oneblob import one_blob
def run(server):
cluster = os.environ.get('SLURM_CLUSTER_NAME', '')
jid = os.environ.get('SLURM_JOB_ID', '')
aid = os.environ.get('SLURM_ARRAY_TASK_ID', '')
ajid = os.environ.get('SLURM_ARRAY_JOB_ID', '')
nid = os.environ.get('SLURM_NODEID', '')
print('SLURM_CLUSTER_NAME', cluster)
print('SLURM_JOB_ID', jid)
print('SLURM_ARRAY_TASK_ID', aid)
print('SLURM_ARRAY_JOB_ID', ajid)
print('SLURM_NODEID', nid)
import socket
me = socket.gethostname()
print('Hostname', me)
if len(cluster + jid + aid) == 0:
jobid = me + '_' + 'pid' + str(os.getpid())
else:
if len(aid):
jobid = '%s_%s_%s_%s_%s' % (cluster, ajid, aid, nid, me)
else:
jobid = '%s_%s_%s_%s' % (cluster, jid, nid, me)
jobid = jobid.encode()
print('Setting jobid', jobid)
print('Connecting to', server)
ctx = zmq.Context()
sock = ctx.socket(zmq.REQ)
sock.connect(server)
req = None
meta = None
tprev_wall = time.time()
while True:
msg = pickle.dumps(req, -1)
meta_msg = pickle.dumps(meta, -1)
print('Sending', len(msg))
sock.send_multipart([jobid, meta_msg, msg])
rep = sock.recv()
print('Received reply:', len(rep), 'bytes')
rep = pickle.loads(rep)
#print('Reply:', rep)
if rep is None:
print('No work assigned!')
req = None
time.sleep(5)
continue
#break
(brickname, iblob, args) = rep
# DEBUG
# (nblob, iblob, Isrcs, brickwcs, bx0, by0, blobw, blobh, blobmask, timargs,
# srcs, bands, plots, ps, reoptimize, iterative, use_ceres, refmap,
# large_galaxies_force_pointsource, less_masking, frozen_galaxies) = args
(_, iblob, Isrcs, _, _, _, blobw, blobh, _, timargs,
_, _, _, _, _, _, _, _,
_, _, _) = args
print('Work: brick', brickname, 'blob', iblob, 'size', blobw, 'x', blobh, 'with',
len(timargs), 'images and', len(Isrcs), 'sources')
print('Calling one_blob...')
t0_wall = time.time()
t0_cpu = time.process_time()
result = one_blob(args)
t1_cpu = time.process_time()
t1_wall = time.time()
overhead = t0_wall - tprev_wall
tprev_wall = t1_wall
# send our answer along with our next request for work!
req = result
meta = (brickname, iblob, t1_cpu-t0_cpu, t1_wall-t0_wall, overhead)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('server', nargs=1, help='Server URL, eg tcp://edison08:5555')
parser.add_argument('--threads', type=int, help='Number of processes to run')
opt = parser.parse_args()
server = opt.server[0]
if opt.threads:
from multiprocessing import Process
procs = []
for i in range(opt.threads):
p = Process(target=run, args=(server,))
p.start()
procs.append(p)
for i,p in enumerate(procs):
p.join()
print('Joined process', (i+1), 'of', len(procs))
else:
run(server)
print('All done!')
if __name__ == '__main__':
main()
|
djqueue.py | # Import Libraries
import asyncio
import threading
import discord_bot.discord_bot as discord_bot
from twitchbot import BaseBot
import json
import log_system
def DiscordBot(secrets):
logger.info("Started Discord Thread")
discordloop = asyncio.new_event_loop()
asyncio.set_event_loop(discordloop)
asyncio.get_event_loop()
bot = discord_bot.Bot(secrets)
discordloop.create_task(bot.start(secrets["DiscordBotToken"]))
logger.info("Starting Discord Loop")
discordloop.run_forever()
def TwitchBot():
logger.info("Started Twitch Thread")
relayloop = asyncio.new_event_loop()
asyncio.set_event_loop(relayloop)
asyncio.get_event_loop()
relayloop.create_task(BaseBot().run())
logger.info("Starting Twitch Loop")
relayloop.run_forever()
if __name__ == '__main__':
# Open secrets.json file for Tokens
with open("secrets.json", "r") as file:
secrets = json.load(file)
logger = log_system.Main()
# Setup Thread for Discord Bot
DiscordThread = threading.Thread(target=DiscordBot, args=(secrets, ))
DiscordThread.daemon = False
DiscordThread.start()
# Setup Thread for Twitch Bot
TwitchThread = threading.Thread(target=TwitchBot, args=())
TwitchThread.daemon = False
TwitchThread.start()
|
main_1.py | from __future__ import print_function
import time
import numpy as np
import sys
import os
from random import shuffle
from multiprocessing import Queue
from PIL import Image
sys.path.append('..')
from openbci import wifi as bci
import numpy as np
import glob
import matplotlib.pyplot as plt
from multiprocessing import Process
from threading import Thread
can_classify = False
q = Queue()
_q = Queue()
result = Queue()
CLASSIFY_EEG_LEN = 100
START_EEG_LEN = 100
TYPE = ['cat', 'dog']
EEG_LIST = Queue()
def get_file_path():
image_type = TYPE
dir_path = os.path.join(os.path.abspath('.'), 'image')
image_list = []
for type in image_type:
dir_image_path = os.path.join(dir_path, type, '*.jpg')
image_files = glob.glob(dir_image_path)
shuffle(image_files)
for image in image_files:
image_list.append(type + '|' + image)
return image_list
def printData(sample):
if q.qsize() < 2:
q.put(sample.channel_data[0])
_q.put(sample.channel_data[1])
print(sample.channel_data[0])
def proc2(image_list, q, _q):
is_peace = True
data1 = []
data2 = []
peace = []
plt.ion()
fig = plt.figure(figsize=(10, 10))
fig1 = fig.add_subplot(2, 2, 4)
fig2 = fig.add_subplot(2, 2, 3)
fig3 = fig.add_subplot(2, 1, 1)
img_index = 0
eeg_index = 0
while True:
data1.append(q.get())
data2.append(_q.get())
if len(data1) > START_EEG_LEN:
x = np.linspace(0, 1, len(data1))
x1 = np.linspace(0, 1, len(data2))
fig1.cla()
fig2.cla()
fig1.plot(x, data1)
fig2.plot(x1, data2)
s = u'close your eye and keep peace '
if is_peace:
fig3.text(0.5, 0.5, s, fontsize=15, horizontalalignment="center")
# ้้ๅฐๅนณ้ไธ็่็ตๆณขไนๅๆญฃๅผๅผๅงๆต่ฏ
if eeg_index > CLASSIFY_EEG_LEN and img_index < len(image_list):
is_peace = False
t1 = Process(target=classify, args=(data1, data2))
t1.start()
img = Image.open(image_list[img_index].split('|')[1])
fig3.imshow(img)
img_index += 1
eeg_index = 0
elif img_index == len(image_list):
fig.clf()
s = u'data is being processed, please wait '
for i in range(len(s)):
fig.clf()
t_prompt = s[0:i]
fig.text(0.5, 0.5, t_prompt, fontsize=15, horizontalalignment="center")
plt.pause(0.2)
plt.pause(5)
fig.clf()
s = u'the dog is 70% and the cat is 30% '
for i in range(len(s)):
fig.clf()
t_prompt = s[0:i]
fig.text(0.5, 0.5, t_prompt, fontsize=15, horizontalalignment="center")
plt.pause(0.2)
plt.pause(10)
return
data1 = data1[1:]
data2 = data2[1:]
plt.pause(0.00000001)
eeg_index += 1
def classify(EEG_LIST):
while True:
time.sleep(3)
if EEG_LIST.qsize() > 0:
pass
print(99999)
if __name__ == '__main__':
image_list = get_file_path()
# t = Thread(target=classify, args=(EEG_LIST,))
# t.start()
t = Process(target=proc2, args=(image_list, q, _q))
t.start()
shield_name = 'OpenBCI-3F2F'
shield = bci.OpenBCIWiFi(shield_name=shield_name, log=False, high_speed=False)
print("WiFi Shield Instantiated")
shield.start_streaming(printData)
shield.loop()
|
sim800l.py | from time import strftime as now
import threading
import serial
FORMAT = '%Y-%m-%d %H:%M:%S'
ser = serial.Serial('COM4', baudrate=57600)
def log(data, file='sim800.log'):
with open(file, 'a+') as f:
f.write(now(FORMAT) + ' ' + str(data) + '\n')
f.close()
def read_from_port(ser):
while True:
data = ser.readline().rstrip()
print(data)
log(b'<< ' + data)
thread = threading.Thread(target=read_from_port, args=(ser,))
thread.start()
def send(command):
data = bytes(command + "\r", encoding='ascii')
ser.write(data)
log(b'>> ' + data)
while True:
try:
query = input()
if query.upper().startswith("AT"):
send(query)
elif query.upper() == "SEND TIME":
z = float(now("%z")[:3] + '.' + now("%z")[3:]) * 4
time = now("%y/%m/%d,%H:%M:%S") + "{:+03.0f}".format(z)
print("sending time %s" % time)
send('AT+CCLK="%s"' % time)
elif query.upper() == "TIME":
send("AT+CCLK?")
elif query.upper() == "ACTIVATE":
send('AT+CFUN=1')
send('AT+SAPBR=3,1,"CONTYPE","GPRS"')
send('AT+SAPBR=3,1,"APN","telenor"')
send('AT+SAPBR=1,1')
send('AT+SAPBR=2,1')
except (KeyboardInterrupt, SystemExit, EOFError):
break |
subprocess_server_test.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 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, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""Unit tests for the processes module."""
# pytype: skip-file
from __future__ import absolute_import
import os
import re
import shutil
import socketserver
import tempfile
import threading
import unittest
# patches unittest.TestCase to be python3 compatible
import future.tests.base # pylint: disable=unused-import
from apache_beam.utils import subprocess_server
# TODO(Py3): Use tempfile.TemporaryDirectory
class TemporaryDirectory:
def __enter__(self):
self._path = tempfile.mkdtemp()
return self._path
def __exit__(self, *args):
shutil.rmtree(self._path, ignore_errors=True)
class JavaJarServerTest(unittest.TestCase):
def test_gradle_jar_release(self):
self.assertEqual(
'https://repo.maven.apache.org/maven2/org/apache/beam/'
'beam-sdks-java-fake/VERSION/beam-sdks-java-fake-VERSION.jar',
subprocess_server.JavaJarServer.path_to_beam_jar(
':sdks:java:fake:fatJar', version='VERSION'))
self.assertEqual(
'https://repo.maven.apache.org/maven2/org/apache/beam/'
'beam-sdks-java-fake/VERSION/beam-sdks-java-fake-A-VERSION.jar',
subprocess_server.JavaJarServer.path_to_beam_jar(
':sdks:java:fake:fatJar', appendix='A', version='VERSION'))
self.assertEqual(
'https://repo.maven.apache.org/maven2/org/apache/beam/'
'beam-sdks-java-fake/VERSION/beam-sdks-java-fake-A-VERSION.jar',
subprocess_server.JavaJarServer.path_to_beam_jar(
':gradle:target:doesnt:matter',
appendix='A',
version='VERSION',
artifact_id='beam-sdks-java-fake'))
def test_gradle_jar_dev(self):
with self.assertRaisesRegex(
Exception,
re.escape(os.path.join('sdks',
'java',
'fake',
'build',
'libs',
'beam-sdks-java-fake-VERSION-SNAPSHOT.jar')) +
' not found.'):
subprocess_server.JavaJarServer.path_to_beam_jar(
':sdks:java:fake:fatJar', version='VERSION.dev')
with self.assertRaisesRegex(
Exception,
re.escape(os.path.join('sdks',
'java',
'fake',
'build',
'libs',
'beam-sdks-java-fake-A-VERSION-SNAPSHOT.jar')) +
' not found.'):
subprocess_server.JavaJarServer.path_to_beam_jar(
':sdks:java:fake:fatJar', appendix='A', version='VERSION.dev')
with self.assertRaisesRegex(
Exception,
re.escape(os.path.join('sdks',
'java',
'fake',
'build',
'libs',
'fake-artifact-id-A-VERSION-SNAPSHOT.jar')) +
' not found.'):
subprocess_server.JavaJarServer.path_to_beam_jar(
':sdks:java:fake:fatJar',
appendix='A',
version='VERSION.dev',
artifact_id='fake-artifact-id')
def test_beam_services(self):
with subprocess_server.JavaJarServer.beam_services({':some:target': 'foo'}):
self.assertEqual(
'foo',
subprocess_server.JavaJarServer.path_to_beam_jar(':some:target'))
def test_local_jar(self):
class Handler(socketserver.BaseRequestHandler):
timeout = 1
def handle(self):
self.request.recv(1024)
self.request.sendall(b'HTTP/1.1 200 OK\n\ndata')
port, = subprocess_server.pick_port(None)
server = socketserver.TCPServer(('localhost', port), Handler)
t = threading.Thread(target=server.handle_request)
t.daemon = True
t.start()
with TemporaryDirectory() as temp_dir:
subprocess_server.JavaJarServer.local_jar(
'http://localhost:%s/path/to/file.jar' % port, temp_dir)
with open(os.path.join(temp_dir, 'file.jar')) as fin:
self.assertEqual(fin.read(), 'data')
if __name__ == '__main__':
unittest.main()
|
backtester_coin_vj.py | import os
import sys
import sqlite3
import pandas as pd
from matplotlib import pyplot as plt
from multiprocessing import Process, Queue
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
from utility.setting import DB_BACKTEST, DB_COIN_TICK
from utility.static import now, strf_time, timedelta_day
class BackTester2mCoin:
def __init__(self, q_, ticker_list_, num_):
self.q = q_
self.ticker_list = ticker_list_
self.batting = num_[0]
self.testperiod = num_[1]
self.totaltime = num_[2]
self.starttime = num_[3]
self.endtime = num_[4]
self.gap_ch = num_[5]
self.avg_time = num_[6]
self.gap_sm = num_[7]
self.ch_low = num_[8]
self.dm_low = num_[9]
self.per_low = num_[10]
self.per_high = num_[11]
self.cs_per = num_[12]
self.ticker = None
self.df = None
self.totalcount = 0
self.totalcount_p = 0
self.totalcount_m = 0
self.totalholdday = 0
self.totaleyun = 0
self.totalper = 0.
self.hold = False
self.buycount = 0
self.buyprice = 0
self.sellprice = 0
self.index = 0
self.indexb = 0
self.indexn = 0
self.ccond = 0
self.Start()
def Start(self):
conn = sqlite3.connect(DB_COIN_TICK)
tcount = len(self.ticker_list)
int_daylimit = int(strf_time('%Y%m%d', timedelta_day(-self.testperiod)))
for k, ticker in enumerate(self.ticker_list):
self.ticker = ticker
self.df = pd.read_sql(f"SELECT * FROM '{ticker}'", conn)
self.df = self.df.set_index('index')
self.df['๊ณ ์ ํ๊ท ๋๋น๋ฑ๋ฝ์จ'] = (self.df['ํ์ฌ๊ฐ'] / ((self.df['๊ณ ๊ฐ'] + self.df['์ ๊ฐ']) / 2) - 1) * 100
self.df['๊ณ ์ ํ๊ท ๋๋น๋ฑ๋ฝ์จ'] = self.df['๊ณ ์ ํ๊ท ๋๋น๋ฑ๋ฝ์จ'].round(2)
self.df['์ฒด๊ฒฐ๊ฐ๋'] = self.df['๋์ ๋งค์๋'] / self.df['๋์ ๋งค๋๋'] * 100
self.df['์ฒด๊ฒฐ๊ฐ๋'] = self.df['์ฒด๊ฒฐ๊ฐ๋'].round(2)
self.df['์ง์ ์ฒด๊ฒฐ๊ฐ๋'] = self.df['์ฒด๊ฒฐ๊ฐ๋'].shift(1)
self.df['์ง์ ๋์ ๊ฑฐ๋๋๊ธ'] = self.df['๋์ ๊ฑฐ๋๋๊ธ'].shift(1)
self.df = self.df.fillna(0)
self.df['๊ฑฐ๋๋๊ธ'] = self.df['๋์ ๊ฑฐ๋๋๊ธ'] - self.df['์ง์ ๋์ ๊ฑฐ๋๋๊ธ']
self.df['์ง์ ๊ฑฐ๋๋๊ธ'] = self.df['๊ฑฐ๋๋๊ธ'].shift(1)
self.df = self.df.fillna(0)
self.df['๊ฑฐ๋๋๊ธํ๊ท '] = self.df['์ง์ ๊ฑฐ๋๋๊ธ'].rolling(window=self.avg_time).mean()
self.df['์ฒด๊ฒฐ๊ฐ๋ํ๊ท '] = self.df['์ง์ ์ฒด๊ฒฐ๊ฐ๋'].rolling(window=self.avg_time).mean()
self.df['์ต๊ณ ์ฒด๊ฒฐ๊ฐ๋'] = self.df['์ง์ ์ฒด๊ฒฐ๊ฐ๋'].rolling(window=self.avg_time).max()
self.df = self.df.fillna(0)
self.totalcount = 0
self.totalcount_p = 0
self.totalcount_m = 0
self.totalholdday = 0
self.totaleyun = 0
self.totalper = 0.
self.ccond = 0
lasth = len(self.df) - 1
for h, index in enumerate(self.df.index):
if h != 0 and index[:8] != self.df.index[h - 1][:8]:
self.ccond = 0
if int(index[:8]) < int_daylimit or \
(not self.hold and (self.endtime <= int(index[8:]) or int(index[8:]) < self.starttime)):
continue
self.index = index
self.indexn = h
self.ccond += 1
if not self.hold and self.starttime < int(index[8:]) < self.endtime and self.BuyTerm():
self.Buy()
elif self.hold and self.starttime < int(index[8:]) < self.endtime and self.SellTerm():
self.Sell()
elif self.hold and (h == lasth or int(index[8:]) >= self.endtime > int(self.df.index[h - 1][8:])):
self.Sell()
self.Report(k + 1, tcount)
conn.close()
def BuyTerm(self):
if type(self.df['ํ์ฌ๊ฐ'][self.index]) == pd.Series:
return False
if self.ccond < self.avg_time:
return False
# ์ ๋ต ๋น๊ณต๊ฐ
return True
def Buy(self):
if self.df['๋งค๋ํธ๊ฐ1'][self.index] * self.df['๋งค๋์๋1'][self.index] >= self.batting:
s1hg = self.df['๋งค๋ํธ๊ฐ1'][self.index]
self.buycount = int(self.batting / s1hg)
self.buyprice = s1hg
else:
s1hg = self.df['๋งค๋ํธ๊ฐ1'][self.index]
s1jr = self.df['๋งค๋์๋1'][self.index]
s2hg = self.df['๋งค๋ํธ๊ฐ2'][self.index]
ng = self.batting - s1hg * s1jr
s2jc = int(ng / s2hg)
self.buycount = s1jr + s2jc
self.buyprice = round((s1hg * s1jr + s2hg * s2jc) / self.buycount, 2)
if self.buycount == 0:
return
self.hold = True
self.indexb = self.indexn
def SellTerm(self):
if type(self.df['ํ์ฌ๊ฐ'][self.index]) == pd.Series:
return False
if self.df['๋ฑ๋ฝ์จ'][self.index] > 29:
return True
bg = self.buycount * self.buyprice
cg = self.buycount * self.df['ํ์ฌ๊ฐ'][self.index]
eyun, per = self.GetEyunPer(bg, cg)
# ์ ๋ต ๋น๊ณต๊ฐ
return False
def Sell(self):
if self.df['๋งค์์๋1'][self.index] >= self.buycount:
self.sellprice = self.df['๋งค์ํธ๊ฐ1'][self.index]
else:
b1hg = self.df['๋งค์ํธ๊ฐ1'][self.index]
b1jr = self.df['๋งค์์๋1'][self.index]
b2hg = self.df['๋งค์ํธ๊ฐ2'][self.index]
nc = self.buycount - b1jr
self.sellprice = round((b1hg * b1jr + b2hg * nc) / self.buycount, 2)
self.hold = False
self.CalculationEyun()
self.indexb = 0
def CalculationEyun(self):
self.totalcount += 1
bg = self.buycount * self.buyprice
cg = self.buycount * self.sellprice
eyun, per = self.GetEyunPer(bg, cg)
self.totalper = round(self.totalper + per, 2)
self.totaleyun = int(self.totaleyun + eyun)
self.totalholdday += self.indexn - self.indexb
if per > 0:
self.totalcount_p += 1
else:
self.totalcount_m += 1
self.q.put([self.index, self.ticker, per, eyun])
# noinspection PyMethodMayBeStatic
def GetEyunPer(self, bg, cg):
gtexs = cg * 0.0023
gsfee = cg * 0.00015
gbfee = bg * 0.00015
texs = gtexs - (gtexs % 1)
sfee = gsfee - (gsfee % 10)
bfee = gbfee - (gbfee % 10)
pg = int(cg - texs - sfee - bfee)
eyun = pg - bg
per = round(eyun / bg * 100, 2)
return eyun, per
def Report(self, count, tcount):
if self.totalcount > 0:
plus_per = round((self.totalcount_p / self.totalcount) * 100, 2)
avgholdday = round(self.totalholdday / self.totalcount, 2)
self.q.put([self.ticker, self.totalcount, avgholdday, self.totalcount_p, self.totalcount_m,
plus_per, self.totalper, self.totaleyun])
ticker, totalcount, avgholdday, totalcount_p, totalcount_m, plus_per, totalper, totaleyun = \
self.GetTotal(plus_per, avgholdday)
print(f" ์ข
๋ชฉ์ฝ๋ {ticker} | ํ๊ท ๋ณด์ ๊ธฐ๊ฐ {avgholdday}์ด | ๊ฑฐ๋ํ์ {totalcount}ํ | "
f" ์ต์ {totalcount_p}ํ | ์์ {totalcount_m}ํ | ์น๋ฅ {plus_per}% |"
f" ์์ต๋ฅ {totalper}% | ์์ต๊ธ {totaleyun}์ [{count}/{tcount}]")
else:
self.q.put([self.ticker, 0, 0, 0, 0, 0., 0., 0])
def GetTotal(self, plus_per, avgholdday):
ticker = str(self.ticker)
ticker = ticker + ' ' if len(ticker) == 6 else ticker
ticker = ticker + ' ' if len(ticker) == 7 else ticker
ticker = ticker + ' ' if len(ticker) == 8 else ticker
ticker = ticker + ' ' if len(ticker) == 9 else ticker
totalcount = str(self.totalcount)
totalcount = ' ' + totalcount if len(totalcount) == 1 else totalcount
totalcount = ' ' + totalcount if len(totalcount) == 2 else totalcount
avgholdday = str(avgholdday)
avgholdday = ' ' + avgholdday if len(avgholdday.split('.')[0]) == 1 else avgholdday
avgholdday = ' ' + avgholdday if len(avgholdday.split('.')[0]) == 2 else avgholdday
avgholdday = ' ' + avgholdday if len(avgholdday.split('.')[0]) == 3 else avgholdday
avgholdday = ' ' + avgholdday if len(avgholdday.split('.')[0]) == 4 else avgholdday
avgholdday = avgholdday + '0' if len(avgholdday.split('.')[1]) == 1 else avgholdday
totalcount_p = str(self.totalcount_p)
totalcount_p = ' ' + totalcount_p if len(totalcount_p) == 1 else totalcount_p
totalcount_p = ' ' + totalcount_p if len(totalcount_p) == 2 else totalcount_p
totalcount_m = str(self.totalcount_m)
totalcount_m = ' ' + totalcount_m if len(totalcount_m) == 1 else totalcount_m
totalcount_m = ' ' + totalcount_m if len(totalcount_m) == 2 else totalcount_m
plus_per = str(plus_per)
plus_per = ' ' + plus_per if len(plus_per.split('.')[0]) == 1 else plus_per
plus_per = ' ' + plus_per if len(plus_per.split('.')[0]) == 2 else plus_per
plus_per = plus_per + '0' if len(plus_per.split('.')[1]) == 1 else plus_per
totalper = str(self.totalper)
totalper = ' ' + totalper if len(totalper.split('.')[0]) == 1 else totalper
totalper = ' ' + totalper if len(totalper.split('.')[0]) == 2 else totalper
totalper = ' ' + totalper if len(totalper.split('.')[0]) == 3 else totalper
totalper = totalper + '0' if len(totalper.split('.')[1]) == 1 else totalper
totaleyun = format(self.totaleyun, ',')
if len(totaleyun.split(',')) == 1:
totaleyun = ' ' + totaleyun if len(totaleyun.split(',')[0]) == 1 else totaleyun
totaleyun = ' ' + totaleyun if len(totaleyun.split(',')[0]) == 2 else totaleyun
totaleyun = ' ' + totaleyun if len(totaleyun.split(',')[0]) == 3 else totaleyun
totaleyun = ' ' + totaleyun if len(totaleyun.split(',')[0]) == 4 else totaleyun
elif len(totaleyun.split(',')) == 2:
totaleyun = ' ' + totaleyun if len(totaleyun.split(',')[0]) == 1 else totaleyun
totaleyun = ' ' + totaleyun if len(totaleyun.split(',')[0]) == 2 else totaleyun
totaleyun = ' ' + totaleyun if len(totaleyun.split(',')[0]) == 3 else totaleyun
totaleyun = ' ' + totaleyun if len(totaleyun.split(',')[0]) == 4 else totaleyun
elif len(totaleyun.split(',')) == 3:
totaleyun = ' ' + totaleyun if len(totaleyun.split(',')[0]) == 1 else totaleyun
return ticker, totalcount, avgholdday, totalcount_p, totalcount_m, plus_per, totalper, totaleyun
class Total:
def __init__(self, q_, last_, num_):
super().__init__()
self.q = q_
self.last = last_
self.batting = num_[0]
self.testperiod = num_[1]
self.totaltime = num_[2]
self.starttime = num_[3]
self.endtime = num_[4]
self.gap_ch = num_[5]
self.avg_time = num_[6]
self.gap_sm = num_[7]
self.ch_low = num_[8]
self.dm_low = num_[9]
self.per_low = num_[10]
self.per_high = num_[11]
self.cs_per = num_[12]
self.Start()
def Start(self):
columns = ['๊ฑฐ๋ํ์', 'ํ๊ท ๋ณด์ ๊ธฐ๊ฐ', '์ต์ ', '์์ ', '์น๋ฅ ', '์์ต๋ฅ ', '์์ต๊ธ']
df_back = pd.DataFrame(columns=columns)
df_tsg = pd.DataFrame(columns=['์ข
๋ชฉ๋ช
', 'per', 'ttsg'])
k = 0
while True:
data = self.q.get()
if len(data) == 4:
if data[0] in df_tsg.index:
df_tsg.at[data[0]] = df_tsg['์ข
๋ชฉ๋ช
'][data[0]] + ';' + data[1], \
df_tsg['per'][data[0]] + data[2], \
df_tsg['ttsg'][data[0]] + data[3]
else:
df_tsg.at[data[0]] = data[1], data[2], data[3]
else:
df_back.at[data[0]] = data[1], data[2], data[3], data[4], data[5], data[6], data[7]
k += 1
if k == self.last:
break
if len(df_back) > 0:
text = [self.gap_ch, self.avg_time, self.gap_sm, self.ch_low, self.dm_low,
self.per_low, self.per_high, self.cs_per]
print(f' {text}')
tc = df_back['๊ฑฐ๋ํ์'].sum()
if tc != 0:
pc = df_back['์ต์ '].sum()
mc = df_back['์์ '].sum()
pper = round(pc / tc * 100, 2)
df_back_ = df_back[df_back['ํ๊ท ๋ณด์ ๊ธฐ๊ฐ'] != 0]
avghold = round(df_back_['ํ๊ท ๋ณด์ ๊ธฐ๊ฐ'].sum() / len(df_back_), 2)
avgsp = round(df_back['์์ต๋ฅ '].sum() / tc, 2)
tsg = int(df_back['์์ต๊ธ'].sum())
onedaycount = round(tc / self.totaltime, 4)
onegm = int(self.batting * onedaycount * avghold)
if onegm < self.batting:
onegm = self.batting
tsp = round(tsg / onegm * 100, 4)
text = f" ์ข
๋ชฉ๋น ๋ฐฐํ
๊ธ์ก {format(self.batting, ',')}์, ํ์์๊ธ {format(onegm, ',')}์, "\
f" ์ข
๋ชฉ์ถํ๋น๋์ {onedaycount}๊ฐ/์ด, ๊ฑฐ๋ํ์ {tc}ํ, ํ๊ท ๋ณด์ ๊ธฐ๊ฐ {avghold}์ด,\n ์ต์ {pc}ํ, "\
f" ์์ {mc}ํ, ์น๋ฅ {pper}%, ํ๊ท ์์ต๋ฅ {avgsp}%, ์์ต๋ฅ ํฉ๊ณ {tsp}%, ์์ต๊ธํฉ๊ณ {format(tsg, ',')}์"
print(text)
conn = sqlite3.connect(DB_BACKTEST)
df_back.to_sql(f"{strf_time('%Y%m%d')}_2cm", conn, if_exists='replace', chunksize=1000)
conn.close()
if len(df_tsg) > 0:
df_tsg['์ฒด๊ฒฐ์๊ฐ'] = df_tsg.index
df_tsg.sort_values(by=['์ฒด๊ฒฐ์๊ฐ'], inplace=True)
df_tsg['ttsg_cumsum'] = df_tsg['ttsg'].cumsum()
df_tsg[['ttsg', 'ttsg_cumsum']] = df_tsg[['ttsg', 'ttsg_cumsum']].astype(int)
conn = sqlite3.connect(DB_BACKTEST)
df_tsg.to_sql(f"{strf_time('%Y%m%d')}_2tm", conn, if_exists='replace', chunksize=1000)
conn.close()
df_tsg.plot(figsize=(12, 9), rot=45)
plt.show()
if __name__ == "__main__":
start = now()
con = sqlite3.connect(DB_COIN_TICK)
df = pd.read_sql("SELECT name FROM sqlite_master WHERE TYPE = 'table'", con)
con.close()
table_list = list(df['name'].values)
last = len(table_list)
batting = int(sys.argv[1]) * 1000000
testperiod = int(sys.argv[2])
totaltime = int(sys.argv[3])
starttime = int(sys.argv[4])
endtime = int(sys.argv[5])
gap_ch = float(sys.argv[6])
avg_time = int(sys.argv[7])
gap_sm = int(sys.argv[8])
ch_low = float(sys.argv[9])
dm_low = int(sys.argv[10])
per_low = float(sys.argv[11])
per_high = float(sys.argv[12])
cs_per = float(sys.argv[13])
num = [batting, testperiod, totaltime, starttime, endtime,
gap_ch, avg_time, gap_sm, ch_low, dm_low, per_low, per_high, cs_per]
q = Queue()
w = Process(target=Total, args=(q, last, num))
w.start()
procs = []
workcount = int(last / int(sys.argv[14])) + 1
for j in range(0, last, workcount):
ticker_list = table_list[j:j + workcount]
p = Process(target=BackTester2mCoin, args=(q, ticker_list, num))
procs.append(p)
p.start()
for p in procs:
p.join()
w.join()
end = now()
print(f" ๋ฐฑํ
์คํ
์์์๊ฐ {end - start}")
|
all_reduce_train.py | #!/usr/bin/env python
import os
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from math import ceil
from random import Random
from torch.multiprocessing import Process
from torch.autograd import Variable
from torchvision import datasets, transforms
class Partition(object):
""" Dataset-like object, but only access a subset of it. """
def __init__(self, data, index):
self.data = data
self.index = index
def __len__(self):
return len(self.index)
def __getitem__(self, index):
data_idx = self.index[index]
return self.data[data_idx]
class DataPartitioner(object):
""" Partitions a dataset into different chuncks. """
# ๅ
ๅฏนindex่ฟ่กshuffle
# ็ถๅๆ็
งsize่ฟ่กpartition
def __init__(self, data, sizes=[0.7, 0.2, 0.1], seed=1234):
self.data = data
self.partitions = []
rng = Random()
rng.seed(seed)
data_len = len(data)
indexes = [x for x in range(0, data_len)]
rng.shuffle(indexes)
for frac in sizes:
part_len = int(frac * data_len)
self.partitions.append(indexes[0:part_len])
indexes = indexes[part_len:]
def use(self, partition):
return Partition(self.data, self.partitions[partition])
class Net(nn.Module):
""" Network architecture. """
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.conv2_drop = nn.Dropout2d()
self.fc1 = nn.Linear(320, 50)
self.fc2 = nn.Linear(50, 10)
def forward(self, x):
x = F.relu(F.max_pool2d(self.conv1(x), 2))
x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))
x = x.view(-1, 320)
x = F.relu(self.fc1(x))
x = F.dropout(x, training=self.training)
x = self.fc2(x)
return F.log_softmax(x)
def partition_dataset():
""" Partitioning MNIST """
dataset = datasets.MNIST(
'./data',
train=True,
download=True,
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307, ), (0.3081, ))
]))
size = int(dist.get_world_size()) # ่ทๅrank็ไธชๆฐ
total_bach_size = 128
bsz = int(total_bach_size / float(size)) # ๆฏไธชrankๅฏนๅบ็batch size
partition_sizes = [1.0 / size for _ in range(size)] # ่ฎพ็ฝฎๆฏไธชrankๅค็ๆฐๆฎ้็ๅคงๅฐ
partition = DataPartitioner(dataset, partition_sizes) # ๆฐๆฎๅๅ
partition = partition.use(dist.get_rank()) # ่ทๅๅฝๅrankๅฏนๅบ็ๆฐๆฎ
train_set = torch.utils.data.DataLoader(partition, batch_size=bsz, shuffle=True)
return train_set, bsz
def average_gradients(model):
""" Gradient averaging. """
size = float(dist.get_world_size())
for param in model.parameters():
dist.all_reduce(param.grad.data, op=dist.reduce_op.SUM)
param.grad.data /= size
def run(rank, size):
""" Distributed Synchronous SGD Example """
torch.manual_seed(1234)
train_set, bsz = partition_dataset()
model = Net()
model = model
model = model.cuda(rank)
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)
num_batches = ceil(len(train_set.dataset) / float(bsz))
for epoch in range(10):
epoch_loss = 0.0
for data, target in train_set:
data, target = Variable(data), Variable(target)
data, target = Variable(data.cuda(rank)), Variable(target.cuda(rank))
optimizer.zero_grad()
output = model(data)
loss = F.nll_loss(output, target)
epoch_loss += loss.item()
loss.backward()
average_gradients(model)
optimizer.step()
print('Rank ',
dist.get_rank(), ', epoch ', epoch, ': ',
epoch_loss / num_batches)
def init_processes(rank, size, fn, backend='nccl'):
""" Initialize the distributed environment. """
os.environ['MASTER_ADDR'] = '127.0.0.1'
os.environ['MASTER_PORT'] = '29500'
dist.init_process_group(backend, rank=rank, world_size=size)
fn(rank, size)
if __name__ == "__main__":
size = 2
processes = []
for rank in range(size):
p = Process(target=init_processes, args=(rank, size, run))
p.start()
processes.append(p)
for p in processes:
p.join()
|
downsamples.py | #!/usr/bin/python2.7
from __future__ import division
import os
import sys
from multiprocessing import dummy as mp
from multiprocessing import Lock
from mutex import mutex
from copy import copy
import cv2
import rospy
from sensor_msgs.msg import Image
from geometry_msgs.msg import PoseStamped
from cv_bridge import CvBridge, CvBridgeError
logger = None
class DataWriter:
def __init__ (self, targetDir, fps=10.0):
# Create target directory and pose log
if not os.path.exists(targetDir) :
os.mkdir (targetDir)
self.poseFd = open(targetDir+"/pose.csv", 'w')
self.path = targetDir
self.currentImage = None
self.currentPose = None
self.fps = fps
self.bridge = CvBridge()
self.currentTimestamp = 0.0
# Prepare multiprocessing
self.dataEx = Lock()
self.process = mp.Process(target=self.start)
self.end = False
self.process.start()
def start (self):
rate = rospy.Rate(self.fps)
counter = 0
while (self.end == False):
if self.currentImage is not None and self.currentPose is not None :
self.dataEx.acquire()
cpImg = copy (self.currentImage)
cpPose = copy (self.currentPose)
self.dataEx.release()
curImageName = "{0:06d}.jpg".format (counter)
cv2.imwrite (self.path + "/"+curImageName, self.currentImage)
poseStr = "{:.6f} {} {} {} {} {} {} {}".format(
rospy.Time.now().to_sec(),
cpPose.position.x,
cpPose.position.y,
cpPose.position.z,
cpPose.orientation.x,
cpPose.orientation.y,
cpPose.orientation.z,
cpPose.orientation.w)
self.poseFd.write(poseStr+"\n")
counter += 1
rate.sleep()
def close (self):
self.end = True
self.poseFd.close()
def ImageCallback (imageMsg):
if logger is None:
return
# Convert to OpenCV format
logger.dataEx.acquire()
cImage = logger.bridge.imgmsg_to_cv2(imageMsg, 'mono8')
logger.currentImage = copy (cImage)
logger.dataEx.release()
def PoseCallback (poseMsg):
if logger is None:
return
# Put into datawriter
logger.dataEx.acquire()
logger.currentTimestamp = poseMsg.header.stamp.to_sec()
logger.currentPose = copy(poseMsg.pose)
logger.dataEx.release()
if __name__ == '__main__' :
rospy.init_node ("ImagePoseSubscriber", anonymous=True)
logger = DataWriter(sys.argv[1])
rospy.Subscriber ("/camera/image_hs", Image, ImageCallback, queue_size=20)
rospy.Subscriber ("/filtered_ndt_current_pose", PoseStamped, PoseCallback, queue_size=100)
rospy.spin()
logger.close()
pass
|
sensing_interface.py | #!/usr/bin/env python
import rospy
import rospkg
import re
import threading
import numpy as np
from threading import Lock
import imp
from rosplan_knowledge_msgs.srv import KnowledgeUpdateServiceArray, KnowledgeUpdateServiceArrayRequest
from rosplan_knowledge_msgs.srv import GetDomainPredicateDetailsService, GetDomainPredicateDetailsServiceRequest
from rosplan_knowledge_msgs.srv import GetDomainAttributeService
from rosplan_knowledge_msgs.srv import GetAttributeService, GetAttributeServiceRequest
from rosplan_knowledge_msgs.srv import GetInstanceService, GetInstanceServiceRequest
from rosplan_knowledge_msgs.srv import SetNamedBool, SetNamedBoolRequest
from rosplan_knowledge_msgs.msg import KnowledgeItem, StatusUpdate
from diagnostic_msgs.msg import KeyValue
class RosplanSensing:
def __init__(self):
self.mutex = Lock()
self.srv_mutex = Lock()
self.dump_cache_mutex = Lock()
################################################################################################################
self.knowledge_base = '/rosplan_knowledge_base'
if rospy.has_param('~knowledge_base'):
self.knowledge_base = rospy.get_param('~knowledge_base')
# Init clients and publishers
rospy.wait_for_service(self.knowledge_base + '/update_array')
self.update_kb_srv = rospy.ServiceProxy(self.knowledge_base + '/update_array', KnowledgeUpdateServiceArray)
rospy.wait_for_service(self.knowledge_base + '/domain/predicate_details')
self.get_predicates_srv = rospy.ServiceProxy(self.knowledge_base + '/domain/predicate_details', GetDomainPredicateDetailsService)
rospy.wait_for_service(self.knowledge_base + '/domain/functions')
self.get_functions_srv = rospy.ServiceProxy(self.knowledge_base + '/domain/functions', GetDomainAttributeService)
rospy.wait_for_service(self.knowledge_base + '/state/instances')
self.get_instances_srv = rospy.ServiceProxy(self.knowledge_base + '/state/instances', GetInstanceService)
rospy.wait_for_service(self.knowledge_base + '/state/propositions')
self.get_state_propositions_srv = rospy.ServiceProxy(self.knowledge_base + '/state/propositions', GetAttributeService)
rospy.wait_for_service(self.knowledge_base + '/state/functions')
self.get_state_functions_srv = rospy.ServiceProxy(self.knowledge_base + '/state/functions', GetAttributeService)
self.set_sensed_predicate_srv = rospy.ServiceProxy(self.knowledge_base + '/update_sensed_predicates', SetNamedBool)
self.kb_update_status_subs = rospy.Subscriber(self.knowledge_base + '/status/update', StatusUpdate, self.kb_update_status)
################################################################################################################
# Get cfg
self.cfg_topics = self.cfg_service = {}
self.functions_path = None
found_config = False
if rospy.has_param('~topics'):
self.cfg_topics = rospy.get_param('~topics')
found_config = True
if rospy.has_param('~services'):
self.cfg_service = rospy.get_param('~services')
found_config = True
if rospy.has_param('~functions'):
self.functions_path = rospy.get_param('~functions')[0]
regexp = re.compile('\$\(find (.*)\)')
groups = regexp.match(self.functions_path).groups()
if len(groups):
try:
ros_pkg_path = rospkg.RosPack().get_path(groups[0])
self.functions_path = regexp.sub(ros_pkg_path, self.functions_path)
except:
rospy.logerr('KCL: (RosplanSensing) Error: Package %s was not found! Fix configuration file and retry.' % groups[0])
rospy.signal_shutdown('Wrong path in cfg file')
return
if not found_config:
rospy.logerr('KCL: (RosplanSensing) Error: configuration file is not defined!')
rospy.signal_shutdown('Config not found')
return
################################################################################################################
# Load scripts
if self.functions_path:
self.scripts = imp.load_source('sensing_scripts', self.functions_path)
# Declare tools in the scripts module:
self.scripts.get_kb_attribute = self.get_kb_attribute
self.scripts.rospy = rospy
################################################################################################################
# Init variables
self.sensed_topics = {}
self.sensed_services = {}
self.params = {} # Params defined for each predicate
######
# Subscribe to all the topics
self.offset = {} # Offset for reading cfg
for predicate_name, predicate_info in self.cfg_topics.iteritems():
if type(predicate_info) is list: # We have nested elements in the predicate
for i, pi in enumerate(predicate_info):
pi['sub_idx'] = i
subscribed = self.subscribe_topic(predicate_name, pi)
if not subscribed:
rospy.loginfo('Could not subscribe for predicate ' + predicate_name + ' and config: ' + str(pi))
continue
else:
predicate_info['sub_idx'] = 0 # As we don't have nested elements in this predicate
subscribed = self.subscribe_topic(predicate_name, predicate_info)
if not subscribed:
rospy.loginfo('Could not subscribe for predicate ' + predicate_name + ' and config: ' + str(predicate_info))
############
# Create clients for all the services
self.service_clients = []
self.service_names = []
self.service_type_names = []
self.service_predicate_names = []
self.last_called_time = []
self.time_between_calls = []
self.request_src = []
self.response_process_src = []
self.clients_sub_idx = []
for predicate_name, predicate_info in self.cfg_service.iteritems():
if type(predicate_info) is list:
for i, pi in enumerate(predicate_info):
pi['sub_idx'] = i
client_created = self.create_service_client(predicate_name, pi)
if not client_created:
rospy.loginfo('Could not create client for predicate ' + predicate_name + ' and config: ' + str(pi))
continue
else:
predicate_info['sub_idx'] = 0 # As we don't have nested elements in this predicate
client_created = self.create_service_client(predicate_name, predicate_info)
if not client_created:
rospy.loginfo('Could not create client for predicate ' + predicate_name + ' and config: ' + str(predicate_info))
continue
# Returns (bool, bool), first tells if the parameters could be loaded, second if parameters were loaded from config file and false if they were taken directly from the kb
def load_params(self, predicate_name, predicate_info):
# Check if predicate
kb_info = None
try:
kb_info = self.get_predicates_srv.call(GetDomainPredicateDetailsServiceRequest(predicate_name)).predicate
except Exception as e:
kb_info = self.get_function_params(predicate_name)
if not kb_info:
rospy.logerr("KCL: (RosplanSensing) Could not find predicate or function %s" % predicate_name)
return (False, False)
if predicate_name not in self.params: # Prepare dictionary
self.params[predicate_name] = {}
# Obtain all the instances for each parameter
kb_params = []
for p in kb_info.typed_parameters:
instances = self.get_instances_srv.call(GetInstanceServiceRequest(p.value)).instances
kb_params.append(instances)
if 'params' in predicate_info:
params = predicate_info['params']
if len(kb_params) != len(params):
rospy.logerr("KCL: (RosplanSensing) Parameters defined for predicate %s don't match the knowledge base" % predicate_name)
rospy.signal_shutdown('Wrong cfg file parameters definition')
return (False, True)
# Check params
wildcard = False
for i, p in enumerate(params):
if p != '*' and p != '_':
if p in kb_params[i]:
kb_params[i] = [p]
else:
rospy.logerr('KCL: (RosplanSensing) Unknown parameter instance "%s" of type "%s" for predicate "%s"',
p, kb_info.typed_parameters[i].value, predicate_name)
rospy.signal_shutdown('Wrong cfg file parameters definition')
return (False, True)
else:
wildcard = True
# If the params are fully instantiated we store them as a list, else it will be a matrix with a list of
# instances per parameter
self.params[predicate_name][predicate_info['sub_idx']] = kb_params if wildcard else params
return (True, True)
else:
self.params[predicate_name][predicate_info['sub_idx']] = kb_params
return (True, False)
def subscribe_topic(self, predicate_name, predicate_info):
params_loaded = self.load_params(predicate_name, predicate_info) # If parameters found, add 1 to the indexes
if not params_loaded[0]:
return False
if len(predicate_info) < 2 + int(params_loaded[1]):
rospy.logerr("Error: Wrong configuration file for predicate %s" % predicate_name)
return False
try:
msg_type = predicate_info['msg_type']
except KeyError:
rospy.logerr("Error: msg_type was not specified for predicate %s" % predicate_name)
return False
self.import_msg(msg_type)
try:
if isinstance(predicate_info['topic'], list):
for topic in predicate_info['topic']:
pred_info = predicate_info.copy()
pred_info['publisher'] = topic
rospy.Subscriber(str(topic), eval(msg_type[msg_type.rfind('/') + 1:]), self.subs_callback, (predicate_name, pred_info))
else:
rospy.Subscriber(predicate_info['topic'], eval(msg_type[msg_type.rfind('/') + 1:]), self.subs_callback, (predicate_name, predicate_info))
except KeyError:
rospy.logerr("Error: topic was not specified for predicate %s" % predicate_name)
return False
# self.sensed_topics[predicate_name] = (None, False)
try: # Update KB to inform about the sensed predicates
sensed_srv_req = SetNamedBoolRequest()
sensed_srv_req.name = predicate_name
sensed_srv_req.value = True
self.set_sensed_predicate_srv.call(sensed_srv_req)
except Exception as e:
rospy.logerr(
'KCL: (RosplanSensing) Could not update sensing information in Knowledge Base for proposition %s',
predicate_name)
rospy.loginfo('KCL: (RosplanSensing) Predicate %s: Subscribed to topic %s of type %s', predicate_name,
predicate_info['topic'], msg_type)
return True
def create_service_client(self, predicate_name, predicate_info):
params_loaded = self.load_params(predicate_name, predicate_info) # If parameters found, add 1 to the indexes
if not params_loaded[0]:
return False
if len(predicate_info) < 2 + int(params_loaded[1]):
rospy.logerr("Error: Wrong configuration file for predicate %s" % predicate_name)
return False
try:
srv_type = predicate_info['srv_type']
except KeyError:
rospy.logerr("Error: service was not specified for predicate %s" % predicate_name)
return False
srv_typename = self.import_srv(srv_type)
self.service_type_names.append(srv_typename)
self.clients_sub_idx.append(predicate_info['sub_idx'])
try:
self.service_clients.append(rospy.ServiceProxy(predicate_info['service'], eval(srv_typename)))
self.service_names.append(predicate_info['service'])
except KeyError:
rospy.logerr("Error: service was not specified for predicate %s" % predicate_name)
return False
self.service_predicate_names.append(predicate_name)
self.last_called_time.append(rospy.Time(0))
try:
self.time_between_calls.append(predicate_info['time_between_calls'])
except:
rospy.logerr("Error: time_between_calls was not specified for predicate %s" % predicate_name)
return False
# Gets the request creation
if 'request' in predicate_info:
self.request_src.append(predicate_info['request'])
else:
self.request_src.append(None)
# Gets the result processing
if 'operation' in predicate_info:
self.response_process_src.append(predicate_info['operation'])
else:
self.response_process_src.append(None)
try: # Update KB to inform about the sensed predicates
sensed_srv_req = SetNamedBoolRequest()
sensed_srv_req.name = predicate_name
sensed_srv_req.value = True
self.set_sensed_predicate_srv.call(sensed_srv_req)
except Exception as e:
rospy.logerr(
'KCL: (RosplanSensing) Could not update sensing information in Knowledge Base for proposition %s',
predicate_name)
rospy.loginfo('KCL: (RosplanSensing) Predicate %s: Client for service %s of type %s is ready', predicate_name,
predicate_info['service'], srv_type)
return True
def get_function_params(self, func_name):
functions = self.get_functions_srv.call()
for i in functions.items:
if i.name == func_name:
return i
return None
def subs_callback(self, msg, (pred_name, pred_info)):
if 'operation' in pred_info: # pred_info is of type self.cfg_topics[pred_name]
python_string = pred_info['operation']
else: # Call the method from the scripts.py file
if not pred_name in dir(self.scripts):
rospy.logerr('KCL: (RosplanSensing) Predicate "%s" does not have either a function or processing information' % pred_name)
return None
if 'publisher' in pred_info:
python_string = "self.scripts." + pred_name + "(msg, self.params[pred_name][pred_info['sub_idx']], pred_info['publisher'])"
else:
python_string = "self.scripts." + pred_name + "(msg, self.params[pred_name][pred_info['sub_idx']])"
self.mutex.acquire(True)
result = eval(python_string, globals(), locals())
self.mutex.release()
changed = False
if type(result) is list:
for params, val in result:
self.mutex.acquire(True) # ROS subscribers are multithreaded in Python
try:
if type(val) is bool:
changed = self.sensed_topics[pred_name + ':' + params][0] ^ val
else:
changed = self.sensed_topics[pred_name + ':' + params][0] != val
except: # If hasn't been added yet just ignore it
changed = True
if changed:
self.sensed_topics[pred_name + ':' + params] = (val, changed, False)
self.mutex.release()
else:
params = reduce(lambda r, x: r + ':' + x, self.params[pred_name][pred_info['sub_idx']])
if type(params) == list:
rospy.logerr('KCL: (RosplanSensing) Predicate "%s" needs to have all the parameters defined and fully instantiated' % pred_name)
rospy.signal_shutdown('Wrong cfg params')
return None
self.mutex.acquire(True) # ROS subscribers are multithreaded in Python
try:
if type(result) is bool:
changed = self.sensed_topics[pred_name + ':' + params][0] ^ result
else:
changed = self.sensed_topics[pred_name + ':' + params][0] != result
except: # If hasn't been added yet just ignore it
changed = True
if changed:
self.sensed_topics[pred_name + ':' + params] = (result, changed, False)
self.mutex.release()
# Import a ros msg type of type pkg_name/MessageName
def import_msg(self, ros_msg_string):
# msg_string will be something like std_msgs/String -> convert it to from std_msgs.msg import String
i = ros_msg_string.find('/')
pkg_name = ros_msg_string[:i]
msg_name = ros_msg_string[i+1:]
exec('from ' + pkg_name + ".msg import " + msg_name, globals())
exec('self.scripts.' + msg_name + " = " + msg_name, globals(), locals())
# Import a ros srv type of type pkg_name/MessageName
def import_srv(self, ros_srv_string):
# srv str will be something like std_msgs/String -> convert it to from std_msgs.srv import String StringRequest
i = ros_srv_string.find('/')
pkg_name = ros_srv_string[:i]
srv_name = ros_srv_string[i + 1:]
exec ('from ' + pkg_name + ".srv import " + srv_name + ", " + srv_name + "Request", globals())
exec ('self.scripts.' + srv_name + " = " + srv_name, globals(), locals())
exec ('self.scripts.' + srv_name + "Request = " + srv_name + "Request", globals(), locals())
return srv_name
# To be run in its own thread
def call_services(self):
rospy.loginfo("Waiting for services to become available...")
for i in xrange(len(self.service_names)):
rospy.loginfo(' Waiting for %s', self.service_names[i])
rospy.wait_for_service(self.service_names[i], 20)
rospy.loginfo('All services are ready.')
r = rospy.Rate(20)
while not rospy.is_shutdown():
for i in xrange(len(self.service_clients)):
now = rospy.Time.now()
if (now-self.last_called_time[i]) < rospy.Duration(self.time_between_calls[i]):
continue
pred_name = self.service_predicate_names[i]
# Get request
if self.request_src[i]:
python_string = self.request_src[i]
else: # Call the method from the scripts.py file
if not ('req_' + pred_name) in dir(self.scripts):
rospy.logerr(
'KCL: (RosplanSensing) Predicate "%s" does not have either a Request creation method' % pred_name)
continue
python_string = "self.scripts." + 'req_' + pred_name + "()"
req = eval(python_string, globals(), locals())
try:
res = self.service_clients[i].call(req)
self.last_called_time[i] = now
except Exception as e:
rospy.logerr("KCL (SensingInterface) Failed to call service for predicate %s base: %s" % (pred_name, e.message))
continue
# Process response
if self.response_process_src[i]:
python_string = self.response_process_src[i]
else: # Call the method from the scripts.py file
if not pred_name in dir(self.scripts):
rospy.logerr('KCL: (RosplanSensing) Predicate "%s" does not have either a function or processing information' %
pred_name)
continue
python_string = "self.scripts." + pred_name + "(res, self.params[pred_name][self.clients_sub_idx[i]])"
result = eval(python_string, globals(), locals())
changed = False
if type(result) is list:
for params, val in result:
self.srv_mutex.acquire(True) # ROS subscribers are multithreaded in Python
try:
if type(val) is bool:
changed = self.sensed_services[pred_name + ':' + params][0] ^ val
else:
changed = self.sensed_services[pred_name + ':' + params][0] != val
except: # If hasn't been added yet just ignore it
changed = True
if changed:
self.sensed_services[pred_name + ':' + params] = (val, changed, False)
self.srv_mutex.release()
else:
params = reduce(lambda r, x: r + ':' + x, self.params[pred_name][self.clients_sub_idx[i]]) if self.params[pred_name][self.clients_sub_idx[i]] else ''
if type(params) == list:
rospy.logerr(
'KCL: (RosplanSensing) Predicate "%s" needs to have all the parameters defined and fully instantiated' % pred_name)
rospy.signal_shutdown('Wrong cfg params')
return None
self.srv_mutex.acquire(True) # ROS subscribers are multithreaded in Python
try:
if type(result) is bool:
changed = self.sensed_services[pred_name + ':' + params][0] ^ result
else:
changed = self.sensed_services[pred_name + ':' + params][0] != result
except: # If hasn't been added yet just ignore it
changed = True
if changed:
self.sensed_services[pred_name + ':' + params] = (result, changed, False)
self.srv_mutex.release()
r.sleep()
return None # Finish thread
def update_kb(self):
kus = KnowledgeUpdateServiceArrayRequest()
# Get info from KB functions and propositions (to know type of variable)
# Fill update
self.dump_cache_mutex.acquire(True)
self.mutex.acquire(True)
sensed_predicates = self.sensed_topics.copy()
self.mutex.release()
self.srv_mutex.acquire(True)
sensed_predicates.update(self.sensed_services.copy())
self.srv_mutex.release()
for predicate, (val, changed, updated) in sensed_predicates.iteritems():
if updated:
continue
if predicate in self.sensed_topics:
self.mutex.acquire(True)
self.sensed_topics[predicate] = (self.sensed_topics[predicate][0], False, True) # Set to not changed and updated KB
self.mutex.release()
else:
self.srv_mutex.acquire(True)
self.sensed_services[predicate] = (self.sensed_services[predicate][0], False, True) # Set to not changed and updated KB
self.srv_mutex.release()
predicate_info = predicate.split(':')
ki = KnowledgeItem()
ki.attribute_name = predicate_info.pop(0)
if type(val) is bool:
ki.knowledge_type = ki.FACT
ki.is_negative = not val
else:
ki.knowledge_type = ki.FUNCTION
ki.function_value = val
# TODO what to do if no parameters specified? iterate over all the instantiated parameters and add them?
for i, param in enumerate(predicate_info):
kv = KeyValue()
kv.key = 'p' + str(i)
kv.value = param
ki.values.append(kv)
kus.update_type += np.array(kus.ADD_KNOWLEDGE).tostring()
kus.knowledge.append(ki)
self.dump_cache_mutex.release()
# Update the KB with the full array
if len(kus.update_type) > 0:
try:
self.update_kb_srv.call(kus)
except Exception as e:
rospy.logerr("KCL (SensingInterface) Failed to update knowledge base: %s" % e.message)
def get_kb_attribute(self, attribute_name):
try:
request = GetAttributeServiceRequest(attribute_name)
ret = self.get_state_propositions_srv.call(request)
if len(ret.attributes) > 0:
return ret.attributes
return self.get_state_functions_srv.call(request).attributes
except Exception as e:
rospy.logwarn("KCL (SensingInterface) Failed to call knowledge base for details: %s" % e.message)
return []
def kb_update_status(self, msg):
if not msg.last_update_client == rospy.get_name(): # if I did not update the KB....
self.dump_cache_mutex.acquire(True)
self.mutex.acquire(True)
self.srv_mutex.acquire(True)
# Dump cache, it will be reloaded in the next update
for predicate, (val, changed, updated) in self.sensed_topics.iteritems():
self.sensed_topics[predicate] = (val, changed, False)
self.sensed_services.clear()
self.srv_mutex.release()
self.mutex.release()
self.dump_cache_mutex.release()
if __name__ == "__main__":
rospy.init_node('rosplan_sensing_interface', anonymous=False)
rps = RosplanSensing()
t = threading.Thread(target=RosplanSensing.call_services, args=(rps,))
# main loop
hz_rate = rospy.get_param('~main_rate', 10)
rate = rospy.Rate(hz_rate) # 10hz
t.start()
while not rospy.is_shutdown():
# Note: spin is not needed in python as the callback methods are run in a different thread
rps.update_kb()
rate.sleep()
t.join()
|
cpu_bound_multiprocess.py | """ cpu bound single module """
from collections.abc import Generator
import itertools
import time
import multiprocessing as mp
def fibonacci() -> Generator[int, None, None]:
""" generate an infinite sequence of fibonacci numbers """
num_1 = 0
num_2 = 1
yield num_1
yield num_2
while True:
next_num = num_1 + num_2
yield next_num
num_1 = num_2
num_2 = next_num
def calc_fib_total(p_results: list[int]) -> None:
""" calc fib total """
total = 0
for num in itertools.islice(fibonacci(), 0, 500000):
total = total + num
p_results.append(total)
if __name__ == "__main__":
start_time = time.time()
with mp.Manager() as manager:
results: list[int] = manager.list()
processes: list[mp.Process] = []
for _ in range(8):
a_process = mp.Process(target=calc_fib_total, args=(results,))
a_process.start()
processes.append(a_process)
for a_process in processes:
a_process.join()
time_elapsed = time.time() - start_time
print(len(results))
print(time_elapsed)
|
clang_format.py | #! /usr/bin/env python
"""
A script that provides:
1. Ability to grab binaries where possible from LLVM.
2. Ability to download binaries from MongoDB cache for clang-format.
3. Validates clang-format is the right version.
4. Has support for checking which files are to be checked.
5. Supports validating and updating a set of files to the right coding style.
"""
from __future__ import print_function, absolute_import
import Queue
import difflib
import itertools
import os
import re
import shutil
import string
import subprocess
import sys
import tarfile
import tempfile
import threading
import time
import urllib
from distutils import spawn
from optparse import OptionParser
from multiprocessing import cpu_count
# Get relative imports to work when the package is not installed on the PYTHONPATH.
if __name__ == "__main__" and __package__ is None:
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(os.path.realpath(__file__)))))
from buildscripts.resmokelib.utils import globstar
from buildscripts import moduleconfig
##############################################################################
#
# Constants for clang-format
#
#
# Expected version of clang-format
CLANG_FORMAT_VERSION = "3.6.0"
# Name of clang-format as a binary
CLANG_FORMAT_PROGNAME = "clang-format"
# URL location of the "cached" copy of clang-format to download
# for users which do not have clang-format installed
CLANG_FORMAT_HTTP_LINUX_CACHE = "https://s3.amazonaws.com/boxes.10gen.com/build/clang-format-rhel55.tar.gz"
# URL on LLVM's website to download the clang tarball
CLANG_FORMAT_SOURCE_URL_BASE = string.Template("http://llvm.org/releases/$version/clang+llvm-$version-$llvm_distro.tar.xz")
# Path in the tarball to the clang-format binary
CLANG_FORMAT_SOURCE_TAR_BASE = string.Template("clang+llvm-$version-$tar_path/bin/" + CLANG_FORMAT_PROGNAME)
# Path to the modules in the mongoldb source tree
# Has to match the string in SConstruct
MODULE_DIR = "src/mongol/db/modules"
# Copied from python 2.7 version of subprocess.py
# Exception classes used by this module.
class CalledProcessError(Exception):
"""This exception is raised when a process run by check_call() or
check_output() returns a non-zero exit status.
The exit status will be stored in the returncode attribute;
check_output() will also store the output in the output attribute.
"""
def __init__(self, returncode, cmd, output=None):
self.returncode = returncode
self.cmd = cmd
self.output = output
def __str__(self):
return ("Command '%s' returned non-zero exit status %d with output %s" %
(self.cmd, self.returncode, self.output))
# Copied from python 2.7 version of subprocess.py
def check_output(*popenargs, **kwargs):
r"""Run command with arguments and return its output as a byte string.
If the exit code was non-zero it raises a CalledProcessError. The
CalledProcessError object will have the return code in the returncode
attribute and output in the output attribute.
The arguments are the same as for the Popen constructor. Example:
>>> check_output(["ls", "-l", "/dev/null"])
'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
The stdout argument is not allowed as it is used internally.
To capture standard error in the result, use stderr=STDOUT.
>>> check_output(["/bin/sh", "-c",
... "ls -l non_existent_file ; exit 0"],
... stderr=STDOUT)
'ls: non_existent_file: No such file or directory\n'
"""
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs)
output, unused_err = process.communicate()
retcode = process.poll()
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
raise CalledProcessError(retcode, cmd, output)
return output
def callo(args):
"""Call a program, and capture its output
"""
return check_output(args)
def get_llvm_url(version, llvm_distro):
"""Get the url to download clang-format from llvm.org
"""
return CLANG_FORMAT_SOURCE_URL_BASE.substitute(
version=version,
llvm_distro=llvm_distro)
def get_tar_path(version, tar_path):
""" Get the path to clang-format in the llvm tarball
"""
return CLANG_FORMAT_SOURCE_TAR_BASE.substitute(
version=version,
tar_path=tar_path)
def extract_clang_format(tar_path):
# Extract just the clang-format binary
# On OSX, we shell out to tar because tarfile doesn't support xz compression
if sys.platform == 'darwin':
subprocess.call(['tar', '-xzf', tar_path, '*clang-format*'])
# Otherwise we use tarfile because some versions of tar don't support wildcards without
# a special flag
else:
tarfp = tarfile.open(tar_path)
for name in tarfp.getnames():
if name.endswith('clang-format'):
tarfp.extract(name)
tarfp.close()
def get_clang_format_from_llvm(llvm_distro, tar_path, dest_file):
"""Download clang-format from llvm.org, unpack the tarball,
and put clang-format in the specified place
"""
# Build URL
url = get_llvm_url(CLANG_FORMAT_VERSION, llvm_distro)
dest_dir = tempfile.gettempdir()
temp_tar_file = os.path.join(dest_dir, "temp.tar.xz")
# Download from LLVM
print("Downloading clang-format %s from %s, saving to %s" % (CLANG_FORMAT_VERSION,
url, temp_tar_file))
urllib.urlretrieve(url, temp_tar_file)
extract_clang_format(temp_tar_file)
# Destination Path
shutil.move(get_tar_path(CLANG_FORMAT_VERSION, tar_path), dest_file)
def get_clang_format_from_linux_cache(dest_file):
"""Get clang-format from mongoldb's cache
"""
# Get URL
url = CLANG_FORMAT_HTTP_LINUX_CACHE
dest_dir = tempfile.gettempdir()
temp_tar_file = os.path.join(dest_dir, "temp.tar.xz")
# Download the file
print("Downloading clang-format %s from %s, saving to %s" % (CLANG_FORMAT_VERSION,
url, temp_tar_file))
urllib.urlretrieve(url, temp_tar_file)
extract_clang_format(temp_tar_file)
# Destination Path
shutil.move("llvm/Release/bin/clang-format", dest_file)
class ClangFormat(object):
"""Class encapsulates finding a suitable copy of clang-format,
and linting/formating an individual file
"""
def __init__(self, path, cache_dir):
if os.path.exists('/usr/bin/clang-format-3.6'):
clang_format_progname = 'clang-format-3.6'
else:
clang_format_progname = CLANG_FORMAT_PROGNAME
# Initialize clang-format configuration information
if sys.platform.startswith("linux"):
#"3.6.0/clang+llvm-3.6.0-x86_64-linux-gnu-ubuntu-14.04.tar.xz
self.platform = "linux_x64"
self.llvm_distro = "x86_64-linux-gnu-ubuntu"
self.tar_path = "x86_64-linux-gnu"
elif sys.platform == "win32":
self.platform = "windows_x64"
self.llvm_distro = "windows_x64"
self.tar_path = None
clang_format_progname += ".exe"
elif sys.platform == "darwin":
#"3.6.0/clang+llvm-3.6.0-x86_64-apple-darwin.tar.xz
self.platform = "darwin_x64"
self.llvm_distro = "x86_64-apple-darwin"
self.tar_path = "x86_64-apple-darwin"
self.path = None
# Find Clang-Format now
if path is not None:
if os.path.isfile(path):
self.path = path
else:
print("WARNING: Could not find clang-format %s" % (path))
# Check the envionrment variable
if "MONGO_CLANG_FORMAT" in os.environ:
self.path = os.environ["MONGO_CLANG_FORMAT"]
if self.path and not self._validate_version(warn=True):
self.path = None
# Check the users' PATH environment variable now
if self.path is None:
self.path = spawn.find_executable(clang_format_progname)
if self.path and not self._validate_version(warn=True):
self.path = None
# If Windows, try to grab it from Program Files
if sys.platform == "win32":
win32bin = os.path.join(os.environ["ProgramFiles(x86)"], "LLVM\\bin\\clang-format.exe")
if os.path.exists(win32bin):
self.path = win32bin
# Have not found it yet, download it from the web
if self.path is None:
if not os.path.isdir(cache_dir):
os.makedirs(cache_dir)
self.path = os.path.join(cache_dir, clang_format_progname)
if not os.path.isfile(self.path):
if sys.platform.startswith("linux"):
get_clang_format_from_linux_cache(self.path)
elif sys.platform == "darwin":
get_clang_format_from_llvm(self.llvm_distro, self.tar_path, self.path)
else:
print("ERROR: clang-format.py does not support downloading clang-format " +
" on this platform, please install clang-format " + CLANG_FORMAT_VERSION)
# Validate we have the correct version
self._validate_version()
self.print_lock = threading.Lock()
def _validate_version(self, warn=False):
"""Validate clang-format is the expected version
"""
cf_version = callo([self.path, "--version"])
if CLANG_FORMAT_VERSION in cf_version:
return True
if warn:
print("WARNING: clang-format found in path, but incorrect version found at " +
self.path + " with version: " + cf_version)
return False
def lint(self, file_name):
"""Check the specified file has the correct format
"""
with open(file_name, 'r') as original_text:
original_file = original_text.read()
# Get formatted file as clang-format would format the file
formatted_file = callo([self.path, "--style=file", file_name])
if original_file != formatted_file:
original_lines = original_file.splitlines()
formatted_lines = formatted_file.splitlines()
result = difflib.unified_diff(original_lines, formatted_lines)
# Take a lock to ensure diffs do not get mixed
with self.print_lock:
print("ERROR: Found diff for " + file_name)
print("To fix formatting errors, run %s --style=file -i %s" %
(self.path, file_name))
for line in result:
print(line.rstrip())
return False
return True
def format(self, file_name):
"""Update the format of the specified file
"""
# Update the file with clang-format
return not subprocess.call([self.path, "--style=file", "-i", file_name])
def parallel_process(items, func):
"""Run a set of work items to completion
"""
try:
cpus = cpu_count()
except NotImplementedError:
cpus = 1
# print("Running across %d cpus" % (cpus))
task_queue = Queue.Queue()
# Use a list so that worker function will capture this variable
pp_event = threading.Event()
pp_result = [True]
pp_lock = threading.Lock()
def worker():
"""Worker thread to process work items in parallel
"""
while not pp_event.is_set():
try:
item = task_queue.get_nowait()
except Queue.Empty:
# if the queue is empty, exit the worker thread
pp_event.set()
return
try:
ret = func(item)
finally:
# Tell the queue we finished with the item
task_queue.task_done()
# Return early if we fail, and signal we are done
if not ret:
with pp_lock:
pp_result[0] = False
pp_event.set()
return
# Enqueue all the work we want to process
for item in items:
task_queue.put(item)
# Process all the work
threads = []
for cpu in range(cpus):
thread = threading.Thread(target=worker)
thread.daemon = True
thread.start()
threads.append(thread)
# Wait for the threads to finish
# Loop with a timeout so that we can process Ctrl-C interrupts
# Note: On Python 2.6 wait always returns None so we check is_set also,
# This works because we only set the event once, and never reset it
while not pp_event.wait(1) and not pp_event.is_set():
time.sleep(1)
for thread in threads:
thread.join()
return pp_result[0]
def get_base_dir():
"""Get the base directory for mongol repo.
This script assumes that it is running in buildscripts/, and uses
that to find the base directory.
"""
try:
return subprocess.check_output(['git', 'rev-parse', '--show-toplevel']).rstrip()
except:
# We are not in a valid git directory. Use the script path instead.
return os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
def get_repos():
"""Get a list of Repos to check clang-format for
"""
base_dir = get_base_dir()
# Get a list of modules
# TODO: how do we filter rocks, does it matter?
mongol_modules = moduleconfig.discover_module_directories(
os.path.join(base_dir, MODULE_DIR), None)
paths = [os.path.join(base_dir, MODULE_DIR, m) for m in mongol_modules]
paths.append(base_dir)
return [Repo(p) for p in paths]
class Repo(object):
"""Class encapsulates all knowledge about a git repository, and its metadata
to run clang-format.
"""
def __init__(self, path):
self.path = path
# Get candidate files
self.candidate_files = self._get_candidate_files()
self.root = self._get_root()
def _callgito(self, args):
"""Call git for this repository
"""
# These two flags are the equivalent of -C in newer versions of Git
# but we use these to support versions back to ~1.8
return callo(['git', '--git-dir', os.path.join(self.path, ".git"),
'--work-tree', self.path] + args)
def _get_local_dir(self, path):
"""Get a directory path relative to the git root directory
"""
if os.path.isabs(path):
return os.path.relpath(path, self.root)
return path
def get_candidates(self, candidates):
"""Get the set of candidate files to check by doing an intersection
between the input list, and the list of candidates in the repository
Returns the full path to the file for clang-format to consume.
"""
# NOTE: Files may have an absolute root (i.e. leading /)
if candidates is not None and len(candidates) > 0:
candidates = [self._get_local_dir(f) for f in candidates]
valid_files = list(set(candidates).intersection(self.get_candidate_files()))
else:
valid_files = list(self.get_candidate_files())
# Get the full file name here
valid_files = [os.path.normpath(os.path.join(self.root, f)) for f in valid_files]
return valid_files
def get_root(self):
"""Get the root directory for this repository
"""
return self.root
def _get_root(self):
"""Gets the root directory for this repository from git
"""
gito = self._callgito(['rev-parse', '--show-toplevel'])
return gito.rstrip()
def get_candidate_files(self):
"""Get a list of candidate files
"""
return self._get_candidate_files()
def _get_candidate_files(self):
"""Query git to get a list of all files in the repo to consider for analysis
"""
gito = self._callgito(["ls-files"])
# This allows us to pick all the interesting files
# in the mongol and mongol-enterprise repos
file_list = [line.rstrip()
for line in gito.splitlines() if "src" in line and not "src/third_party" in line]
files_match = re.compile('\\.(h|cpp)$')
file_list = [a for a in file_list if files_match.search(a)]
return file_list
def expand_file_string(glob_pattern):
"""Expand a string that represents a set of files
"""
return [os.path.abspath(f) for f in globstar.iglob(glob_pattern)]
def get_files_to_check(files):
"""Filter the specified list of files to check down to the actual
list of files that need to be checked."""
candidates = []
# Get a list of candidate_files
candidates = [expand_file_string(f) for f in files]
candidates = list(itertools.chain.from_iterable(candidates))
repos = get_repos()
valid_files = list(itertools.chain.from_iterable([r.get_candidates(candidates) for r in repos]))
return valid_files
def get_files_to_check_from_patch(patches):
"""Take a patch file generated by git diff, and scan the patch for a list of files to check.
"""
candidates = []
# Get a list of candidate_files
check = re.compile(r"^diff --git a\/([a-z\/\.\-_0-9]+) b\/[a-z\/\.\-_0-9]+")
lines = []
for patch in patches:
with open(patch, "rb") as infile:
lines += infile.readlines()
candidates = [check.match(line).group(1) for line in lines if check.match(line)]
repos = get_repos()
valid_files = list(itertools.chain.from_iterable([r.get_candidates(candidates) for r in repos]))
return valid_files
def _get_build_dir():
"""Get the location of the scons' build directory in case we need to download clang-format
"""
return os.path.join(get_base_dir(), "build")
def _lint_files(clang_format, files):
"""Lint a list of files with clang-format
"""
clang_format = ClangFormat(clang_format, _get_build_dir())
lint_clean = parallel_process([os.path.abspath(f) for f in files], clang_format.lint)
if not lint_clean:
print("ERROR: Code Style does not match coding style")
sys.exit(1)
def lint_patch(clang_format, infile):
"""Lint patch command entry point
"""
files = get_files_to_check_from_patch(infile)
# Patch may have files that we do not want to check which is fine
if files:
_lint_files(clang_format, files)
def lint(clang_format, glob):
"""Lint files command entry point
"""
files = get_files_to_check(glob)
_lint_files(clang_format, files)
return True
def _format_files(clang_format, files):
"""Format a list of files with clang-format
"""
clang_format = ClangFormat(clang_format, _get_build_dir())
format_clean = parallel_process([os.path.abspath(f) for f in files], clang_format.format)
if not format_clean:
print("ERROR: failed to format files")
sys.exit(1)
def format_func(clang_format, glob):
"""Format files command entry point
"""
files = get_files_to_check(glob)
_format_files(clang_format, files)
def usage():
"""Print usage
"""
print("clang-format.py supports 3 commands [ lint, lint-patch, format ]. Run "
" <command> -? for more information")
def main():
"""Main entry point
"""
parser = OptionParser()
parser.add_option("-c", "--clang-format", type="string", dest="clang_format")
(options, args) = parser.parse_args(args=sys.argv)
if len(args) > 1:
command = args[1]
if command == "lint":
lint(options.clang_format, args[2:])
elif command == "lint-patch":
lint_patch(options.clang_format, args[2:])
elif command == "format":
format_func(options.clang_format, args[2:])
else:
usage()
else:
usage()
if __name__ == "__main__":
main()
|
multiprocessing.py | from __future__ import absolute_import
from __future__ import print_function
import multiprocessing
import threading
import sys
import os
import signal
from six.moves import range
from six.moves import zip
_slave = False
_rank = None
_size = None
_pipe = None
_recv_lock = None
_recv_buffer = []
_print_exceptions = True
# Compatibility fix for python >=3.8 on MacOS, where the default process start
# method changed:
if sys.version_info[:2]>=(3,3):
mp_context = multiprocessing.get_context('fork')
else :
mp_context = multiprocessing
class NoMatchingItem(Exception):
pass
def send(data, destination, tag=0):
_pipe.send((data, destination, tag))
def receive_any(source=None):
return receive(source,None,True)
def receive(source=None, tag=0, return_tag=False):
while True:
try:
item = _pop_first_match_from_reception_buffer(source, tag)
if return_tag:
return item
else:
return item[0]
except NoMatchingItem:
_receive_item_into_buffer()
NUMPY_SPECIAL_TAG = 1515
def send_numpy_array(data, destination):
send(data,destination,tag=NUMPY_SPECIAL_TAG)
def receive_numpy_array(source):
return receive(source,tag=NUMPY_SPECIAL_TAG)
def _pop_first_match_from_reception_buffer(source, tag):
for item in _recv_buffer:
if ((item[2] == tag or tag is None) and (item[1] == source or source is None)):
# consume item
_recv_buffer.remove(item)
return item
raise NoMatchingItem()
def _receive_item_into_buffer():
if _recv_lock.acquire(False):
try:
_recv_buffer.append(_pipe.recv())
finally:
_recv_lock.release()
else:
# block until a data item has been received by another thread
_recv_lock.acquire()
_recv_lock.release()
def rank():
return _rank
def size():
return _size
def barrier():
pass
def finalize():
_pipe.send("finalize")
def launch_wrapper(target_fn, rank_in, size_in, pipe_in, args_in):
global _slave, _rank, _size, _pipe, _recv_lock
_rank = rank_in
_size = size_in
_pipe = pipe_in
_recv_lock = threading.Lock()
try:
target_fn(*args_in)
finalize()
except Exception as e:
import sys, traceback
exc_type, exc_value, exc_traceback = sys.exc_info()
global _print_exceptions
if _print_exceptions:
print("Error on a sub-process:", file=sys.stderr)
traceback.print_exception(exc_type, exc_value, exc_traceback,
file=sys.stderr)
_pipe.send(("error", e))
_pipe.close()
def launch_functions(functions, args):
global _slave
if _slave:
raise RuntimeError("Multiprocessing session is already underway")
num_procs = len(functions)
child_connections, parent_connections = list(zip(*[mp_context.Pipe() for rank in range(num_procs)]))
processes = [mp_context.Process(target=launch_wrapper, args=(function, rank, num_procs, pipe, args_i))
for rank, (pipe, function, args_i) in
enumerate(zip(child_connections, functions, args))]
for proc_i in processes:
proc_i.start()
running = [True for rank in range(num_procs)]
error = False
while any(running):
for i, pipe_i in enumerate(parent_connections):
if pipe_i.poll():
message = pipe_i.recv()
if message=='finalize':
#print " ---> multiprocessing backend: finalize node ",i,running
running[i]=False
elif message[0]=='error':
error = message[1]
running = [False]
break
else:
#print "multiprocessing backend: pass message ",i,"->",message[1]
parent_connections[message[1]].send((message[0],i,message[2]))
#print "multiprocessing backend: all finished"
for pipe_i in parent_connections:
pipe_i.close()
for proc_i in processes:
if error:
#print "multiprocessing backend: send signal to",proc_i.pid
os.kill(proc_i.pid, signal.SIGTERM)
proc_i.join()
if error:
raise error
def launch(function, num_procs, args):
if num_procs is None:
raise RuntimeError("To launch a parallel session using multiprocessing backend, you need to specify the number of processors")
launch_functions([function]*num_procs, [args]*num_procs)
|
lmds.py | from pathlib import Path
from threading import Event, Thread, Lock
from queue import Queue, Empty
from signal import signal, SIGINT, SIGQUIT, SIGTERM
# Lock wrapper. Used to aid in migrating to read-write
# locks later.
class LMDSLock:
def __init__(self):
self.lock = Lock()
def acquire(self, blocking=True, timeout=-1):
self.lock.acquire(blocking, timeout)
def release(self):
self.lock.release()
# helper functions
def runAsync(func, *args):
Thread(target=func, args=args).run()
# Enhanced version of the list class with internal lock
# and some thread-safe asyncronous functions
class LMDSList(list, LMDSLock): # TODO use RWLock
def _appendSafe(self, item):
self.acquire()
self.append(item)
self.release()
def appendAsync(self, item):
runAsync(self._appendSafe, self, item)
def _insertSafe(self, index, item):
self.acquire()
self.insert(index, item)
self.release()
def insertAsync(self, index, item):
runAsync(self._insertSafe, self, index, item)
def _removeSafe(self, item):
self.acquire()
self.remove(item)
self.release()
def removeAsync(self, item):
runAsync(self._removeSafe, self, item)
# Improved version of the dict class with internal lock
# and some thread-safe asyncronous functions
class LMDSDict(dict, LMDSLock): # TODO use RWLock
def _add(self, key, value):
self.acquire()
self[key] = value
self.release()
def addAsync(self, key, value):
runAsync(self._add, self, key, value)
def _remove(self, key):
self.acquire()
del self[key]
self.release()
def removeAsync(self, key):
runAsync(self._remove, self, key)
done = Event() # set to true when told to exit
rules = LMDSList()
sources = LMDSList()
targets = LMDSDict()
messages = Queue()
exitFunctions = []
class LMDSException(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return message
class NonexistantRuleError(LMDSException):
def __init__(self, rule, message):
self.rule = rule
LMDSException.__init__(self, message)
def __str__(self):
return repr(self.rule) + ": " + self.message
class Message:
pass
class Rule:
def __init__(self, match, action):
self.match = match
self.action = action
def __eq__(self, other):
return self.match == other.match and self.action == other.action
# builtin rule actions
class Actions:
# dispatch message to target specified by message.target
def dispatchToTarget(message):
targets.acquire()
if message.target in targets:
del message.target
targets[message.target].dispatch(message)
return True
else:
pass # TODO: handle properly once we have a logging system
# drop the message
def drop(message):
return true
# builtin rule matchers
class Matchers:
# matches any message containing a target attribute
def target(message):
return hasattr(message, 'target')
# some preconfigured rules
class Rules:
# sends the message to the target specified in the
# target attribute (if possible)
dispatchToTarget = Rule(Matchers.target, Actions.dispatchToTarget)
# signal handler for 'exit' signals (INT, QUIT, TERM)
def exitHandler(number, frame):
done.set()
# Any messages not dispatched are dropped.
def processMessage(message):
for rule in rules:
# If rule.match returns true then call rule.action.
# If either returns false the message has not been
# handled completely
if rule.match(message) and rule.action(message):
break;
|
app_action.py | from app_base import *
from app_data import *
import etk_helper
@api.route('/projects/<project_name>/actions/project_config')
class ActionProjectConfig(Resource):
@requires_auth
def post(self, project_name): # frontend needs to fresh to get all configs again
if project_name not in data:
return rest.not_found('project {} not found'.format(project_name))
try:
parse = reqparse.RequestParser()
parse.add_argument('file_data', type=werkzeug.FileStorage, location='files')
args = parse.parse_args()
# save to tmp path and test
tmp_project_config_path = os.path.join(get_project_dir_path(project_name),
'working_dir/uploaded_project_config.tar.gz')
tmp_project_config_extracted_path = os.path.join(get_project_dir_path(project_name),
'working_dir/uploaded_project_config')
args['file_data'].save(tmp_project_config_path)
with tarfile.open(tmp_project_config_path, 'r:gz') as tar:
tar.extractall(tmp_project_config_extracted_path)
# master_config
with open(os.path.join(tmp_project_config_extracted_path, 'master_config.json'), 'r') as f:
new_master_config = json.loads(f.read())
# TODO: validation and sanitizing
# overwrite indices
new_master_config['index'] = {
'sample': project_name,
'full': project_name + '_deployed',
'version': 0
}
# overwrite configuration
if 'configuration' not in new_master_config:
new_master_config['configuration'] = dict()
new_master_config['configuration']['sandpaper_sample_url'] \
= data[project_name]['master_config']['configuration']['sandpaper_sample_url']
new_master_config['configuration']['sandpaper_full_url'] \
= data[project_name]['master_config']['configuration']['sandpaper_full_url']
# overwrite previous master config
data[project_name]['master_config'] = new_master_config
update_master_config_file(project_name)
# replace dependencies
distutils.dir_util.copy_tree(
os.path.join(tmp_project_config_extracted_path, 'glossaries'),
os.path.join(get_project_dir_path(project_name), 'glossaries')
)
distutils.dir_util.copy_tree(
os.path.join(tmp_project_config_extracted_path, 'spacy_rules'),
os.path.join(get_project_dir_path(project_name), 'spacy_rules')
)
distutils.dir_util.copy_tree(
os.path.join(tmp_project_config_extracted_path, 'landmark_rules'),
os.path.join(get_project_dir_path(project_name), 'landmark_rules')
)
distutils.dir_util.copy_tree(
os.path.join(tmp_project_config_extracted_path, 'working_dir/generated_em'),
os.path.join(get_project_dir_path(project_name), 'working_dir/generated_em')
)
distutils.dir_util.copy_tree(
os.path.join(tmp_project_config_extracted_path, 'working_dir/additional_ems'),
os.path.join(get_project_dir_path(project_name), 'working_dir/additional_ems')
)
# etl config
tmp_etl_config = os.path.join(tmp_project_config_extracted_path,
'working_dir/etl_config.json')
if os.path.exists(tmp_etl_config):
shutil.copyfile(tmp_etl_config, os.path.join(get_project_dir_path(project_name),
'working_dir/etl_config.json'))
# landmark
tmp_landmark_config_path = os.path.join(tmp_project_config_extracted_path,
'working_dir/_landmark_config.json')
if os.path.exists(tmp_landmark_config_path):
with open(tmp_landmark_config_path, 'r') as f:
ActionProjectConfig.landmark_import(project_name, f.read())
return rest.created()
except Exception as e:
logger.exception('fail to import project config')
return rest.internal_error('fail to import project config')
finally:
# always clean up, or some of the files may affect new uploaded files
if os.path.exists(tmp_project_config_path):
os.remove(tmp_project_config_path)
if os.path.exists(tmp_project_config_extracted_path):
shutil.rmtree(tmp_project_config_extracted_path)
def get(self, project_name):
if project_name not in data:
return rest.not_found('project {} not found'.format(project_name))
export_path = os.path.join(get_project_dir_path(project_name), 'working_dir/project_config.tar.gz')
# tarzip file
with tarfile.open(export_path, 'w:gz') as tar:
tar.add(os.path.join(get_project_dir_path(project_name), 'master_config.json'),
arcname='master_config.json')
tar.add(os.path.join(get_project_dir_path(project_name), 'glossaries'),
arcname='glossaries')
tar.add(os.path.join(get_project_dir_path(project_name), 'spacy_rules'),
arcname='spacy_rules')
tar.add(os.path.join(get_project_dir_path(project_name), 'landmark_rules'),
arcname='landmark_rules')
tar.add(os.path.join(get_project_dir_path(project_name), 'working_dir/generated_em'),
arcname='working_dir/generated_em')
tar.add(os.path.join(get_project_dir_path(project_name), 'working_dir/additional_ems'),
arcname='working_dir/additional_ems')
# etl config
etl_config_path = os.path.join(get_project_dir_path(project_name),
'working_dir/etl_config.json')
if os.path.exists(etl_config_path):
tar.add(etl_config_path, arcname='working_dir/etl_config.json')
# landmark
landmark_config = ActionProjectConfig.landmark_export(project_name)
if len(landmark_config) > 0:
landmark_config_path = os.path.join(
get_project_dir_path(project_name), 'working_dir/_landmark_config.json')
write_to_file(json.dumps(landmark_config), landmark_config_path)
tar.add(landmark_config_path, arcname='working_dir/_landmark_config.json')
export_file_name = project_name + '_' + time.strftime("%Y%m%d%H%M%S") + '.tar.gz'
ret = send_file(export_path, mimetype='application/gzip',
as_attachment=True, attachment_filename=export_file_name)
ret.headers['Access-Control-Expose-Headers'] = 'Content-Disposition'
return ret
@staticmethod
def landmark_export(project_name):
try:
url = config['landmark']['export'].format(project_name=project_name)
resp = requests.post(url)
return resp.json()
except Exception as e:
logger.exception('landmark export error')
return list()
@staticmethod
def landmark_import(project_name, landmark_config):
try:
url = config['landmark']['import'].format(project_name=project_name)
resp = requests.post(url, data=landmark_config)
except Exception as e:
logger.exception('landmark import error')
# @api.route('/projects/<project_name>/actions/etk_filters')
# class ActionProjectEtkFilters(Resource):
# @requires_auth
# def post(self, project_name):
# if project_name not in data:
# return rest.not_found('project {} not found'.format(project_name))
#
# input = request.get_json(force=True)
# filtering_rules = input.get('filters', {})
#
# try:
# # validation
# for tld, rules in filtering_rules.items():
# if tld.strip() == '' or not isinstance(rules, list):
# return rest.bad_request('Invalid TLD')
# for rule in rules:
# if 'field' not in rule or rule['field'].strip() == '':
# return rest.bad_request('Invalid Field in TLD: {}'.format(tld))
# if 'action' not in rule or rule['action'] not in ('no_action', 'keep', 'discard'):
# return rest.bad_request('Invalid action in TLD: {}, Field {}'.format(tld, rule['field']))
# if 'regex' not in rule:
# return rest.bad_request('Invalid regex in TLD: {}, Field {}'.format(tld, rule['field']))
# try:
# re.compile(rule['regex'])
# except re.error:
# return rest.bad_request(
# 'Invalid regex in TLD: {}, Field: {}'.format(tld, rule['field']))
#
# # write to file
# dir_path = os.path.join(get_project_dir_path(project_name), 'working_dir')
# if not os.path.exists(dir_path):
# os.mkdir(dir_path)
# config_path = os.path.join(dir_path, 'etk_filters.json')
# write_to_file(json.dumps(input), config_path)
# return rest.created()
# except Exception as e:
# logger.exception('fail to import ETK filters')
# return rest.internal_error('fail to import ETK filters')
#
# def get(self, project_name):
# if project_name not in data:
# return rest.not_found('project {} not found'.format(project_name))
#
# ret = {'filters': {}}
# config_path = os.path.join(get_project_dir_path(project_name),
# 'working_dir/etk_filters.json')
# if os.path.exists(config_path):
# with open(config_path, 'r') as f:
# ret = json.loads(f.read())
#
# return ret
@api.route('/projects/<project_name>/actions/<action_name>')
class Actions(Resource):
@requires_auth
def post(self, project_name, action_name):
if project_name not in data:
return rest.not_found('project {} not found'.format(project_name))
# if action_name == 'add_data':
# return self._add_data(project_name)
if action_name == 'desired_num':
return self.update_desired_num(project_name)
elif action_name == 'extract':
return self.etk_extract(project_name)
elif action_name == 'recreate_mapping':
return self.recreate_mapping(project_name)
elif action_name == 'landmark_extract':
return self.landmark_extract(project_name)
elif action_name == 'reload_blacklist':
return self.reload_blacklist(project_name)
else:
return rest.not_found('action {} not found'.format(action_name))
@requires_auth
def get(self, project_name, action_name):
if project_name not in data:
return rest.not_found('project {} not found'.format(project_name))
if action_name == 'extract':
return self._get_extraction_status(project_name)
else:
return rest.not_found('action {} not found'.format(action_name))
@requires_auth
def delete(self, project_name, action_name):
if action_name == 'extract':
if not Actions._etk_stop(project_name):
return rest.internal_error('failed to kill_etk in ETL')
return rest.deleted()
@staticmethod
def _get_extraction_status(project_name):
ret = dict()
parser = reqparse.RequestParser()
parser.add_argument('value', type=str)
args = parser.parse_args()
if args['value'] is None:
args['value'] = 'all'
if args['value'] in ('all', 'etk_status'):
ret['etk_status'] = Actions._is_etk_running(project_name)
if args['value'] in ('all', 'tld_statistics'):
tld_list = dict()
with data[project_name]['locks']['status']:
for tld in data[project_name]['status']['total_docs'].keys():
if tld not in data[project_name]['status']['desired_docs']:
data[project_name]['status']['desired_docs'][tld] = 0
if tld in data[project_name]['status']['total_docs']:
tld_obj = {
'tld': tld,
'total_num': data[project_name]['status']['total_docs'][tld],
'es_num': 0,
'es_original_num': 0,
'desired_num': data[project_name]['status']['desired_docs'][tld]
}
tld_list[tld] = tld_obj
# query es count if doc exists
query = """
{
"aggs": {
"group_by_tld_original": {
"filter": {
"bool": {
"must_not": {
"term": {
"created_by": "etk"
}
}
}
},
"aggs": {
"grouped": {
"terms": {
"field": "tld.raw",
"size": 2147483647
}
}
}
},
"group_by_tld": {
"terms": {
"field": "tld.raw",
"size": 2147483647
}
}
},
"size":0
}
"""
es = ES(config['es']['sample_url'])
r = es.search(project_name, data[project_name]['master_config']['root_name'],
query, ignore_no_index=True, filter_path=['aggregations'])
if r is not None:
for obj in r['aggregations']['group_by_tld']['buckets']:
# check if tld is in uploaded file
tld = obj['key']
if tld not in tld_list:
tld_list[tld] = {
'tld': tld,
'total_num': 0,
'es_num': 0,
'es_original_num': 0,
'desired_num': 0
}
tld_list[tld]['es_num'] = obj['doc_count']
for obj in r['aggregations']['group_by_tld_original']['grouped']['buckets']:
# check if tld is in uploaded file
tld = obj['key']
if tld not in tld_list:
tld_list[tld] = {
'tld': tld,
'total_num': 0,
'es_num': 0,
'es_original_num': 0,
'desired_num': 0
}
tld_list[tld]['es_original_num'] = obj['doc_count']
ret['tld_statistics'] = list(tld_list.values())
return ret
@staticmethod
def _is_etk_running(project_name):
url = config['etl']['url'] + '/etk_status/' + project_name
resp = requests.get(url)
if resp.status_code // 100 != 2:
return rest.internal_error('error in getting etk_staus')
return resp.json()['etk_processes'] > 0
@staticmethod
def update_desired_num(project_name):
# {
# "tlds": {
# 'tld1': 100,
# 'tld2': 200
# }
# }
input = request.get_json(force=True)
tld_list = input.get('tlds', {})
for tld, desired_num in tld_list.items():
desired_num = max(desired_num, 0)
desired_num = min(desired_num, 999999999)
with data[project_name]['locks']['status']:
if tld not in data[project_name]['status']['desired_docs']:
data[project_name]['status']['desired_docs'][tld] = dict()
data[project_name]['status']['desired_docs'][tld] = desired_num
set_status_dirty(project_name)
return rest.created()
@staticmethod
def landmark_extract(project_name):
# {
# "tlds": {
# 'tld1': 100,
# 'tld2': 200
# }
# }
input = request.get_json(force=True)
tld_list = input.get('tlds', {})
payload = dict()
for tld, num_to_run in tld_list.items():
if tld in data[project_name]['data']:
# because the catalog can be huge, can not use a simple pythonic random here
num_to_select = min(num_to_run, len(data[project_name]['data'][tld]))
selected = set()
while len(selected) < num_to_select:
cand_num = random.randint(0, num_to_select - 1)
if cand_num not in selected:
selected.add(cand_num)
# construct payload
idx = 0
for doc_id, catalog_obj in data[project_name]['data'][tld].items():
if idx not in selected:
idx += 1
continue
# payload format
# {
# "tld1": {"documents": [{doc_id, raw_content_path, url}, {...}, ...]},
# }
payload[tld] = payload.get(tld, dict())
payload[tld]['documents'] = payload[tld].get('documents', list())
catalog_obj['doc_id'] = doc_id
payload[tld]['documents'].append(catalog_obj)
idx += 1
url = config['landmark']['create'].format(project_name=project_name)
resp = requests.post(url, json.dumps(payload), timeout=10)
if resp.status_code // 100 != 2:
return rest.internal_error('Landmark error: {}'.format(resp.status_code))
return rest.accepted()
@staticmethod
def _generate_etk_config(project_name):
glossary_dir = os.path.join(get_project_dir_path(project_name), 'glossaries')
inferlink_dir = os.path.join(get_project_dir_path(project_name), 'landmark_rules')
working_dir = os.path.join(get_project_dir_path(project_name), 'working_dir')
spacy_dir = os.path.join(get_project_dir_path(project_name), 'spacy_rules')
content = etk_helper.generate_base_etk_module(
data[project_name]['master_config'],
glossary_dir=glossary_dir,
inferlink_dir=inferlink_dir,
working_dir=working_dir,
spacy_dir=spacy_dir
)
revision = hashlib.sha256(content.encode('utf-8')).hexdigest().upper()[:6]
output_path = os.path.join(get_project_dir_path(project_name),
'working_dir/generated_em', 'em_base.py'.format(revision))
archive_output_path = os.path.join(get_project_dir_path(project_name),
'working_dir/generated_em', 'archive_em_{}.py'.format(revision))
additional_ems_path = os.path.join(get_project_dir_path(project_name), 'working_dir/additional_ems')
generated_additional_ems_path = os.path.join(get_project_dir_path(project_name),
'working_dir/generated_additional_ems')
etk_helper.generated_additional_ems(additional_ems_path, generated_additional_ems_path, glossary_dir,
inferlink_dir, working_dir, spacy_dir)
write_to_file(content, output_path)
write_to_file(content, archive_output_path)
@staticmethod
def recreate_mapping(project_name):
logger.info('recreate_mapping')
# 1. kill etk (and clean up previous queue)
data[project_name]['data_pushing_worker'].stop_adding_data = True
if not Actions._etk_stop(project_name, clean_up_queue=True):
return rest.internal_error('failed to kill_etk in ETL')
# 2. create etk config and snapshot
Actions._generate_etk_config(project_name)
# add config for etl
# when creating kafka container, group id is not there. set consumer to read from start.
etl_config_path = os.path.join(get_project_dir_path(project_name), 'working_dir/etl_config.json')
if not os.path.exists(etl_config_path):
etl_config = {
"input_args": {
"auto_offset_reset": "earliest",
"fetch_max_bytes": 52428800,
"max_partition_fetch_bytes": 10485760,
"max_poll_records": 10
},
"output_args": {
"max_request_size": 10485760,
"compression_type": "gzip"
}
}
write_to_file(json.dumps(etl_config, indent=2), etl_config_path)
# 3. sandpaper
# 3.1 delete previous index
url = '{}/{}'.format(
config['es']['sample_url'],
project_name
)
try:
resp = requests.delete(url, timeout=10)
except:
pass # ignore no index error
# 3.2 create new index
url = '{}/mapping?url={}&project={}&index={}&endpoint={}'.format(
config['sandpaper']['url'],
config['sandpaper']['ws_url'],
project_name,
data[project_name]['master_config']['index']['sample'],
config['es']['sample_url']
)
resp = requests.put(url, timeout=10)
if resp.status_code // 100 != 2:
return rest.internal_error('failed to create index in sandpaper')
# 3.3 switch index
url = '{}/config?url={}&project={}&index={}&endpoint={}'.format(
config['sandpaper']['url'],
config['sandpaper']['ws_url'],
project_name,
data[project_name]['master_config']['index']['sample'],
config['es']['sample_url']
)
resp = requests.post(url, timeout=10)
if resp.status_code // 100 != 2:
return rest.internal_error('failed to switch index in sandpaper')
# 4. clean up added data status
logger.info('re-add data')
with data[project_name]['locks']['status']:
if 'added_docs' not in data[project_name]['status']:
data[project_name]['status']['added_docs'] = dict()
for tld in data[project_name]['status']['added_docs'].keys():
data[project_name]['status']['added_docs'][tld] = 0
with data[project_name]['locks']['data']:
for tld in data[project_name]['data'].keys():
for doc_id in data[project_name]['data'][tld]:
data[project_name]['data'][tld][doc_id]['add_to_queue'] = False
set_status_dirty(project_name)
# 5. restart extraction
data[project_name]['data_pushing_worker'].stop_adding_data = False
return Actions.etk_extract(project_name)
@staticmethod
def reload_blacklist(project_name):
if project_name not in data:
return rest.not_found('project {} not found'.format(project_name))
# 1. kill etk
if not Actions._etk_stop(project_name):
return rest.internal_error('failed to kill_etk in ETL')
# 2. generate etk config
Actions._generate_etk_config(project_name)
# 3. fetch and re-add data
t = threading.Thread(target=Data._reload_blacklist_worker, args=(project_name,), name='reload_blacklist')
t.start()
data[project_name]['threads'].append(t)
return rest.accepted()
@staticmethod
def _reload_blacklist_worker(project_name):
# copy here to avoid modification while iteration
for field_name, field_obj in data[project_name]['master_config']['fields'].items():
if 'blacklists' not in field_obj or len(field_obj['blacklists']) == 0:
continue
# get all stop words and generate query
# only use the last blacklist if there are multiple blacklists
blacklist = data[project_name]['master_config']['fields'][field_name]['blacklists'][-1]
file_path = os.path.join(get_project_dir_path(project_name),
'glossaries', '{}.txt'.format(blacklist))
query_conditions = []
with open(file_path, 'r') as f:
for line in f:
key = line.strip()
if len(key) == 0:
continue
query_conditions.append(
'{{ "term": {{"knowledge_graph.{field_name}.key": "{key}"}} }}'
.format(field_name=field_name, key=key))
query = """
{{
"size": 1000,
"query": {{
"bool": {{
"should": [{conditions}]
}}
}},
"_source": ["doc_id", "tld"]
}}
""".format(conditions=','.join(query_conditions))
logger.debug(query)
# init query
scroll_alive_time = '1m'
es = ES(config['es']['sample_url'])
r = es.search(project_name, data[project_name]['master_config']['root_name'], query,
params={'scroll': scroll_alive_time}, ignore_no_index=False)
if r is None:
return
scroll_id = r['_scroll_id']
Actions._re_add_docs(r, project_name)
# scroll queries
while True:
# use the es object here directly
r = es.es.scroll(scroll_id=scroll_id, scroll=scroll_alive_time)
if r is None:
break
if len(r['hits']['hits']) == 0:
break
Actions._re_add_docs(r, project_name)
Actions.etk_extract(project_name)
@staticmethod
def _re_add_docs(resp, project_name):
input_topic = project_name + '_in'
for obj in resp['hits']['hits']:
doc_id = obj['_source']['doc_id']
tld = obj['_source']['tld']
try:
logger.info('re-add doc %s (%s)', doc_id, tld)
ret, msg = Actions._publish_to_kafka_input_queue(
doc_id, data[project_name]['data'][tld][doc_id], g_vars['kafka_producer'], input_topic)
if not ret:
logger.error('Error of re-adding data to Kafka: %s', msg)
except Exception as e:
logger.exception('error in re_add_docs')
@staticmethod
def etk_extract(project_name, clean_up_queue=False):
if Actions._is_etk_running(project_name):
return rest.exists('already running')
# etk_config_file_path = os.path.join(
# get_project_dir_path(project_name), 'working_dir/etk_config.json')
# if not os.path.exists(etk_config_file_path):
# return rest.not_found('No etk config')
# recreate etk config every time
Actions._generate_etk_config(project_name)
url = '{}/{}'.format(
config['es']['sample_url'],
project_name
)
try:
resp = requests.get(url, timeout=10)
if resp.status_code // 100 != 2:
return rest.not_found('No es index')
except Exception as e:
return rest.not_found('No es index')
url = config['etl']['url'] + '/run_etk'
payload = {
'project_name': project_name,
'number_of_workers': config['etl']['number_of_workers']
}
if clean_up_queue:
payload['input_offset'] = 'seek_to_end'
payload['output_offset'] = 'seek_to_end'
resp = requests.post(url, json.dumps(payload), timeout=config['etl']['timeout'])
if resp.status_code // 100 != 2:
return rest.internal_error('failed to run_etk in ETL')
return rest.accepted()
@staticmethod
def _etk_stop(project_name, wait_till_kill=True, clean_up_queue=False):
url = config['etl']['url'] + '/kill_etk'
payload = {
'project_name': project_name
}
if clean_up_queue:
payload['input_offset'] = 'seek_to_end'
payload['output_offset'] = 'seek_to_end'
resp = requests.post(url, json.dumps(payload), timeout=config['etl']['timeout'])
if resp.status_code // 100 != 2:
logger.error('failed to kill_etk in ETL')
return False
if wait_till_kill:
while True:
time.sleep(5)
if not Actions._is_etk_running(project_name):
break
return True
@staticmethod
def _publish_to_kafka_input_queue(doc_id, catalog_obj, producer, topic):
try:
with open(catalog_obj['json_path'], 'r', encoding='utf-8') as f:
doc_obj = json.loads(f.read())
with open(catalog_obj['raw_content_path'], 'r', encoding='utf-8') as f:
doc_obj['raw_content'] = f.read() # .decode('utf-8', 'ignore')
except Exception as e:
logger.exception('error in reading file from catalog')
return False, 'error in reading file from catalog'
try:
r = producer.send(topic, doc_obj)
r.get(timeout=60) # wait till sent
logger.info('sent %s to topic %s', doc_id, topic)
except Exception as e:
logger.exception('error in sending data to kafka queue')
return False, 'error in sending data to kafka queue'
return True, ''
class DataPushingWorker(threading.Thread):
def __init__(self, project_name, sleep_interval):
super(DataPushingWorker, self).__init__()
self.project_name = project_name
self.exit_signal = False
self.stop_adding_data = False
self.is_adding_data = False
self.sleep_interval = sleep_interval
# set up input kafka
self.producer = g_vars['kafka_producer']
self.input_topic = project_name + '_in'
def get_status(self):
return {
'stop_adding_data': self.stop_adding_data,
'is_adding_data': self.is_adding_data,
'sleep_interval': self.sleep_interval
}
def run(self):
logger.info('thread DataPushingWorker running... %s', self.project_name)
while not self.exit_signal:
if not self.stop_adding_data:
self._add_data_worker(self.project_name, self.producer, self.input_topic)
# wait interval
t = self.sleep_interval * 10
while t > 0 and not self.exit_signal:
time.sleep(0.1)
t -= 1
def _add_data_worker(self, project_name, producer, input_topic):
got_lock = data[project_name]['locks']['data'].acquire(False)
try:
if not got_lock or self.stop_adding_data:
return
for tld in data[project_name]['data'].keys():
if self.stop_adding_data:
break
with data[project_name]['locks']['status']:
if tld not in data[project_name]['status']['added_docs']:
data[project_name]['status']['added_docs'][tld] = 0
if tld not in data[project_name]['status']['desired_docs']:
data[project_name]['status']['desired_docs'][tld] = \
data[project_name]['master_config'].get('default_desired_num', 0)
if tld not in data[project_name]['status']['total_docs']:
data[project_name]['status']['total_docs'][tld] = 0
added_num = data[project_name]['status']['added_docs'][tld]
total_num = data[project_name]['status']['total_docs'][tld]
desired_num = data[project_name]['status']['desired_docs'][tld]
desired_num = min(desired_num, total_num)
# only add docs to queue if desired num is larger than added num
if desired_num > added_num:
self.is_adding_data = True
# update mark in catalog
num_to_add = desired_num - added_num
added_num_this_round = 0
for doc_id in data[project_name]['data'][tld].keys():
if not self.stop_adding_data:
# finished
if num_to_add <= 0:
break
# already added
if data[project_name]['data'][tld][doc_id]['add_to_queue']:
continue
# mark data
data[project_name]['data'][tld][doc_id]['add_to_queue'] = True
num_to_add -= 1
added_num_this_round += 1
# publish to kafka queue
ret, msg = Actions._publish_to_kafka_input_queue(
doc_id, data[project_name]['data'][tld][doc_id], producer, input_topic)
if not ret:
logger.error('Error of pushing data to Kafka: %s', msg)
# roll back
data[project_name]['data'][tld][doc_id]['add_to_queue'] = False
num_to_add += 1
added_num_this_round -= 1
self.is_adding_data = False
if added_num_this_round > 0:
with data[project_name]['locks']['status']:
data[project_name]['status']['added_docs'][tld] = added_num + added_num_this_round
set_catalog_dirty(project_name)
set_status_dirty(project_name)
except Exception as e:
logger.exception('exception in Actions._add_data_worker() data lock')
finally:
if got_lock:
data[project_name]['locks']['data'].release()
class MemoryDumpWorker(threading.Thread):
def __init__(self, project_name, sleep_interval, function, kwargs=dict()):
super(MemoryDumpWorker, self).__init__()
self.project_name = project_name
self.exit_signal = False
init_time = time.time()
self.file_timestamp = init_time
self.memory_timestamp = init_time
self.sleep_interval = sleep_interval
self.function = function
self.kwargs = kwargs
def get_status(self):
return {
'sleep_interval': self.sleep_interval,
'file_timestamp': self.file_timestamp,
'memory_timestamp': self.memory_timestamp,
'is_dirty': self.file_timestamp != self.memory_timestamp
}
def run_function(self):
memory_timestamp = self.memory_timestamp
if self.file_timestamp < memory_timestamp:
self.function(**self.kwargs)
self.file_timestamp = memory_timestamp
def run(self):
logger.info('thread MemoryDumpWorker (%s) running... %s', self.function.__name__, self.project_name)
while not self.exit_signal:
self.run_function()
# wait interval
t = self.sleep_interval * 10
while t > 0 and not self.exit_signal:
time.sleep(0.1)
t -= 1
# make sure memory data is dumped
self.run_function()
def start_threads_and_locks(project_name):
data[project_name]['locks']['data'] = threading.Lock()
data[project_name]['locks']['status'] = threading.Lock()
data[project_name]['locks']['catalog_log'] = threading.Lock()
data[project_name]['data_pushing_worker'] = DataPushingWorker(
project_name, config['data_pushing_worker_backoff_time'])
data[project_name]['data_pushing_worker'].start()
data[project_name]['status_memory_dump_worker'] = MemoryDumpWorker(
project_name, config['status_memory_dump_backoff_time'],
update_status_file, kwargs={'project_name': project_name})
data[project_name]['status_memory_dump_worker'].start()
data[project_name]['catalog_memory_dump_worker'] = MemoryDumpWorker(
project_name, config['catalog_memory_dump_backoff_time'],
update_catalog_file, kwargs={'project_name': project_name})
data[project_name]['catalog_memory_dump_worker'].start()
def stop_threads_and_locks(project_name):
try:
data[project_name]['data_pushing_worker'].exit_signal = True
data[project_name]['data_pushing_worker'].join()
data[project_name]['status_memory_dump_worker'].exit_signal = True
data[project_name]['status_memory_dump_worker'].join()
data[project_name]['catalog_memory_dump_worker'].exit_signal = True
data[project_name]['catalog_memory_dump_worker'].join()
logger.info('threads of project %s exited', project_name)
except:
pass
|
main.py | # Launch of an autonomous robo-advisor
from train import train_agent
from trade import trade_agent
from multiprocessing import Process
from multiprocessing import Lock
from utils import primary_initialization_window_time_rmse
individual_agent_number_0 = 0
individual_agent_number_1 = 1
# Number of workers/agents individual_agent_number_
number_workers = 2
# Initialize priority time window of seconds and the initial error
primary_window_time = 90
primary_initialization_window_time_rmse(seconds=primary_window_time, number_workers=number_workers)
lock = Lock()
if __name__ == '__main__':
training_process_1 = Process(target=train_agent, args=(lock, individual_agent_number_0))
training_process_2 = Process(target=train_agent, args=(lock, individual_agent_number_1))
trading_process = Process(target=trade_agent, args=(lock,number_workers))
#########################
training_process_1.start()
training_process_2.start()
trading_process.start()
#########################
training_process_1.join()
training_process_2.join()
trading_process.join()
|
sensing_interface.py | #!/usr/bin/env python
import rospy
import rospkg
import re
import threading
import numpy as np
from threading import Lock
import imp
from rosplan_knowledge_msgs.srv import KnowledgeUpdateServiceArray, KnowledgeUpdateServiceArrayRequest
from rosplan_knowledge_msgs.srv import GetDomainPredicateDetailsService, GetDomainPredicateDetailsServiceRequest
from rosplan_knowledge_msgs.srv import GetDomainAttributeService
from rosplan_knowledge_msgs.srv import GetAttributeService, GetAttributeServiceRequest
from rosplan_knowledge_msgs.srv import GetInstanceService, GetInstanceServiceRequest
from rosplan_knowledge_msgs.srv import SetNamedBool, SetNamedBoolRequest
from rosplan_knowledge_msgs.msg import KnowledgeItem
from diagnostic_msgs.msg import KeyValue
class RosplanSensing:
def __init__(self):
self.mutex = Lock()
self.srv_mutex = Lock()
################################################################################################################
# Init clients and publishers
rospy.wait_for_service('/rosplan_knowledge_base/update_array')
self.update_kb_srv = rospy.ServiceProxy('/rosplan_knowledge_base/update_array', KnowledgeUpdateServiceArray)
rospy.wait_for_service('/rosplan_knowledge_base/domain/predicate_details')
self.get_predicates_srv = rospy.ServiceProxy('/rosplan_knowledge_base/domain/predicate_details', GetDomainPredicateDetailsService)
rospy.wait_for_service('/rosplan_knowledge_base/domain/functions')
self.get_functions_srv = rospy.ServiceProxy('/rosplan_knowledge_base/domain/functions', GetDomainAttributeService)
rospy.wait_for_service('/rosplan_knowledge_base/state/instances')
self.get_instances_srv = rospy.ServiceProxy('/rosplan_knowledge_base/state/instances', GetInstanceService)
rospy.wait_for_service('/rosplan_knowledge_base/state/propositions')
self.get_state_propositions_srv = rospy.ServiceProxy('/rosplan_knowledge_base/state/propositions', GetAttributeService)
rospy.wait_for_service('/rosplan_knowledge_base/state/functions')
self.get_state_functions_srv = rospy.ServiceProxy('/rosplan_knowledge_base/state/functions', GetAttributeService)
self.set_sensed_predicate_srv = rospy.ServiceProxy('/rosplan_knowledge_base/update_sensed_predicates', SetNamedBool)
################################################################################################################
# Get cfg
self.cfg_topics = self.cfg_service = {}
self.functions_path = None
found_config = False
if rospy.has_param('~topics'):
self.cfg_topics = rospy.get_param('~topics')
found_config = True
if rospy.has_param('~services'):
self.cfg_service = rospy.get_param('~services')
found_config = True
if rospy.has_param('~functions'):
self.functions_path = rospy.get_param('~functions')[0]
regexp = re.compile('\$\(find (.*)\)')
groups = regexp.match(self.functions_path).groups()
if len(groups):
try:
ros_pkg_path = rospkg.RosPack().get_path(groups[0])
self.functions_path = regexp.sub(ros_pkg_path, self.functions_path)
except:
rospy.logerr('KCL: (RosplanSensing) Error: Package %s was not found! Fix configuration file and retry.' % groups[0])
rospy.signal_shutdown('Wrong path in cfg file')
return
if not found_config:
rospy.logerr('KCL: (RosplanSensing) Error: configuration file is not defined!')
rospy.signal_shutdown('Config not found')
return
################################################################################################################
# Load scripts
if self.functions_path:
self.scripts = imp.load_source('sensing_scripts', self.functions_path)
# Declare tools in the scripts module:
self.scripts.get_kb_attribute = self.get_kb_attribute
self.scripts.rospy = rospy
################################################################################################################
# Init variables
self.sensed_topics = {}
self.sensed_services = {}
self.params = {} # Params defined for each predicate
######
# Subscribe to all the topics
self.offset = {} # Offset for reading cfg
for predicate_name, predicate_info in self.cfg_topics.iteritems():
if type(predicate_info) is list: # We have nested elements in the predicate
for i, pi in enumerate(predicate_info):
pi['sub_idx'] = i
subscribed = self.subscribe_topic(predicate_name, pi)
if not subscribed:
rospy.loginfo('Could not subscribe for predicate ' + predicate_name + ' and config: ' + str(pi))
continue
else:
predicate_info['sub_idx'] = 0 # As we don't have nested elements in this predicate
subscribed = self.subscribe_topic(predicate_name, predicate_info)
if not subscribed:
rospy.loginfo('Could not subscribe for predicate ' + predicate_name + ' and config: ' + str(predicate_info))
############
# Create clients for all the services
self.service_clients = []
self.service_names = []
self.service_type_names = []
self.service_predicate_names = []
self.last_called_time = []
self.time_between_calls = []
self.request_src = []
self.response_process_src = []
self.clients_sub_idx = []
for predicate_name, predicate_info in self.cfg_service.iteritems():
if type(predicate_info) is list:
for i, pi in enumerate(predicate_info):
pi['sub_idx'] = i
client_created = self.create_service_client(predicate_name, pi)
if not client_created:
rospy.loginfo('Could not create client for predicate ' + predicate_name + ' and config: ' + str(pi))
continue
else:
predicate_info['sub_idx'] = 0 # As we don't have nested elements in this predicate
client_created = self.create_service_client(predicate_name, predicate_info)
if not client_created:
rospy.loginfo('Could not create client for predicate ' + predicate_name + ' and config: ' + str(predicate_info))
continue
# Returns (bool, bool), first tells if the parameters could be loaded, second if parameters were loaded from config file and false if they were taken directly from the kb
def load_params(self, predicate_name, predicate_info):
# Check if predicate
kb_info = None
try:
kb_info = self.get_predicates_srv.call(GetDomainPredicateDetailsServiceRequest(predicate_name)).predicate
except Exception as e:
kb_info = self.get_function_params(predicate_name)
if not kb_info:
rospy.logerr("KCL: (RosplanSensing) Could not find predicate or function %s" % predicate_name)
return (False, False)
if predicate_name not in self.params: # Prepare dictionary
self.params[predicate_name] = {}
# Obtain all the instances for each parameter
kb_params = []
for p in kb_info.typed_parameters:
instances = self.get_instances_srv.call(GetInstanceServiceRequest(p.value)).instances
kb_params.append(instances)
if 'params' in predicate_info:
params = predicate_info['params']
if len(kb_params) != len(params):
rospy.logerr("KCL: (RosplanSensing) Parameters defined for predicate %s don't match the knowledge base" % predicate_name)
rospy.signal_shutdown('Wrong cfg file parameters definition')
return (False, True)
# Check params
wildcard = False
for i, p in enumerate(params):
if p != '*' and p != '_':
if p in kb_params[i]:
kb_params[i] = [p]
else:
rospy.logerr('KCL: (RosplanSensing) Unknown parameter instance "%s" of type "%s" for predicate "%s"',
p, kb_info.typed_parameters[i].value, predicate_name)
rospy.signal_shutdown('Wrong cfg file parameters definition')
return (False, True)
else:
wildcard = True
# If the params are fully instantiated we store them as a list, else it will be a matrix with a list of
# instances per parameter
self.params[predicate_name][predicate_info['sub_idx']] = kb_params if wildcard else params
return (True, True)
else:
self.params[predicate_name][predicate_info['sub_idx']] = kb_params
return (True, False)
def subscribe_topic(self, predicate_name, predicate_info):
params_loaded = self.load_params(predicate_name, predicate_info) # If parameters found, add 1 to the indexes
if not params_loaded[0]:
return False
if len(predicate_info) < 2 + int(params_loaded[1]):
rospy.logerr("Error: Wrong configuration file for predicate %s" % predicate_name)
return False
try:
msg_type = predicate_info['msg_type']
except KeyError:
rospy.logerr("Error: msg_type was not specified for predicate %s" % predicate_name)
return False
self.import_msg(msg_type)
try:
rospy.Subscriber(predicate_info['topic'], eval(msg_type[msg_type.rfind('/') + 1:]), self.subs_callback,
(predicate_name, predicate_info))
except KeyError:
rospy.logerr("Error: topic was not specified for predicate %s" % predicate_name)
return False
# self.sensed_topics[predicate_name] = (None, False)
try: # Update KB to inform about the sensed predicates
sensed_srv_req = SetNamedBoolRequest()
sensed_srv_req.name = predicate_name
sensed_srv_req.value = True
self.set_sensed_predicate_srv.call(sensed_srv_req)
except Exception as e:
rospy.logerr(
'KCL: (RosplanSensing) Could not update sensing information in Knowledge Base for proposition %s',
predicate_name)
rospy.loginfo('KCL: (RosplanSensing) Predicate %s: Subscribed to topic %s of type %s', predicate_name,
predicate_info['topic'], msg_type)
return True
def create_service_client(self, predicate_name, predicate_info):
params_loaded = self.load_params(predicate_name, predicate_info) # If parameters found, add 1 to the indexes
if not params_loaded[0]:
return False
if len(predicate_info) < 2 + int(params_loaded[1]):
rospy.logerr("Error: Wrong configuration file for predicate %s" % predicate_name)
return False
try:
srv_type = predicate_info['srv_type']
except KeyError:
rospy.logerr("Error: service was not specified for predicate %s" % predicate_name)
return False
srv_typename = self.import_srv(srv_type)
self.service_type_names.append(srv_typename)
self.clients_sub_idx.append(predicate_info['sub_idx'])
try:
self.service_clients.append(rospy.ServiceProxy(predicate_info['service'], eval(srv_typename)))
self.service_names.append(predicate_info['service'])
except KeyError:
rospy.logerr("Error: service was not specified for predicate %s" % predicate_name)
return False
self.service_predicate_names.append(predicate_name)
self.last_called_time.append(rospy.Time(0))
try:
self.time_between_calls.append(predicate_info['time_between_calls'])
except:
rospy.logerr("Error: time_between_calls was not specified for predicate %s" % predicate_name)
return False
# Gets the request creation
if 'request' in predicate_info:
self.request_src.append(predicate_info['request'])
else:
self.request_src.append(None)
# Gets the result processing
if 'operation' in predicate_info:
self.response_process_src.append(predicate_info['operation'])
else:
self.response_process_src.append(None)
try: # Update KB to inform about the sensed predicates
sensed_srv_req = SetNamedBoolRequest()
sensed_srv_req.name = predicate_name
sensed_srv_req.value = True
self.set_sensed_predicate_srv.call(sensed_srv_req)
except Exception as e:
rospy.logerr(
'KCL: (RosplanSensing) Could not update sensing information in Knowledge Base for proposition %s',
predicate_name)
rospy.loginfo('KCL: (RosplanSensing) Predicate %s: Client for service %s of type %s is ready', predicate_name,
predicate_info['service'], srv_type)
return True
def get_function_params(self, func_name):
functions = self.get_functions_srv.call()
for i in functions.items:
if i.name == func_name:
return i
return None
def subs_callback(self, msg, (pred_name, pred_info)):
if 'operation' in pred_info: # pred_info is of type self.cfg_topics[pred_name]
python_string = pred_info['operation']
else: # Call the method from the scripts.py file
if not pred_name in dir(self.scripts):
rospy.logerr('KCL: (RosplanSensing) Predicate "%s" does not have either a function or processing information' % pred_name)
return None
python_string = "self.scripts." + pred_name + "(msg, self.params[pred_name][pred_info['sub_idx']])"
result = eval(python_string, globals(), locals())
changed = False
if type(result) is list:
for params, val in result:
self.mutex.acquire(True) # ROS subscribers are multithreaded in Python
try:
if type(val) is bool:
changed = self.sensed_topics[pred_name + ':' + params][0] ^ val
else:
changed = self.sensed_topics[pred_name + ':' + params][0] != val
except: # If hasn't been added yet just ignore it
changed = True
self.sensed_topics[pred_name + ':' + params] = (val, changed)
self.mutex.release()
else:
params = reduce(lambda r, x: r + ':' + x, self.params[pred_name][pred_info['sub_idx']])
if type(params) == list:
rospy.logerr('KCL: (RosplanSensing) Predicate "%s" needs to have all the parameters defined and fully instantiated' % pred_name)
rospy.signal_shutdown('Wrong cfg params')
return None
self.mutex.acquire(True) # ROS subscribers are multithreaded in Python
try:
if type(result) is bool:
changed = self.sensed_topics[pred_name + ':' + params][0] ^ result
else:
changed = self.sensed_topics[pred_name + ':' + params][0] != result
except: # If hasn't been added yet just ignore it
changed = True
self.sensed_topics[pred_name + ':' + params] = (result, changed)
self.mutex.release()
# Import a ros msg type of type pkg_name/MessageName
def import_msg(self, ros_msg_string):
# msg_string will be something like std_msgs/String -> convert it to from std_msgs.msg import String
i = ros_msg_string.find('/')
pkg_name = ros_msg_string[:i]
msg_name = ros_msg_string[i+1:]
exec('from ' + pkg_name + ".msg import " + msg_name, globals())
exec('self.scripts.' + msg_name + " = " + msg_name, globals(), locals())
# Import a ros srv type of type pkg_name/MessageName
def import_srv(self, ros_srv_string):
# srv str will be something like std_msgs/String -> convert it to from std_msgs.srv import String StringRequest
i = ros_srv_string.find('/')
pkg_name = ros_srv_string[:i]
srv_name = ros_srv_string[i + 1:]
exec ('from ' + pkg_name + ".srv import " + srv_name + ", " + srv_name + "Request", globals())
exec ('self.scripts.' + srv_name + " = " + srv_name, globals(), locals())
exec ('self.scripts.' + srv_name + "Request = " + srv_name + "Request", globals(), locals())
return srv_name
# To be run in its own thread
def call_services(self):
rospy.loginfo("Waiting for services to become available...")
for i in xrange(len(self.service_names)):
rospy.loginfo(' Waiting for %s', self.service_names[i])
rospy.wait_for_service(self.service_names[i], 20)
rospy.loginfo('All services are ready.')
r = rospy.Rate(20)
while not rospy.is_shutdown():
for i in xrange(len(self.service_clients)):
now = rospy.Time.now()
if (now-self.last_called_time[i]) < rospy.Duration(self.time_between_calls[i]):
continue
pred_name = self.service_predicate_names[i]
# Get request
if self.request_src[i]:
python_string = self.request_src[i]
else: # Call the method from the scripts.py file
if not ('req_' + pred_name) in dir(self.scripts):
rospy.logerr(
'KCL: (RosplanSensing) Predicate "%s" does not have either a Request creation method' % pred_name)
continue
python_string = "self.scripts." + 'req_' + pred_name + "()"
req = eval(python_string, globals(), locals())
try:
res = self.service_clients[i].call(req)
self.last_called_time[i] = now
except Exception as e:
rospy.logerr("KCL (SensingInterface) Failed to call service for predicate %s base: %s" % (pred_name, e.message))
continue
# Process response
if self.response_process_src[i]:
python_string = self.response_process_src[i]
else: # Call the method from the scripts.py file
if not pred_name in dir(self.scripts):
rospy.logerr('KCL: (RosplanSensing) Predicate "%s" does not have either a function or processing information' %
pred_name)
continue
python_string = "self.scripts." + pred_name + "(res, self.params[pred_name][self.clients_sub_idx[i]])"
result = eval(python_string, globals(), locals())
changed = False
if type(result) is list:
for params, val in result:
self.srv_mutex.acquire(True) # ROS subscribers are multithreaded in Python
try:
if type(val) is bool:
changed = self.sensed_services[pred_name + ':' + params][0] ^ val
else:
changed = self.sensed_services[pred_name + ':' + params][0] != val
except: # If hasn't been added yet just ignore it
changed = True
self.sensed_services[pred_name + ':' + params] = (val, changed)
self.srv_mutex.release()
else:
params = reduce(lambda r, x: r + ':' + x, self.params[pred_name][self.clients_sub_idx[i]]) if self.params[pred_name][self.clients_sub_idx[i]] else ''
if type(params) == list:
rospy.logerr(
'KCL: (RosplanSensing) Predicate "%s" needs to have all the parameters defined and fully instantiated' % pred_name)
rospy.signal_shutdown('Wrong cfg params')
return None
self.srv_mutex.acquire(True) # ROS subscribers are multithreaded in Python
try:
if type(result) is bool:
changed = self.sensed_services[pred_name + ':' + params][0] ^ result
else:
changed = self.sensed_services[pred_name + ':' + params][0] != result
except: # If hasn't been added yet just ignore it
changed = True
self.sensed_services[pred_name + ':' + params] = (result, changed)
self.srv_mutex.release()
r.sleep()
return None # Finish thread
def update_kb(self):
kus = KnowledgeUpdateServiceArrayRequest()
# Get info from KB functions and propositions (to know type of variable)
# Fill update
self.mutex.acquire(True)
sensed_predicates = self.sensed_topics.copy()
self.mutex.release()
self.srv_mutex.acquire(True)
sensed_predicates.update(self.sensed_services.copy())
self.srv_mutex.release()
for predicate, (val, changed) in sensed_predicates.iteritems():
if not changed:
continue
if predicate in self.sensed_topics:
self.mutex.acquire(True)
self.sensed_topics[predicate] = (self.sensed_topics[predicate][0], False) # Set to not changed
self.mutex.release()
else:
self.srv_mutex.acquire(True)
self.sensed_services[predicate] = (self.sensed_services[predicate][0], False) # Set to not changed
self.srv_mutex.release()
predicate_info = predicate.split(':')
ki = KnowledgeItem()
ki.attribute_name = predicate_info.pop(0)
if type(val) is bool:
ki.knowledge_type = ki.FACT
ki.is_negative = not val
else:
ki.knowledge_type = ki.FUNCTION
ki.function_value = val
# TODO what to do if no parameters specified? iterate over all the instantiated parameters and add them?
for i, param in enumerate(predicate_info):
kv = KeyValue()
kv.key = 'p' + str(i)
kv.value = param
ki.values.append(kv)
kus.update_type += np.array(kus.ADD_KNOWLEDGE).tostring()
kus.knowledge.append(ki)
# Update the KB with the full array
if len(kus.update_type) > 0:
try:
self.update_kb_srv.call(kus)
except Exception as e:
rospy.logerr("KCL (SensingInterface) Failed to update knowledge base: %s" % e.message)
def get_kb_attribute(self, attribute_name):
request = GetAttributeServiceRequest(attribute_name)
ret = self.get_state_propositions_srv.call(request)
if len(ret.attributes) > 0:
return ret.attributes
return self.get_state_functions_srv.call(request).attributes
if __name__ == "__main__":
rospy.init_node('rosplan_sensing_interface', anonymous=False)
rps = RosplanSensing()
t = threading.Thread(target=RosplanSensing.call_services, args=(rps,))
# main loop
hz_rate = rospy.get_param('~main_rate', 10)
rate = rospy.Rate(hz_rate) # 10hz
t.start()
while not rospy.is_shutdown():
# Note: spin is not needed in python as the callback methods are run in a different thread
rps.update_kb()
rate.sleep()
t.join()
|
example3.py | # ch13/example3.py
import threading
def writer():
global text
while True:
with service:
resource.acquire()
print(f'Writing being done by {threading.current_thread().name}.')
text += f'Writing was done by {threading.current_thread().name}. '
resource.release()
def reader():
global rcount
while True:
with service:
rcounter.acquire()
rcount += 1
if rcount == 1:
resource.acquire()
rcounter.release()
print(f'Reading being done by {threading.current_thread().name}:')
#print(text)
with rcounter:
rcount -= 1
if rcount == 0:
resource.release()
text = 'This is some text. '
rcount = 0
rcounter = threading.Lock()
resource = threading.Lock()
service = threading.Lock()
threads = [threading.Thread(target=reader) for i in range(3)] + [threading.Thread(target=writer) for i in range(2)]
for thread in threads:
thread.start()
|
apparatus.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time
import re
import multiprocessing as mp
from os import path, makedirs, listdir, remove
from shutil import copyfile
from threading import Event
from psyclab.utilities.osc import OSCResponder, route
from psyclab.apparatus.osc_controller import OSCController
from psyclab.sl import Robot, robot_user_path
from psyclab.sl.data_files import read_sl_data_file, last_data_file, InvalidSLDataFile
class Apparatus(OSCResponder):
"""
Apparatus class used to connect an SL robot model to an experiment controller
"""
data_file = Event()
_controller_class = OSCController
def __init__(self, robot_name, configuration='User', host='0.0.0.0', port=7401, **kwargs):
OSCResponder.__init__(self, host=host, port=port, **kwargs)
# to handle multiple udp clients
self._client = {}
self.n_data_file = None
self.configuration = configuration
self.robot_name = robot_name
self.controller = None
self.robot = Robot(robot_name, user_path=robot_user_path(robot_name, configuration))
def start_robot(self, *args, **kwargs):
if self.robot is not None:
if self.robot.running:
return
return self.robot.start(**kwargs)
def stop(self, *args):
if self.controller:
self._client['controller'].send_message('/stop', True)
self.controller.terminate()
self.robot.stop()
OSCResponder.stop(self)
def set_task(self, task_name):
if not self.running:
return
self.send('/task', task_name, to='apparatus')
@route('/apparatus/connect')
def connect_apparatus(self, route, source, *messages):
""" Incoming connection request from apparatus """
pid, port = messages
host, _ = source
self._client['apparatus'] = self.connect(host, port)
self.debug(f'apparatus pid:{pid} connecting from {host}:{port}')
self.connected_apparatus(pid, host, port)
def connected_apparatus(self, *args):
""" Connected as client to apparatus callback function """
pid, host, port = args
self.send('/apparatus', port, to='apparatus')
@route('/sl/data_file')
def receive_data_file(self, route, source, n_data_file):
host, port = source
self.n_data_file = int(n_data_file)
self.info(f'data file d{n_data_file:05d} saved; apparatus {host}:{port}')
self.data_file.set()
self.data_file.clear()
@property
def user_path(self):
""" Active user path for the SL robot model """
if hasattr(self, '_user_path'):
return self._user_path
return self.robot._user_path
@property
def last_data(self):
""" Index of the current data file from SL data collection """
return last_data_file(self.user_path)
def reset_data_index(self):
""" Reset the data file index """
try:
remove(path.join(self.user_path, '.last_data'))
except FileNotFoundError:
pass
def load_data_file(self, n_data_file, retry=3, pause=0.25):
""" Read an SL data file into a metadata header and a dictionary of numpy arrays """
if n_data_file is None:
return
while retry:
# if the data file has not been written (or not fully written), handle exception and retry
try:
header, data = read_sl_data_file(f'd{n_data_file:05d}')
return header, data
except (ValueError, FileNotFoundError, InvalidSLDataFile):
# self.warning(f'failed to read d{n_data_file:05d}, retrying... ({retry})')
time.sleep(pause)
retry -= 1
pause *= 2
def remove_data_files(self, archive_path=None, confirm=False):
""" Remove all saved data files in the user path; optional archiving """
for data_file in listdir(self.user_path):
if not re.match('d\d{5}', data_file):
continue
if confirm:
remove(path.join(self.user_path, data_file))
else:
print('rm ' + path.join(self.user_path, data_file))
def archive_data_files(self, archive_path, make_paths=True):
""" Archive all data files in the user path """
if make_paths:
makedirs(archive_path)
for data_file in listdir(self.user_path):
if not re.match('d\d{5}', data_file):
continue
copyfile(data_file, path.join(archive_path, data_file))
def start_controller(self, server_port, client_port, apparatus_host, pid=None):
kwargs = {
'robot_name': self.robot_name,
'robot_pid': pid or self._pid,
'apparatus_port': server_port,
'apparatus_host': apparatus_host,
'configuration': self.configuration,
'start': True,
}
ctx = mp.get_context('spawn')
controller = ctx.Process(target=self._controller_class, kwargs=kwargs)
controller.start()
client = self.connect(apparatus_host, client_port)
self.debug(f'started {self._controller_class.__name__}, listening {server_port}, sending {client_port}')
return client, controller
@route('/controller/connect')
def connect_controller(self, route, source, pid, port):
host, source_port = source
self.debug(f'apparatus pid {pid} controller connecting; {port}:{host}:{source_port}')
if self.controller:
self.error('new controller not connected - controller already running!')
return
client, controller = self.start_controller(int(port), int(port) + 1, host, pid=pid)
self.controller = controller
self._client['controller'] = client
|
vulcan_ash.py | __all__ = ['SignInWithScreenshot', 'SignInSpeedup']
from typing import List
from requests.exceptions import *
from src.BusinessCentralLayer.coroutine_engine import lsu_
from src.BusinessCentralLayer.setting import logger
class SignInSpeedup(lsu_):
"""็จไบ่ถๆ็ญพๅฐ็่ฝป้ๅๅ็จๅ ้ๆงไปถ"""
def __init__(self, task_docker: List[dict], power=2):
"""
:param task_docker: ่ฃ
ๆๅญฆๅท็ๅ่กจ
"""
super(SignInSpeedup, self).__init__(task_docker=task_docker, power=power)
from src.BusinessLogicLayer.apis.manager_users import stu_twqd
self.core_ = stu_twqd
def offload_task(self):
for task in self.task_docker:
self.work_q.put_nowait(task)
def control_driver(self, user: dict):
"""
:param user: {"username":str } or {"username":str ,"password":str }
:return:
"""
try:
# ไธบ่ดฆๅทๅผ่พๅๅญ็บงๅฎไพ๏ผ้ฟๅ
ๅ ้ซๅนถๅๅผ่ตท็ๅ
ฑไบซ้็จ้ฎ้ข
response = self.core_(user=user, cover=False)
logger.success(f"<VulcanAsh> FinishTank (N/{self.work_q.qsize()}) || {response['info']}")
except IndexError or KeyError or ConnectionError:
# ๆฐๆฎๅฎน็พ
logger.error(f"<OshRunner> {user['username']} || cookieๆดๆฐๅคฑ่ดฅ ่ฏทๆฑ้ขๆฌก่ฟ้ซ IPๅฏ่ฝ่ขซๅฐ็ฆ")
self.ddt(task=user)
def ddt(self, task: dict):
"""
็จไบ้็พคๅฎน่ฝฝๆIPๅ
ฑไบซ
:return:
"""
# TODO ๆนๆก1 ้่ฟHTTPๆฅๅฃ่ฏทๆฑๅไผดๆๅกๅจ๏ผ็กฎไฟๅๆฐๅๆญฅ
import requests
from src.BusinessCentralLayer.setting import API_PORT, API_SLAVES, PUBLIC_API_STU_TWQD
from threading import Thread
atomic = API_SLAVES.copy().pop()
if atomic:
slave_api = f"http://{atomic}:{API_PORT}{PUBLIC_API_STU_TWQD}"
Thread(target=requests.post, kwargs={"url": slave_api, "data": task}).start()
logger.debug(f"<SignInSpeedup> {task['username']} -> slaves")
else:
# ๆฌๆบๆ่ตทIP่งฃๅฐ้้ปๆชๆฝ
logger.warning(f"<SignInSpeedup> {task['username']} || BeatSync 300s")
self.work_q.put(task)
self.beat_sync(sleep_time=300)
# TODO ๆนๆก2 ้่ฟ้
็ฝฎRedisๅฎ็ฐ็ซฏๅฐ็ซฏ่ฎข้
ๅๅธ๏ผๅนถ็ฑslave่ๆๅๆญฅๆถ่งฃไปปๅก
# TODO ๆนๆก3 ้่ฟRECไบคๆตๆฐๆฎ
class SignInWithScreenshot(SignInSpeedup):
"""็จไบไผด้ๆชๅพไธไผ ้ๆฑ็ๅ ้ๆงไปถ"""
def __init__(self, task_docker: List[dict], power=2):
super(SignInWithScreenshot, self).__init__(task_docker=task_docker, power=power)
from src.BusinessLogicLayer.apis.manager_screenshot import capture_and_upload_screenshot
from src.BusinessLogicLayer.apis.manager_users import check_display_state
self.plugin_upload_screenshot = capture_and_upload_screenshot
self.plugin_check_state = check_display_state
def control_driver(self, user: dict):
try:
# ๆฃๆต็ญพๅฐ็ถๆ
if self.plugin_check_state(user)['code'] != 902:
# ไธบ่ดฆๅทๅผ่พๅๅญ็บงๅฎไพ๏ผ้ฟๅ
ๅ ้ซๅนถๅๅผ่ตท็ๅ
ฑไบซ้็จ้ฎ้ข
self.core_(user=user, cover=False)
# ๆชๅพไธไผ
self.release_plugin_upload_screenshot(user=user)
except IndexError or KeyError or RequestException:
logger.error(f"<OshRunner> {user['username']} || cookieๆดๆฐๅคฑ่ดฅ ่ฏทๆฑ้ขๆฌก่ฟ้ซ IPๅฏ่ฝ่ขซๅฐ็ฆ")
# ๆฐๆฎๅฎน็พ
self.ddt(task=user)
def release_plugin_upload_screenshot(self, user: dict):
self.plugin_upload_screenshot(user=user, silence=True)
|
roomba.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Python 2.7/Python 3.5/3.6 (thanks to pschmitt for adding Python 3 compatibility)
Program to connect to Roomba 980 vacuum cleaner, dcode json, and forward to mqtt
server
Nick Waterton 24th April 2017: V 1.0: Initial Release
Nick Waterton 4th July 2017 V 1.1.1: Fixed MQTT protocol version, and map
paths, fixed paho-mqtt tls changes
Nick Waterton 5th July 2017 V 1.1.2: Minor fixes, CV version 3 .2 support
Nick Waterton 7th July 2017 V1.2.0: Added -o option "roomOutline" allows
enabling/disabling of room outline drawing, added auto creation of css/html files
Nick Waterton 11th July 2017 V1.2.1: Quick (untested) fix for room outlines
if you don't have OpenCV
'''
from __future__ import print_function
from __future__ import absolute_import
__version__ = "1.2.1"
from ast import literal_eval
from collections import OrderedDict, Mapping
from roomba.password import Password
import datetime
import json
import math
import logging
import os
import six
import socket
import ssl
import sys
import threading
import time
try:
import configparser
except:
from six.moves import configparser
# Import trickery
global HAVE_CV2
global HAVE_MQTT
global HAVE_PIL
HAVE_CV2 = False
HAVE_MQTT = False
HAVE_PIL = False
try:
import paho.mqtt.client as mqtt
HAVE_MQTT = True
except ImportError:
print("paho mqtt client not found")
try:
import cv2
import numpy as np
HAVE_CV2 = True
except ImportError:
print("CV or numpy module not found, falling back to PIL")
# NOTE: MUST use Pillow Pillow 4.1.1 to avoid some horrible memory leaks in the
# text handling!
try:
from PIL import Image, ImageDraw, ImageFont, ImageFilter, ImageOps
HAVE_PIL = True
except ImportError:
print("PIL module not found, maps are disabled")
# On Python 3 raw_input was renamed to input
try:
input = raw_input
except NameError:
pass
class RoombaConnectionError(Exception):
pass
class Roomba(object):
'''
This is a Class for Roomba 900 series WiFi connected Vacuum cleaners
Requires firmware version 2.0 and above (not V1.0). Tested with Roomba 980
username (blid) and password are required, and can be found using the
password() class above (or can be auto discovered)
Most of the underlying info was obtained from here:
https://github.com/koalazak/dorita980 many thanks!
The values received from the Roomba as stored in a dictionay called
master_state, and can be accessed at any time, the contents are live, and
will build with time after connection.
This is not needed if the forward to mqtt option is used, as the events will
be decoded and published on the designated mqtt client topic.
'''
VERSION = "1.0"
states = {"charge": "Charging",
"new": "New Mission",
"run": "Running",
"resume": "Running",
"hmMidMsn": "Recharging",
"recharge": "Recharging",
"stuck": "Stuck",
"hmUsrDock": "User Docking",
"dock": "Docking",
"dockend": "Docking - End Mission",
"cancelled": "Cancelled",
"stop": "Stopped",
"pause": "Paused",
"hmPostMsn": "End Mission",
"": None}
# From http://homesupport.irobot.com/app/answers/detail/a_id/9024/~/roomba-900-error-messages
_ErrorMessages = {
0: "None",
1: "Roomba is stuck with its left or right wheel hanging down.",
2: "The debris extractors can't turn.",
5: "The left or right wheel is stuck.",
6: "The cliff sensors are dirty, it is hanging over a drop, "\
"or it is stuck on a dark surface.",
8: "The fan is stuck or its filter is clogged.",
9: "The bumper is stuck, or the bumper sensor is dirty.",
10: "The left or right wheel is not moving.",
11: "Roomba has an internal error.",
14: "The bin has a bad connection to the robot.",
15: "Roomba has an internal error.",
16: "Roomba has started while moving or at an angle, or was bumped "\
"while running.",
17: "The cleaning job is incomplete.",
18: "Roomba cannot return to the Home Base or starting position."
}
def __init__(self, address=None, blid=None, password=None, topic="#",
continuous=True, delay=1, clean=False, cert_name="", roombaName="",
file="./config.ini"):
'''
address is the IP address of the Roomba, the continuous flag enables a
continuous mqtt connection, if this is set to False, the client connects
and disconnects every 'delay' seconds (1 by default, but can be
changed). This is to allow other programs access, as there can only be
one Roomba connection at a time.
As cloud connections are unaffected, I reccomend leaving this as True.
leave topic as is, unless debugging (# = all messages).
if a python standard logging object exists, it will be used for logging.
'''
self.debug = False
self.log = logging.getLogger(__name__)
if self.log.getEffectiveLevel() == logging.DEBUG:
self.debug = True
self.address = address
if not cert_name:
self.cert_name = "/etc/ssl/certs/ca-certificates.crt"
else:
self.cert_name = cert_name
self.continuous = continuous
if self.continuous:
self.log.debug("CONTINUOUS connection")
else:
self.log.debug("PERIODIC connection")
# set the following to True to enable pretty printing of json data
self.pretty_print = False
self.stop_connection = False
self.periodic_connection_running = False
self.clean = clean
self.roomba_port = 8883
self.blid = blid
self.password = password
self.roombaName = roombaName
self.topic = topic
self.mqttc = None
self.exclude = ""
self.delay = delay
self.roomba_connected = False
self.indent = 0
self.master_indent = 0
self.raw = False
self.drawmap = False
self.previous_co_ords = self.co_ords = self.zero_coords()
self.fnt = None
self.home_pos = None
self.angle = 0
self.cleanMissionStatus_phase = ""
self.previous_cleanMissionStatus_phase = ""
self.current_state = None
self.last_completed_time = None
self.bin_full = False
self.base = None #base map
self.dock_icon = None #dock icon
self.roomba_icon = None #roomba icon
self.roomba_cancelled_icon = None #roomba cancelled icon
self.roomba_battery_icon = None #roomba battery low icon
self.roomba_error_icon = None #roomba error icon
self.bin_full_icon = None #bin full icon
self.room_outline_contour = None
self.room_outline = None
self.transparent = (0, 0, 0, 0) #transparent
self.previous_display_text = self.display_text = None
self.master_state = {}
self.time = time.time()
self.update_seconds = 300 #update with all values every 5 minutes
self.show_final_map = True
self.client = None
if self.address is None or blid is None or password is None:
self.read_config_file(file)
def read_config_file(self, file="./config.ini"):
# read config file
Config = configparser.ConfigParser()
try:
Config.read(file)
except Exception as e:
self.log.warning("Error reading config file %s", e)
self.log.debug("No Roomba specified, and no config file found - "
"attempting discovery")
if Password(self.address, file):
return self.read_config_file(file)
else:
return False
self.log.debug("Reading info from config file %s" % file)
addresses = Config.sections()
if self.address is None:
if len(addresses) > 1:
self.log.warning("The config file has entries for %d Roombas, "
"only configuring the first!", len(addresses))
self.address = addresses[0]
self.blid = Config.get(self.address, "blid"),
self.password = Config.get(self.address, "password")
# self.roombaName = literal_eval(
# Config.get(self.address, "data"))["robotname"]
return True
def setup_client(self):
if self.client is None:
if not HAVE_MQTT:
print("Please install paho-mqtt 'pip install paho-mqtt' "
"to use this library")
return False
self.client = mqtt.Client(
client_id=self.blid, clean_session=self.clean,
protocol=mqtt.MQTTv311)
# Assign event callbacks
self.client.on_message = self.on_message
self.client.on_connect = self.on_connect
self.client.on_publish = self.on_publish
self.client.on_subscribe = self.on_subscribe
self.client.on_disconnect = self.on_disconnect
# Uncomment to enable debug messages
# client.on_log = self.on_log
# set TLS, self.cert_name is required by paho-mqtt, even if the
# certificate is not used...
# but v1.3 changes all this, so have to do the following:
self.log.debug("Setting TLS certificate")
try:
self.client.tls_set(
self.cert_name, cert_reqs=ssl.CERT_NONE,
tls_version=ssl.PROTOCOL_TLSv1)
except ValueError: # try V1.3 version
self.log.warning("TLS Setting failed - trying 1.3 version")
self.client._ssl_context = None
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
context.verify_mode = ssl.CERT_NONE
context.load_default_certs()
self.client.tls_set_context(context)
# disables peer verification
self.client.tls_insecure_set(True)
self.client.username_pw_set(self.blid, self.password)
return True
return False
def connect(self):
if self.address is None or self.blid is None or self.password is None:
self.log.critical("Invalid address, blid, or password! All these "
"must be specified!")
raise Exception("Invalid address, blid, or password! All these "
"must be specified!")
if self.roomba_connected or self.periodic_connection_running:
return
if self.continuous:
if not self._connect():
if self.mqttc is not None:
self.mqttc.disconnect()
raise Exception("failed to connect!")
else:
self._thread = threading.Thread(target=self.periodic_connection)
self._thread.daemon = True
self._thread.start()
self.time = time.time() # save connection time
def _connect(self, count=0, new_connection=False):
max_retries = 3
try:
if self.client is None or new_connection:
self.log.info("Connecting to %s", self.roombaName)
self.setup_client()
self.client.connect(self.address, self.roomba_port, 60)
else:
self.log.info("Attempting to reconnect to %s", self.roombaName)
self.client.loop_stop()
self.client.reconnect()
self.client.loop_start()
return True
except Exception as e:
self.log.error("Error: %s " % e)
exc_type, exc_obj, exc_tb = sys.exc_info()
# self.log.error("Exception: %s" % exc_type)
# if e[0] == 111: #errno.ECONNREFUSED - does not work with
# python 3.0 so...
if exc_type == socket.error or exc_type == ConnectionRefusedError:
count += 1
if count <= max_retries:
self.log.debug("Attempting connection #%d" % count)
time.sleep(1)
self._connect(count, True)
if count >= max_retries:
self.log.error("Unable to connect to %s", self.address)
raise RoombaConnectionError(
"Unable to connect to Roomba at {}".format(self.address))
return False
def disconnect(self):
if self.continuous:
self.client.disconnect()
else:
self.stop_connection = True
def periodic_connection(self):
# only one connection thread at a time!
if self.periodic_connection_running:
return
self.periodic_connection_running = True
while not self.stop_connection:
if self._connect():
time.sleep(self.delay)
self.client.disconnect()
time.sleep(self.delay)
self.client.disconnect()
self.periodic_connection_running = False
def on_connect(self, client, userdata, flags, rc):
self.log.info("Connected to Roomba %s", self.roombaName)
if rc == 0:
self.roomba_connected = True
self.client.subscribe(self.topic)
else:
self.log.error("Roomba Connected with result code " + str(rc))
self.log.error("Please make sure your blid and password are "
"correct %s" % self.roombaName)
if self.mqttc is not None:
self.mqttc.disconnect()
raise Exception("Failure in on_connect")
def on_message(self, mosq, obj, msg):
# print(msg.topic + " " + str(msg.qos) + " " + str(msg.payload))
if self.exclude != "":
if self.exclude in msg.topic:
return
if self.indent == 0:
self.master_indent = max(self.master_indent, len(msg.topic))
log_string, json_data = self.decode_payload(msg.topic,msg.payload)
self.dict_merge(self.master_state, json_data)
if self.pretty_print:
self.log.debug("%-{:d}s : %s".format(self.master_indent),
msg.topic,log_string)
else:
self.log.debug("Received Roomba Data %s: %s, %s",
self.roombaName, str(msg.topic), str(msg.payload))
if self.raw:
self.publish(msg.topic, msg.payload)
else:
self.decode_topics(json_data)
# default every 5 minutes
if time.time() - self.time > self.update_seconds:
self.log.debug("Publishing master_state %s", self.roombaName)
self.decode_topics(self.master_state) # publish all values
self.time = time.time()
def on_publish(self, mosq, obj, mid):
pass
def on_subscribe(self, mosq, obj, mid, granted_qos):
self.log.debug("Subscribed: %s %s", str(mid), str(granted_qos))
def on_disconnect(self, mosq, obj, rc):
self.roomba_connected = False
if rc != 0:
self.log.warning("Unexpectedly disconnected from Roomba %s! "
"- reconnecting", self.roombaName)
else:
self.log.info("Disconnected from Roomba %s", self.roombaName)
def on_log(self, mosq, obj, level, string):
self.log.debug(string)
def set_mqtt_client(self, mqttc=None, brokerFeedback=""):
self.mqttc = mqttc
if self.mqttc is not None:
if self.roombaName != "":
self.brokerFeedback = brokerFeedback + "/" + self.roombaName
else:
self.brokerFeedback = brokerFeedback
def send_command(self, command):
self.log.debug("Send command: %s", command)
Command = OrderedDict()
Command["command"] = command
Command["time"] = self.totimestamp(datetime.datetime.now())
Command["initiator"] = "localApp"
myCommand = json.dumps(Command)
self.log.debug("Publishing Roomba Command : %s", myCommand)
self.client.publish("cmd", myCommand)
def set_preference(self, preference, setting):
self.log.debug("Set preference: %s, %s", preference, setting)
val = False
if setting.lower() == "true":
val = True
tmp = {preference: val}
Command = {"state": tmp}
myCommand = json.dumps(Command)
self.log.debug("Publishing Roomba Setting : %s" % myCommand)
self.client.publish("delta", myCommand)
def publish(self, topic, message):
if self.mqttc is not None and message is not None:
self.log.debug("Publishing item: %s: %s"
% (self.brokerFeedback + "/" + topic, message))
self.mqttc.publish(self.brokerFeedback + "/" + topic, message)
def set_options(self, raw=False, indent=0, pretty_print=False):
self.raw = raw
self.indent = indent
self.pretty_print = pretty_print
if self.raw:
self.log.debug("Posting RAW data")
else:
self.log.debug("Posting DECODED data")
def enable_map(self, enable=False, mapSize="(800,1500,0,0,0,0)",
mapPath=".", iconPath = "./", roomOutline=True,
home_icon_file="home.png",
roomba_icon_file="roomba.png",
roomba_error_file="roombaerror.png",
roomba_cancelled_file="roombacancelled.png",
roomba_battery_file="roomba-charge.png",
bin_full_file="binfull.png",
roomba_size=(50,50), draw_edges = 30, auto_rotate=True):
'''
Enable live map drawing. mapSize is x,y size, x,y offset of docking
station ((0,0) is the center of the image) final value is map rotation
(in case map is not straight up/down). These values depend on the
size/shape of the area Roomba covers. Offset depends on where you place
the docking station. This will need some experimentation to get right.
You can supply 32x32 icons for dock and roomba etc. If the files don't
exist, crude representations are made. If you specify home_icon_file as
None, then no dock is drawn. Draw edges attempts to draw straight lines
around the final (not live) map, and Auto_rotate (on/off) attempts to
line the map up vertically. These only work if you have openCV
installed. otherwise a PIL version is used, which is not as good (but
less CPU intensive). roomOutline enables the previous largest saved
outline to be overlayed on the map (so you can see where cleaning was
missed). This is on by default, but the alignment doesn't work so well,
so you can turn it off.
Returns map enabled True/False
'''
if not HAVE_PIL: #can't draw a map without PIL!
return False
if Image.PILLOW_VERSION < "4.1.1":
print("WARNING: PIL version is %s, this is not the latest! you "
"can get bad memory leaks with old versions of PIL"
% Image.PILLOW_VERSION)
print("run: 'pip install --upgrade pillow' to fix this")
self.drawmap = enable
if self.drawmap:
self.log.info("MAP: Maps Enabled")
self.mapSize = literal_eval(mapSize)
if len(mapSize) < 6:
self.log.error("mapSize is required, and is of the form "
"(800,1500,0,0,0,0) - (x,y size, x,y dock loc,"
"theta1, theta2), map,roomba roatation")
self.drawmap = False
return False
self.angle = self.mapSize[4]
self.roomba_angle = self.mapSize[5]
self.mapPath = mapPath
if home_icon_file is None:
self.home_icon_file = None
else:
self.home_icon_file = os.path.join(iconPath, home_icon_file)
self.roomba_icon_file = os.path.join(iconPath, roomba_icon_file)
self.roomba_error_file = os.path.join(iconPath, roomba_error_file)
self.roomba_cancelled_file = os.path.join(iconPath, roomba_cancelled_file)
self.roomba_battery_file = os.path.join(iconPath, roomba_battery_file)
self.bin_full_file = os.path.join(iconPath, bin_full_file)
self.draw_edges = draw_edges // 10000
self.auto_rotate = auto_rotate
if not roomOutline:
self.log.info("MAP: Not drawing Room Outline")
self.roomOutline = roomOutline
self.initialise_map(roomba_size)
return True
return False
def totimestamp(self, dt):
td = dt - datetime.datetime(1970, 1, 1)
return int(td.total_seconds())
def dict_merge(self, dct, merge_dct):
""" Recursive dict merge. Inspired by :meth:``dict.update()``, instead
of updating only top-level keys, dict_merge recurses down into dicts
nested to an arbitrary depth, updating keys. The ``merge_dct`` is
merged into ``dct``.
:param dct: dict onto which the merge is executed
:param merge_dct: dct merged into dct
:return: None
"""
for k, v in six.iteritems(merge_dct):
if (k in dct and isinstance(dct[k], dict)
and isinstance(merge_dct[k], Mapping)):
self.dict_merge(dct[k], merge_dct[k])
else:
dct[k] = merge_dct[k]
def decode_payload(self, topic, payload):
'''
Format json for pretty printing, return string sutiable for logging,
and a dict of the json data
'''
indent = self.master_indent + 31 #number of spaces to indent json data
try:
# if it's json data, decode it (use OrderedDict to preserve keys
# order), else return as is...
json_data = json.loads(
payload.decode("utf-8").replace(":nan", ":NaN").\
replace(":inf", ":Infinity").replace(":-inf", ":-Infinity"),
object_pairs_hook=OrderedDict)
# if it's not a dictionary, probably just a number
if not isinstance(json_data, dict):
return json_data, dict(json_data)
json_data_string = "\n".join((indent * " ") + i for i in \
(json.dumps(json_data, indent = 2)).splitlines())
formatted_data = "Decoded JSON: \n%s" % (json_data_string)
except ValueError:
formatted_data = payload
if self.raw:
formatted_data = payload
return formatted_data, dict(json_data)
def decode_topics(self, state, prefix=None):
'''
decode json data dict, and publish as individual topics to
brokerFeedback/topic the keys are concatinated with _ to make one unique
topic name strings are expressely converted to strings to avoid unicode
representations
'''
for k, v in six.iteritems(state):
if isinstance(v, dict):
if prefix is None:
self.decode_topics(v, k)
else:
self.decode_topics(v, prefix+"_"+k)
else:
if isinstance(v, list):
newlist = []
for i in v:
if isinstance(i, dict):
for ki, vi in six.iteritems(i):
newlist.append((str(ki), vi))
else:
if isinstance(i, six.string_types):
i = str(i)
newlist.append(i)
v = newlist
if prefix is not None:
k = prefix+"_"+k
# all data starts with this, so it's redundant
k = k.replace("state_reported_","")
# save variables for drawing map
if k == "pose_theta":
self.co_ords["theta"] = v
if k == "pose_point_x": #x and y are reversed...
self.co_ords["y"] = v
if k == "pose_point_y":
self.co_ords["x"] = v
if k == "bin_full":
self.bin_full = v
if k == "cleanMissionStatus_error":
try:
self.error_message = self._ErrorMessages[v]
except KeyError as e:
self.log.warning("Error looking up Roomba error "
"message: %s", e)
self.error_message = "Unknown Error number: %d" % v
self.publish("error_message", self.error_message)
if k == "cleanMissionStatus_phase":
self.previous_cleanMissionStatus_phase = \
self.cleanMissionStatus_phase
self.cleanMissionStatus_phase = v
self.publish(k, str(v))
if prefix is None:
self.update_state_machine()
def update_state_machine(self, new_state = None):
'''
Roomba progresses through states (phases), current identified states
are:
"" : program started up, no state yet
"run" : running on a Cleaning Mission
"hmUsrDock" : returning to Dock
"hmMidMsn" : need to recharge
"hmPostMsn" : mission completed
"charge" : chargeing
"stuck" : Roomba is stuck
"stop" : Stopped
"pause" : paused
available states:
states = { "charge":"Charging",
"new":"New Mission",
"run":"Running",
"resume":"Running",
"hmMidMsn":"Recharging",
"recharge":"Recharging",
"stuck":"Stuck",
"hmUsrDock":"User Docking",
"dock":"Docking",
"dockend":"Docking - End Mission",
"cancelled":"Cancelled",
"stop":"Stopped",
"pause":"Paused",
"hmPostMsn":"End Mission",
"":None}
Normal Sequence is "" -> charge -> run -> hmPostMsn -> charge
Mid mission recharge is "" -> charge -> run -> hmMidMsn -> charge
-> run -> hmPostMsn -> charge
Stuck is "" -> charge -> run -> hmPostMsn -> stuck
-> run/charge/stop/hmUsrDock -> charge
Start program during run is "" -> run -> hmPostMsn -> charge
Need to identify a new mission to initialize map, and end of mission to
finalise map.
Assume charge -> run = start of mission (init map)
stuck - > charge = init map
Assume hmPostMsn -> charge = end of mission (finalize map)
Anything else = continue with existing map
'''
current_mission = self.current_state
#if self.current_state == None: #set initial state here for debugging
# self.current_state = self.states["recharge"]
# self.show_final_map = False
# deal with "bin full" timeout on mission
try:
if (self.master_state["state"]["reported"]["cleanMissionStatus"]["mssnM"] == "none" and
self.cleanMissionStatus_phase == "charge" and
(self.current_state == self.states["pause"] or
self.current_state == self.states["recharge"])):
self.current_state = self.states["cancelled"]
except KeyError:
pass
if (self.current_state == self.states["charge"] and
self.cleanMissionStatus_phase == "run"):
self.current_state = self.states["new"]
elif (self.current_state == self.states["run"] and
self.cleanMissionStatus_phase == "hmMidMsn"):
self.current_state = self.states["dock"]
elif (self.current_state == self.states["dock"] and
self.cleanMissionStatus_phase == "charge"):
self.current_state = self.states["recharge"]
elif (self.current_state == self.states["recharge"] and
self.cleanMissionStatus_phase == "charge" and self.bin_full):
self.current_state = self.states["pause"]
elif (self.current_state == self.states["run"] and
self.cleanMissionStatus_phase == "charge"):
self.current_state = self.states["recharge"]
elif (self.current_state == self.states["recharge"]
and self.cleanMissionStatus_phase == "run"):
self.current_state = self.states["pause"]
elif (self.current_state == self.states["pause"]
and self.cleanMissionStatus_phase == "charge"):
self.current_state = self.states["pause"]
# so that we will draw map and can update recharge time
current_mission = None
elif (self.current_state == self.states["charge"] and
self.cleanMissionStatus_phase == "charge"):
# so that we will draw map and can update charge status
current_mission = None
elif ((self.current_state == self.states["stop"] or
self.current_state == self.states["pause"]) and
self.cleanMissionStatus_phase == "hmUsrDock"):
self.current_state = self.states["cancelled"]
elif ((self.current_state == self.states["hmUsrDock"] or
self.current_state == self.states["cancelled"]) and
self.cleanMissionStatus_phase == "charge"):
self.current_state = self.states["dockend"]
elif (self.current_state == self.states["hmPostMsn"] and
self.cleanMissionStatus_phase == "charge"):
self.current_state = self.states["dockend"]
elif (self.current_state == self.states["dockend"] and
self.cleanMissionStatus_phase == "charge"):
self.current_state = self.states["charge"]
else:
self.current_state = self.states[self.cleanMissionStatus_phase]
if new_state is not None:
self.current_state = self.states[new_state]
self.log.debug("Current state: %s", self.current_state)
if self.current_state != current_mission:
self.log.debug("State updated to: %s", self.current_state)
self.publish("state", self.current_state)
self.draw_map(current_mission != self.current_state)
def make_transparent(self, image, colour=None):
'''
take image and make white areas transparent
return transparent image
'''
image = image.convert("RGBA")
datas = image.getdata()
newData = []
for item in datas:
# white (ish)
if item[0] >= 254 and item[1] >= 254 and item[2] >= 254:
newData.append(self.transparent)
else:
if colour:
newData.append(colour)
else:
newData.append(item)
image.putdata(newData)
return image
def make_icon(self, input="./roomba.png", output="./roomba_mod.png"):
#utility function to make roomba icon from generic roomba icon
if not HAVE_PIL: #drawing library loaded?
self.log.error("PIL module not loaded")
return None
try:
roomba = Image.open(input).convert('RGBA')
roomba = roomba.rotate(90, expand=False)
roomba = self.make_transparent(roomba)
draw_wedge = ImageDraw.Draw(roomba)
draw_wedge.pieslice(
[(5,0),(roomba.size[0]-5,roomba.size[1])],
175, 185, fill="red", outline="red")
roomba.save(output, "PNG")
return roomba
except Exception as e:
self.log.error("ERROR: %s", e)
return None
def load_icon(self, filename="", icon_name=None, fnt=None, size=(32,32),
base_icon=None):
'''
Load icon from file, or draw icon if file not found.
returns icon object
'''
if icon_name is None:
return None
try:
icon = Image.open(filename).convert('RGBA').resize(
size,Image.ANTIALIAS)
icon = self.make_transparent(icon)
except IOError as e:
self.log.warning("Error loading %s: %s, using default icon "
"instead", icon_name, e)
if base_icon is None:
icon = Image.new('RGBA', size, self.transparent)
else:
icon = base_icon
draw_icon = ImageDraw.Draw(icon)
if icon_name == "roomba":
if base_icon is None:
draw_icon.ellipse([(5,5),(icon.size[0]-5,icon.size[1]-5)],
fill="green", outline="black")
draw_icon.pieslice([(5,5),(icon.size[0]-5,icon.size[1]-5)],
355, 5, fill="red", outline="red")
elif icon_name == "stuck":
if base_icon is None:
draw_icon.ellipse([(5,5),(icon.size[0]-5,icon.size[1]-5)],
fill="green", outline="black")
draw_icon.pieslice([(5,5),(icon.size[0]-5,icon.size[1]-5)],
175, 185, fill="red", outline="red")
draw_icon.polygon([(
icon.size[0]//2,icon.size[1]), (0, 0), (0,icon.size[1])],
fill = 'red')
if fnt is not None:
draw_icon.text((4,-4), "!", font=fnt,
fill=(255,255,255,255))
elif icon_name == "cancelled":
if base_icon is None:
draw_icon.ellipse([(5,5),(icon.size[0]-5,icon.size[1]-5)],
fill="green", outline="black")
draw_icon.pieslice([(5,5),(icon.size[0]-5,icon.size[1]-5)],
175, 185, fill="red", outline="red")
if fnt is not None:
draw_icon.text((4,-4), "X", font=fnt, fill=(255,0,0,255))
elif icon_name == "bin full":
draw_icon.rectangle([
icon.size[0]-10, icon.size[1]-10,
icon.size[0]+10, icon.size[1]+10],
fill = "grey")
if fnt is not None:
draw_icon.text((4,-4), "F", font=fnt,
fill=(255,255,255,255))
elif icon_name == "battery":
draw_icon.rectangle([icon.size[0]-10, icon.size[1]-10,
icon.size[0]+10,icon.size[1]+10], fill = "orange")
if fnt is not None:
draw_icon.text((4,-4), "B", font=fnt,
fill=(255,255,255,255))
elif icon_name == "home":
draw_icon.rectangle([0,0,32,32], fill="red", outline="black")
if fnt is not None:
draw_icon.text((4,-4), "D", font=fnt,
fill=(255,255,255,255))
else:
icon = None
#rotate icon 180 degrees
icon = icon.rotate(180-self.angle, expand=False)
return icon
def initialise_map(self, roomba_size):
'''
Initialize all map items (base maps, overlay, icons fonts etc)
'''
# get base image of Roomba path
if self.base is None:
try:
self.log.debug("MAP: openening existing line image")
self.base = Image.open(
self.mapPath + '/' + self.roombaName + 'lines.png')\
.convert('RGBA')
if self.base.size != (self.mapSize[0], self.mapSize[1]):
raise IOError("Image is wrong size")
except IOError as e:
self.base = Image.new(
'RGBA',
(self.mapSize[0], self.mapSize[1]), self.transparent)
self.log.warning("MAP: line image problem: %s: created new "
"image", e)
try:
self.log.debug("MAP: openening existing problems image")
self.roomba_problem = Image.open(
self.mapPath + '/'+self.roombaName + 'problems.png')\
.convert('RGBA')
if self.roomba_problem.size != self.base.size:
raise IOError("Image is wrong size")
except IOError as e:
self.roomba_problem = Image.new(
'RGBA', self.base.size, self.transparent)
self.log.warning("MAP: problems image problem: %s: created "
"new image", e)
try:
self.log.debug("MAP: openening existing map no text image")
self.previous_map_no_text = None
self.map_no_text = Image.open(
"{}/{}map_no_text.png".format(
self.mapPath, self.roombaName)).convert('RGBA')
if self.map_no_text.size != self.base.size:
raise IOError("Image is wrong size")
except IOError as e:
self.map_no_text = None
self.log.warning("MAP: map no text image problem: %s: set ",
"to None", e)
# save x and y center of image, for centering of final map image
self.cx = self.base.size[0]
self.cy = self.base.size[1]
# get a font
if self.fnt is None:
try:
self.fnt = ImageFont.truetype('FreeMono.ttf', 40)
except IOError as e:
self.log.warning("Error loading font: %s, loading default "
"font", e)
self.fnt = ImageFont.load_default()
#set dock home position
if self.home_pos is None:
self.home_pos = (
self.mapSize[0] // 2 + self.mapSize[2],
self.mapSize[1] // 2 + self.mapSize[3])
self.log.debug("MAP: home_pos: (%d,%d)",
self.home_pos[0], self.home_pos[1])
#get icons
if self.roomba_icon is None:
self.roomba_icon = self.load_icon(
filename=self.roomba_icon_file, icon_name="roomba",
fnt=self.fnt, size=roomba_size, base_icon=None)
if self.roomba_error_icon is None:
self.roomba_error_icon = self.load_icon(
filename=self.roomba_error_file, icon_name="stuck",
fnt=self.fnt, size=roomba_size, base_icon=self.roomba_icon)
if self.roomba_cancelled_icon is None:
self.roomba_cancelled_icon = self.load_icon(
filename=self.roomba_cancelled_file, icon_name="cancelled",
fnt=self.fnt, size=roomba_size, base_icon=self.roomba_icon)
if self.roomba_battery_icon is None:
self.roomba_battery_icon = self.load_icon(
filename=self.roomba_battery_file, icon_name="battery",
fnt=self.fnt, size=roomba_size, base_icon=self.roomba_icon)
if self.dock_icon is None and self.home_icon_file is not None:
self.dock_icon = self.load_icon(
filename=self.home_icon_file, icon_name="home", fnt=self.fnt)
self.dock_position = (
self.home_pos[0] - self.dock_icon.size[0] // 2,
self.home_pos[1] - self.dock_icon.size[1] // 2)
if self.bin_full_icon is None:
self.bin_full_icon = self.load_icon(
filename=self.bin_full_file, icon_name="bin full",
fnt=self.fnt, size=roomba_size, base_icon=self.roomba_icon)
self.log.debug("MAP: Initialisation complete")
def transparent_paste(self, base_image, icon, position):
'''
needed because PIL pasting of transparent imges gives weird results
'''
image = Image.new('RGBA', self.base.size, self.transparent)
image.paste(icon,position)
base_image = Image.alpha_composite(base_image, image)
return base_image
def zero_coords(self):
'''
returns dictionary with default zero coords
'''
return {"x": 0, "y": 0, "theta": 180}
def offset_coordinates(self, old_co_ords, new_co_ords):
'''
offset coordinates according to mapSize settings, with 0,0 as center
'''
x_y = (new_co_ords["x"] + self.mapSize[0] // 2 + self.mapSize[2],
new_co_ords["y"] + self.mapSize[1] // 2 + self.mapSize[3])
old_x_y = (old_co_ords["x"]+self.mapSize[0] // 2 + self.mapSize[2],
old_co_ords["y"]+self.mapSize[1]//2+self.mapSize[3])
theta = int(new_co_ords["theta"] - 90 + self.roomba_angle)
while theta > 359: theta = 360 - theta
while theta < 0: theta = 360 + theta
return old_x_y, x_y, theta
def get_roomba_pos(self, x_y):
'''
calculate roomba position as list
'''
return [x_y[0] - self.roomba_icon.size[0] // 2,
x_y[1] - self.roomba_icon.size[1] // 2,
x_y[0] + self.roomba_icon.size[0] // 2,
x_y[1] + self.roomba_icon.size[1] // 2]
def draw_vacuum_lines(self, image, old_x_y, x_y, theta, colour="lawngreen"):
'''
draw lines on image from old_x_y to x_y reepresenting vacuum coverage,
taking into account angle theta (roomba angle).
'''
lines = ImageDraw.Draw(image)
if x_y != old_x_y:
self.log.debug("MAP: drawing line: %s, %s", old_x_y, x_y)
lines.line([old_x_y, x_y], fill=colour,
width=self.roomba_icon.size[0] // 2)
#draw circle over roomba vacuum area to give smooth edges.
arcbox = [x_y[0]-self.roomba_icon.size[0] // 4,
x_y[1]-self.roomba_icon.size[0] // 4,
x_y[0]+self.roomba_icon.size[0] // 4,
x_y[1]+self.roomba_icon.size[0] // 4]
lines.ellipse(arcbox, fill=colour)
def draw_text(self, image, display_text, fnt, pos=(0,0),
colour=(0,0,255,255), rotate=False):
#draw text - (WARNING old versions of PIL have huge memory leak here!)
if display_text is None: return
self.log.debug("MAP: writing text: pos: %s, text: %s",
pos, display_text)
if rotate:
txt = Image.new('RGBA', (fnt.getsize(display_text)),
self.transparent)
text = ImageDraw.Draw(txt)
# draw text rotated 180 degrees...
text.text((0,0), display_text, font=fnt, fill=colour)
image.paste(txt.rotate(180-self.angle, expand=True), pos)
else:
text = ImageDraw.Draw(image)
text.text(pos, display_text, font=fnt, fill=colour)
def draw_map(self, force_redraw=False):
'''
Draw map of Roomba cleaning progress
'''
if ((self.co_ords != self.previous_co_ords or
self.cleanMissionStatus_phase !=
self.previous_cleanMissionStatus_phase)
or force_redraw) and self.drawmap:
self.render_map(self.co_ords, self.previous_co_ords)
self.previous_co_ords = self.co_ords.copy()
self.previous_cleanMissionStatus_phase = \
self.cleanMissionStatus_phase
def render_map(self, new_co_ords, old_co_ords):
'''
draw map
'''
draw_final = False
stuck = False
cancelled = False
bin_full = False
battery_low = False
# program just started, and we don't have phase yet.
if self.current_state is None:
return
if self.show_final_map == False:
self.log.debug("MAP: received: new_co_ords: %s old_co_ords: %s "
"phase: %s, state: %s", new_co_ords, old_co_ords,
self.cleanMissionStatus_phase, self.current_state)
if self.current_state == self.states["charge"]:
self.log.debug("MAP: Ignoring new co-ords in charge phase")
new_co_ords = old_co_ords = self.zero_coords()
self.display_text = "Charging: Battery: " + \
str(self.master_state["state"]["reported"]["batPct"]) + "%"
if self.bin_full:
self.display_text = "Bin Full," + \
self.display_text.replace("Charging", "Not Ready")
if (self.last_completed_time is None or time.time() -
self.last_completed_time > 3600):
self.save_text_and_map_on_whitebg(self.map_no_text)
draw_final = True
elif self.current_state == self.states["recharge"]:
self.log.debug("MAP: ignoring new co-ords in recharge phase")
new_co_ords = old_co_ords = self.zero_coords()
self.display_text = "Recharging:" + " Time: " + \
str(self.master_state["state"]["reported"]["cleanMissionStatus"]["rechrgM"]) + "m"
if self.bin_full:
self.display_text = "Bin Full," + self.display_text
self.save_text_and_map_on_whitebg(self.map_no_text)
elif self.current_state == self.states["pause"]:
self.log.debug("MAP: ignoring new co-ords in pause phase")
new_co_ords = old_co_ords
self.display_text = "Paused: " + \
str(self.master_state["state"]["reported"]["cleanMissionStatus"]["mssnM"]) + \
"m, Bat: "+ str(self.master_state["state"]["reported"]["batPct"]) + \
"%"
if self.bin_full:
self.display_text = "Bin Full," + self.display_text
# assume roomba is docked...
new_co_ords = old_co_ords = self.zero_coords()
self.save_text_and_map_on_whitebg(self.map_no_text)
elif self.current_state == self.states["hmPostMsn"]:
self.display_text = "Completed: " + \
time.strftime("%a %b %d %H:%M:%S")
self.log.debug("MAP: end of mission")
elif self.current_state == self.states["dockend"]:
self.log.debug("MAP: mission completed: ignoring new co-ords in "
"docking phase")
new_co_ords = old_co_ords = self.zero_coords()
self.draw_final_map(True)
draw_final = True
elif (self.current_state == self.states["run"] or
self.current_state == self.states["stop"] or
self.current_state == self.states["pause"]):
if self.current_state == self.states["run"]:
self.display_text = self.states["run"] + " Time: " + \
str(self.master_state["state"]["reported"]["cleanMissionStatus"]["mssnM"]) + \
"m, Bat: "+ str(self.master_state["state"]["reported"]["batPct"]) + \
"%"
else:
self.display_text = None
self.show_final_map = False
elif self.current_state == self.states["new"]:
self.angle = self.mapSize[4] #reset angle
self.base = Image.new('RGBA', self.base.size, self.transparent)
# overlay for roomba problem position
self.roomba_problem = Image.new('RGBA', self.base.size,
self.transparent)
self.show_final_map = False
self.display_text = None
self.log.debug("MAP: created new image at start of new run")
elif self.current_state == self.states["stuck"]:
self.display_text = "STUCK!: " + time.strftime("%a %b %d %H:%M:%S")
self.draw_final_map(True)
draw_final = True
stuck = True
elif self.current_state == self.states["cancelled"]:
self.display_text = "Cancelled: " + \
time.strftime("%a %b %d %H:%M:%S")
cancelled = True
elif self.current_state == self.states["dock"]:
self.display_text = "Docking"
if self.bin_full:
self.display_text = "Bin Full," + self.display_text
bin_full = True
else:
self.display_text = "Battery low: " + \
str(self.master_state["state"]["reported"]["batPct"]) + \
"%, " + self.display_text
battery_low = True
else:
self.log.warning("MAP: no special handling for state: %s",
self.current_state)
if self.base is None:
self.log.warning("MAP: no image, exiting...")
return
if self.display_text is None:
self.display_text = self.current_state
if self.show_final_map: # just display final map - not live
self.log.debug("MAP: not updating map - Roomba not running")
return
if self.debug:
# debug final map (careful, uses a lot of CPU power!)
self.draw_final_map()
#calculate co-ordinates, with 0,0 as center
old_x_y, x_y, theta = self.offset_coordinates(old_co_ords, new_co_ords)
roomba_pos = self.get_roomba_pos(x_y)
self.log.debug("MAP: old x,y: %s new x,y: %s theta: %s roomba pos: %s",
old_x_y, x_y, theta, roomba_pos)
#draw lines
self.draw_vacuum_lines(self.base, old_x_y, x_y, theta)
# make a blank image for the text and Roomba overlay, initialized to
# transparent text color
roomba_sprite = Image.new('RGBA', self.base.size, self.transparent)
#draw roomba
self.log.debug("MAP: drawing roomba: pos: %s, theta: %s",
roomba_pos, theta)
if stuck:
self.log.debug("MAP: Drawing stuck Roomba")
self.roomba_problem.paste(self.roomba_error_icon,roomba_pos)
if cancelled:
self.log.debug("MAP: Drawing cancelled Roomba")
self.roomba_problem.paste(self.roomba_cancelled_icon,roomba_pos)
if bin_full:
self.log.debug("MAP: Drawing full bin")
self.roomba_problem.paste(self.bin_full_icon,roomba_pos)
if battery_low:
self.log.debug("MAP: Drawing low battery Roomba")
self.roomba_problem.paste(self.roomba_battery_icon,roomba_pos)
roomba_sprite = self.transparent_paste(
roomba_sprite,
self.roomba_icon.rotate(theta, expand=False), roomba_pos)
# paste dock over roomba_sprite
if self.dock_icon is not None:
roomba_sprite = self.transparent_paste(
roomba_sprite, self.dock_icon, self.dock_position)
# save base lines
self.base.save(self.mapPath + '/' + self.roombaName + 'lines.png',
"PNG")
# save problem overlay
self.roomba_problem.save(self.mapPath + '/' + self.roombaName + \
'problems.png', "PNG")
if self.roomOutline or self.auto_rotate:
# draw room outline (saving results if this is a final map) update
# x,y and angle if auto_rotate
self.draw_room_outline(draw_final)
# merge room outline into base
if self.roomOutline:
#if we want to draw the room outline
out = Image.alpha_composite(self.base, self.room_outline)
else:
out = self.base
#merge roomba lines (trail) with base
out = Image.alpha_composite(out, roomba_sprite)
#merge problem location for roomba into out
out = Image.alpha_composite(out, self.roomba_problem)
if draw_final and self.auto_rotate:
#translate image to center it if auto_rotate is on
self.log.debug("MAP: calculation of center: (%d,%d), "
"translating final map to center it, x:%d, y:%d "
"deg: %.2f" % (
self.cx, self.cy, self.cx - out.size[0] // 2,
self.cy - out.size[1] // 2,
self.angle))
out = out.transform(
out.size, Image.AFFINE,
(1, 0, self.cx-out.size[0] // 2,
0, 1, self.cy-out.size[1] // 2))
# map is upside down, so rotate 180 degrees, and size to fit
out_rotated = out.rotate(180 + self.angle, expand=True).\
resize(self.base.size)
# save composite image
self.save_text_and_map_on_whitebg(out_rotated)
if draw_final:
self.show_final_map = True # prevent re-drawing of map until reset
def save_text_and_map_on_whitebg(self, map):
# if no map or nothing changed
if map is None or (map == self.previous_map_no_text and
self.previous_display_text == self.display_text):
return
self.map_no_text = map
self.previous_map_no_text = self.map_no_text
self.previous_display_text = self.display_text
self.map_no_text.save(self.mapPath + '/' + self.roombaName +
'map_notext.png', "PNG")
final = Image.new('RGBA', self.base.size, (255,255,255,255)) # white
# paste onto a white background, so it's easy to see
final = Image.alpha_composite(final, map)
# draw text
self.draw_text(final, self.display_text, self.fnt)
final.save(self.mapPath + '/'+self.roombaName + '_map.png', "PNG")
# try to avoid other programs reading file while writing it,
# rename should be atomic.
os.rename(self.mapPath + '/' + self.roombaName + '_map.png',
self.mapPath + '/' + self.roombaName + 'map.png')
def ScaleRotateTranslate(self, image, angle, center=None, new_center=None,
scale=None, expand=False):
'''
experimental - not used yet
'''
if center is None:
return image.rotate(angle, expand)
angle = -angle / 180.0 * math.pi
nx, ny = x, y = center
if new_center != center:
(nx, ny) = new_center
sx = sy = 1.0
if scale:
(sx, sy) = scale
cosine = math.cos(angle)
sine = math.sin(angle)
a = cosine / sx
b = sine / sx
c = x - nx * a - ny * b
d = -sine / sy
e = cosine / sy
f = y - nx * d - ny * e
return image.transform(image.size, Image.AFFINE,
(a,b,c,d,e,f), resample=Image.BICUBIC)
def match_outlines(self, orig_image, skewed_image):
orig_image = np.array(orig_image)
skewed_image = np.array(skewed_image)
try:
surf = cv2.xfeatures2d.SURF_create(400)
except Exception:
surf = cv2.SIFT(400)
kp1, des1 = surf.detectAndCompute(orig_image, None)
kp2, des2 = surf.detectAndCompute(skewed_image, None)
FLANN_INDEX_KDTREE = 0
index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)
search_params = dict(checks=50)
flann = cv2.FlannBasedMatcher(index_params, search_params)
matches = flann.knnMatch(des1, des2, k=2)
# store all the good matches as per Lowe's ratio test.
good = []
for m, n in matches:
if m.distance < 0.7 * n.distance:
good.append(m)
MIN_MATCH_COUNT = 10
if len(good) > MIN_MATCH_COUNT:
src_pts = np.float32([kp1[m.queryIdx].pt for m in good
]).reshape(-1, 1, 2)
dst_pts = np.float32([kp2[m.trainIdx].pt for m in good
]).reshape(-1, 1, 2)
M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
# see https://ch.mathworks.com/help/images/examples/find-image-rotation-and-scale-using-automated-feature-matching.html for details
ss = M[0, 1]
sc = M[0, 0]
scaleRecovered = math.sqrt(ss * ss + sc * sc)
thetaRecovered = math.atan2(ss, sc) * 180 / math.pi
self.log.debug("MAP: Calculated scale difference: %.2f, "
"Calculated rotation difference: %.2f" %
(scaleRecovered, thetaRecovered))
#deskew image
im_out = cv2.warpPerspective(skewed_image, np.linalg.inv(M),
(orig_image.shape[1], orig_image.shape[0]))
return im_out
else:
self.log.warning("MAP: Not enough matches found - %d/%d",
len(good), MIN_MATCH_COUNT)
return skewed_image
def draw_room_outline(self, overwrite=False, colour=(64,64,64,255),
width=1):
'''
draw room outline
'''
self.log.debug("MAP: checking room outline")
if HAVE_CV2:
if self.room_outline_contour is None or overwrite:
try:
self.room_outline_contour = np.load(
self.mapPath + '/' + self.roombaName + 'room.npy')
except IOError as e:
self.log.warning("Unable to load room outline: %s, "
"setting to 0", e)
self.room_outline_contour = np.array(
[(0,0),(0,0),(0,0),(0,0)], dtype=np.int)
try:
self.log.debug("MAP: openening existing room outline "
"image")
self.room_outline = Image.open(
self.mapPath + '/' + self.roombaName + 'room.png').\
convert('RGBA')
if self.room_outline.size != self.base.size:
raise IOError("Image is wrong size")
except IOError as e:
self.room_outline = Image.new(
'RGBA', self.base.size, self.transparent)
self.log.warning("MAP: room outline image problem: %s: "
"set to New" % e)
room_outline_area = cv2.contourArea(self.room_outline_contour)
# edgedata = cv2.add(
# np.array(self.base.convert('L'), dtype=np.uint8),
# np.array(self.room_outline.convert('L'), dtype=np.uint8))
edgedata = np.array(self.base.convert('L'))
# find external contour
_, contours, _ = self.findContours(
edgedata,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
if contours[0] is None: return
if len(contours[0]) < 5: return
max_area = cv2.contourArea(contours[0])
# experimental shape matching
# note cv2.cv.CV_CONTOURS_MATCH_I1 does not exist in CV 3.0,
# so just use 1
match = cv2.matchShapes(
self.room_outline_contour,contours[0],1,0.0)
self.log.debug("MAP: perimeter/outline match is: %.4f" % match)
# if match is less than 0.35 - shapes are similar (but if it's 0 -
# then they are the same shape..) try auto rotating map to fit.
if match < 0.35 and match > 0:
#self.match_outlines(self.room_outline, self.base)
pass
if max_area > room_outline_area:
self.log.debug("MAP: found new outline perimiter")
self.room_outline_contour = contours[0]
perimeter = cv2.arcLength(self.room_outline_contour,True)
outline = Image.new('RGBA',self.base.size,self.transparent)
edgeimage = np.array(outline) # make blank RGBA image array
# self.draw_edges is the max deviation from a line (set to 0.3%)
# you can fiddle with this
approx = cv2.approxPolyDP(
self.room_outline_contour,
self.draw_edges * perimeter,
True)
# outline with grey, width 1
cv2.drawContours(edgeimage,[approx] , -1, colour, width)
self.room_outline = Image.fromarray(edgeimage)
else:
if self.room_outline is None or overwrite:
try:
self.log.debug("MAP: openening existing room outline image")
self.room_outline = Image.open(
self.mapPath + '/' + self.roombaName + 'room.png').\
convert('RGBA')
if self.room_outline.size != self.base.size:
raise IOError("Image is wrong size")
except IOError as e:
self.room_outline = Image.new(
'RGBA', self.base.size, self.transparent)
self.log.warning("MAP: room outline image problem: %s: "
"set to New", e)
edges = ImageOps.invert(self.room_outline.convert('L'))
edges.paste(self.base)
edges = edges.convert('L').filter(ImageFilter.SMOOTH_MORE)
edges = ImageOps.invert(edges.filter(ImageFilter.FIND_EDGES))
self.room_outline = self.make_transparent(edges, (0, 0, 0, 255))
if overwrite or self.debug:
# save room outline
self.room_outline.save(
self.mapPath+'/'+self.roombaName+'room.png', "PNG")
if HAVE_CV2:
# save room outline contour as numpy array
np.save(self.mapPath + '/' + self.roombaName + 'room.npy',
self.room_outline_contour)
if self.auto_rotate:
# update outline centre
self.get_image_parameters(
image=self.room_outline, contour=self.room_outline_contour,
final=overwrite)
self.log.debug("MAP: calculation of center: (%d,%d), "
"translating room outline to center it, "
"x:%d, y:%d deg: %.2f",
self.cx, self.cy,
self.cx - self.base.size[0] // 2,
self.cy - self.base.size[1] // 2,
self.angle)
# center room outline, same as map.
self.room_outline = self.room_outline.transform(
self.base.size, Image.AFFINE,
(1, 0, self.cx - self.base.size[0] // 2,
0, 1, self.cy-self.base.size[1]//2))
self.log.debug("MAP: Wrote new room outline files")
def PIL_get_image_parameters(self, image=None, start=90, end = 0, step=-1,
recursion=0):
'''
updates angle of image, and centre using PIL.
NOTE: this assumes the floorplan is rectangular! if you live in a
lighthouse, the angle will not be valid!
input is PIL image
'''
if image is not None and HAVE_PIL:
imbw = image.convert('L')
max_area = self.base.size[0] * self.base.size[1]
x_y = (self.base.size[0] // 2, self.base.size[1] // 2)
angle = self.angle
div_by_10 = False
if step >=10 or step <=-10:
step /= 10
div_by_10 = True
for try_angle in range(start, end, step):
if div_by_10:
try_angle /= 10.0
#rotate image and resize to fit
im = imbw.rotate(try_angle, expand=True)
box = im.getbbox()
if box is not None:
area = (box[2]-box[0]) * (box[3]-box[1])
if area < max_area:
angle = try_angle
x_y = ((box[2] - box[0]) // 2 + box[0],
(box[3] - box[1]) // 2 + box[1])
max_area = area
if recursion >= 1:
return x_y, angle
x_y, angle = self.PIL_get_image_parameters(
image,
(angle + 1) * 10,
(angle - 1) * 10, -10,
recursion + 1)
# self.log.info("MAP: PIL: image center: "
# "x:%d, y:%d, angle %.2f" % (x_y[0], x_y[1], angle))
return x_y, angle
def get_image_parameters(self, image=None, contour=None, final=False):
'''
updates angle of image, and centre using cv2 or PIL.
NOTE: this assumes the floorplan is rectangular! if you live in a
lighthouse, the angle will not be valid!
input is cv2 contour or PIL image
routines find the minnimum area rectangle that fits the image outline
'''
if contour is not None and HAVE_CV2:
# find minnimum area rectangle that fits
# returns (x,y), (width, height), theta - where (x,y) is the center
x_y,l_w,angle = cv2.minAreaRect(contour)
elif image is not None and HAVE_PIL:
x_y, angle = self.PIL_get_image_parameters(image)
else:
return
if angle < self.angle - 45:
angle += 90
if angle > 45-self.angle:
angle -= 90
if final:
self.cx = x_y[0]
self.cy = x_y[1]
self.angle = angle
self.log.debug("MAP: image center: x:%d, y:%d, angle %.2f",
x_y[0], x_y[1], angle)
def angle_between(self, p1, p2):
'''
clockwise angle between two points in degrees
'''
if HAVE_CV2:
ang1 = np.arctan2(*p1[::-1])
ang2 = np.arctan2(*p2[::-1])
return np.rad2deg((ang1 - ang2) % (2 * np.pi))
else:
side1=math.sqrt(((p1[0] - p2[0]) ** 2))
side2=math.sqrt(((p1[1] - p2[1]) ** 2))
return math.degrees(math.atan(side2/side1))
def findContours(self,image,mode,method):
'''
Version independent find contours routine. Works with OpenCV 2 or 3.
Returns modified image (with contours applied), contours list, hierarchy
'''
ver = int(cv2.__version__.split(".")[0])
im = image.copy()
if ver == 2:
contours, hierarchy = cv2.findContours(im,mode,method)
return im, contours, hierarchy
else:
im_cont, contours, hierarchy = cv2.findContours(im,mode,method)
return im_cont, contours, hierarchy
def draw_final_map(self, overwrite=False):
'''
draw map with outlines at end of mission. Called when mission has
finished and Roomba has docked
'''
merge = Image.new('RGBA',self.base.size,self.transparent)
if HAVE_CV2:
# NOTE: this is CPU intensive!
edgedata = np.array(self.base.convert('L'), dtype=np.uint8)
# find all contours
_, contours, _ = self.findContours(
edgedata,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
# zero edge data for later use
edgedata.fill(0)
max_perimeter = 0
max_contour = None
for cnt in contours:
perimeter = cv2.arcLength(cnt,True)
if perimeter >= max_perimeter:
max_contour = cnt # get the contour with maximum length
max_perimeter = perimeter
if max_contour is None: return
if len(max_contour) < 5: return
try:
contours.remove(max_contour) # remove max contour from list
except ValueError:
self.log.warning("MAP: unable to remove contour")
mask = np.full(edgedata.shape, 255, dtype=np.uint8) # white
# create mask (of other contours) in black
cv2.drawContours(mask,contours, -1, 0, -1)
# self.draw_edges is the max deviation from a line
# you can fiddle with this in enable_map
approx = cv2.approxPolyDP(max_contour,
self.draw_edges * max_perimeter,True)
bgimage = np.array(merge) # make blank RGBA image array
# draw contour and fill with "lawngreen"
cv2.drawContours(bgimage,[approx] , -1, (124, 252, 0, 255), -1)
# mask image with internal contours
bgimage = cv2.bitwise_and(bgimage,bgimage,mask = mask)
# not dure if you really need this - uncomment if you want the
# area outlined.
# draw longest contour aproximated to lines (in black), width 1
cv2.drawContours(edgedata,[approx] , -1, (255), 1)
outline = Image.fromarray(edgedata) # outline
base = Image.fromarray(bgimage) # filled background image
else:
base = self.base.filter(ImageFilter.SMOOTH_MORE)
# draw edges at end of mission
outline = base.convert('L').filter(ImageFilter.FIND_EDGES)
# outline = ImageChops.subtract(
# base.convert('L').filter(ImageFilter.EDGE_ENHANCE),
# base.convert('L'))
edges = ImageOps.invert(outline)
edges = self.make_transparent(edges, (0, 0, 0, 255))
if self.debug:
edges.save(self.mapPath+'/'+self.roombaName+'edges.png', "PNG")
merge = Image.alpha_composite(merge,base)
merge = Image.alpha_composite(merge,edges)
if overwrite:
self.log.debug("MAP: Drawing final map")
self.last_completed_time = time.time()
self.base=merge
if self.debug:
merge_rotated = merge.rotate(180+self.angle, expand=True)
merge_rotated.save(
self.mapPath+'/'+self.roombaName+'final_map.png', "PNG")
|
test_ssl.py | # Test the support for SSL and sockets
import sys
import unittest
from test import test_support
import asyncore
import socket
import select
import time
import gc
import os
import errno
import pprint
import urllib, urlparse
import traceback
import weakref
import functools
import platform
from BaseHTTPServer import HTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
ssl = test_support.import_module("ssl")
HOST = test_support.HOST
CERTFILE = None
SVN_PYTHON_ORG_ROOT_CERT = None
def handle_error(prefix):
exc_format = ' '.join(traceback.format_exception(*sys.exc_info()))
if test_support.verbose:
sys.stdout.write(prefix + exc_format)
class BasicTests(unittest.TestCase):
def test_sslwrap_simple(self):
# A crude test for the legacy API
try:
ssl.sslwrap_simple(socket.socket(socket.AF_INET))
except IOError, e:
if e.errno == 32: # broken pipe when ssl_sock.do_handshake(), this test doesn't care about that
pass
else:
raise
try:
ssl.sslwrap_simple(socket.socket(socket.AF_INET)._sock)
except IOError, e:
if e.errno == 32: # broken pipe when ssl_sock.do_handshake(), this test doesn't care about that
pass
else:
raise
# Issue #9415: Ubuntu hijacks their OpenSSL and forcefully disables SSLv2
def skip_if_broken_ubuntu_ssl(func):
if hasattr(ssl, 'PROTOCOL_SSLv2'):
# We need to access the lower-level wrapper in order to create an
# implicit SSL context without trying to connect or listen.
try:
import _ssl
except ImportError:
# The returned function won't get executed, just ignore the error
pass
@functools.wraps(func)
def f(*args, **kwargs):
try:
s = socket.socket(socket.AF_INET)
_ssl.sslwrap(s._sock, 0, None, None,
ssl.CERT_NONE, ssl.PROTOCOL_SSLv2, None, None)
except ssl.SSLError as e:
if (ssl.OPENSSL_VERSION_INFO == (0, 9, 8, 15, 15) and
platform.linux_distribution() == ('debian', 'squeeze/sid', '')
and 'Invalid SSL protocol variant specified' in str(e)):
raise unittest.SkipTest("Patched Ubuntu OpenSSL breaks behaviour")
return func(*args, **kwargs)
return f
else:
return func
class BasicSocketTests(unittest.TestCase):
def test_constants(self):
#ssl.PROTOCOL_SSLv2
ssl.PROTOCOL_SSLv23
ssl.PROTOCOL_SSLv3
ssl.PROTOCOL_TLSv1
ssl.CERT_NONE
ssl.CERT_OPTIONAL
ssl.CERT_REQUIRED
def test_random(self):
v = ssl.RAND_status()
if test_support.verbose:
sys.stdout.write("\n RAND_status is %d (%s)\n"
% (v, (v and "sufficient randomness") or
"insufficient randomness"))
self.assertRaises(TypeError, ssl.RAND_egd, 1)
self.assertRaises(TypeError, ssl.RAND_egd, 'foo', 1)
ssl.RAND_add("this is a random string", 75.0)
@unittest.skipIf(test_support.is_jython, "Jython uses BouncyCastle")
def test_parse_cert(self):
# note that this uses an 'unofficial' function in _ssl.c,
# provided solely for this test, to exercise the certificate
# parsing code
p = ssl._ssl._test_decode_cert(CERTFILE, False)
if test_support.verbose:
sys.stdout.write("\n" + pprint.pformat(p) + "\n")
self.assertEqual(p['subject'],
((('countryName', 'XY'),),
(('localityName', 'Castle Anthrax'),),
(('organizationName', 'Python Software Foundation'),),
(('commonName', 'localhost'),))
)
self.assertEqual(p['subjectAltName'], (('DNS', 'localhost'),))
# Issue #13034: the subjectAltName in some certificates
# (notably projects.developer.nokia.com:443) wasn't parsed
p = ssl._ssl._test_decode_cert(NOKIACERT)
if test_support.verbose:
sys.stdout.write("\n" + pprint.pformat(p) + "\n")
self.assertEqual(p['subjectAltName'],
(('DNS', 'projects.developer.nokia.com'),
('DNS', 'projects.forum.nokia.com'))
)
def test_DER_to_PEM(self):
with open(SVN_PYTHON_ORG_ROOT_CERT, 'r') as f:
pem = f.read()
d1 = ssl.PEM_cert_to_DER_cert(pem)
p2 = ssl.DER_cert_to_PEM_cert(d1)
d2 = ssl.PEM_cert_to_DER_cert(p2)
self.assertEqual(d1, d2)
if not p2.startswith(ssl.PEM_HEADER + '\n'):
self.fail("DER-to-PEM didn't include correct header:\n%r\n" % p2)
if not p2.endswith('\n' + ssl.PEM_FOOTER + '\n'):
self.fail("DER-to-PEM didn't include correct footer:\n%r\n" % p2)
def test_openssl_version(self):
n = ssl.OPENSSL_VERSION_NUMBER
t = ssl.OPENSSL_VERSION_INFO
s = ssl.OPENSSL_VERSION
self.assertIsInstance(n, (int, long))
self.assertIsInstance(t, tuple)
self.assertIsInstance(s, str)
# Some sanity checks follow
# >= 0.9
self.assertGreaterEqual(n, 0x900000)
# < 2.0
self.assertLess(n, 0x20000000)
major, minor, fix, patch, status = t
self.assertGreaterEqual(major, 0)
self.assertLess(major, 2)
self.assertGreaterEqual(minor, 0)
self.assertLess(minor, 256)
self.assertGreaterEqual(fix, 0)
self.assertLess(fix, 256)
self.assertGreaterEqual(patch, 0)
self.assertLessEqual(patch, 26)
self.assertGreaterEqual(status, 0)
self.assertLessEqual(status, 15)
# Version string as returned by OpenSSL, the format might change
self.assertTrue(s.startswith("OpenSSL {:d}.{:d}.{:d}".format(major, minor, fix)),
(s, t))
def test_ciphers(self):
if not test_support.is_resource_enabled('network') or test_support.is_jython:
# see note on Jython support in test_main()
return
remote = ("svn.python.org", 443)
with test_support.transient_internet(remote[0]):
s = ssl.wrap_socket(socket.socket(socket.AF_INET),
cert_reqs=ssl.CERT_NONE, ciphers="ALL")
s.connect(remote)
s = ssl.wrap_socket(socket.socket(socket.AF_INET),
cert_reqs=ssl.CERT_NONE, ciphers="DEFAULT")
s.connect(remote)
# Error checking occurs when connecting, because the SSL context
# isn't created before.
s = ssl.wrap_socket(socket.socket(socket.AF_INET),
cert_reqs=ssl.CERT_NONE, ciphers="^$:,;?*'dorothyx")
with self.assertRaisesRegexp(ssl.SSLError, "No cipher can be selected"):
s.connect(remote)
def test_refcycle(self):
# Issue #7943: an SSL object doesn't create reference cycles with
# itself.
s = socket.socket(socket.AF_INET)
ss = ssl.wrap_socket(s)
wr = weakref.ref(ss)
del ss
test_support.gc_collect() # Usual Jython requirement
self.assertEqual(wr(), None)
def test_wrapped_unconnected(self):
# The _delegate_methods in socket.py are correctly delegated to by an
# unconnected SSLSocket, so they will raise a socket.error rather than
# something unexpected like TypeError.
s = socket.socket(socket.AF_INET)
ss = ssl.wrap_socket(s)
self.assertRaises(socket.error, ss.recv, 1)
self.assertRaises(socket.error, ss.recv_into, bytearray(b'x'))
self.assertRaises(socket.error, ss.recvfrom, 1)
self.assertRaises(socket.error, ss.recvfrom_into, bytearray(b'x'), 1)
self.assertRaises(socket.error, ss.send, b'x')
self.assertRaises(socket.error, ss.sendto, b'x', ('0.0.0.0', 0))
class NetworkedTests(unittest.TestCase):
def test_connect(self):
with test_support.transient_internet("svn.python.org"):
# s = ssl.wrap_socket(socket.socket(socket.AF_INET),
# cert_reqs=ssl.CERT_NONE)
# s.connect(("svn.python.org", 443))
# c = s.getpeercert()
# if c:
# self.fail("Peer cert %s shouldn't be here!")
# s.close()
# this should fail because we have no verification certs
s = ssl.wrap_socket(socket.socket(socket.AF_INET),
cert_reqs=ssl.CERT_REQUIRED)
try:
s.connect(("svn.python.org", 443))
except ssl.SSLError:
pass
finally:
s.close()
# this should succeed because we specify the root cert
s = ssl.wrap_socket(socket.socket(socket.AF_INET),
cert_reqs=ssl.CERT_REQUIRED,
ca_certs=SVN_PYTHON_ORG_ROOT_CERT)
try:
s.connect(("svn.python.org", 443))
finally:
s.close()
def test_connect_ex(self):
# Issue #11326: check connect_ex() implementation
with test_support.transient_internet("svn.python.org"):
s = ssl.wrap_socket(socket.socket(socket.AF_INET),
cert_reqs=ssl.CERT_REQUIRED,
ca_certs=SVN_PYTHON_ORG_ROOT_CERT)
try:
self.assertEqual(0, s.connect_ex(("svn.python.org", 443)))
self.assertTrue(s.getpeercert())
finally:
s.close()
def test_non_blocking_connect_ex(self):
# Issue #11326: non-blocking connect_ex() should allow handshake
# to proceed after the socket gets ready.
with test_support.transient_internet("svn.python.org"):
s = ssl.wrap_socket(socket.socket(socket.AF_INET),
cert_reqs=ssl.CERT_REQUIRED,
ca_certs=SVN_PYTHON_ORG_ROOT_CERT,
do_handshake_on_connect=False)
try:
s.setblocking(False)
rc = s.connect_ex(('svn.python.org', 443))
# EWOULDBLOCK under Windows, EINPROGRESS elsewhere
self.assertIn(rc, (0, errno.EINPROGRESS, errno.EWOULDBLOCK))
# Wait for connect to finish
select.select([], [s], [], 5.0)
# Non-blocking handshake
while True:
try:
s.do_handshake()
break
except ssl.SSLError as err:
if err.args[0] == ssl.SSL_ERROR_WANT_READ:
select.select([s], [], [], 5.0)
elif err.args[0] == ssl.SSL_ERROR_WANT_WRITE:
select.select([], [s], [], 5.0)
else:
raise
# SSL established
self.assertTrue(s.getpeercert())
finally:
s.close()
def test_timeout_connect_ex(self):
# Issue #12065: on a timeout, connect_ex() should return the original
# errno (mimicking the behaviour of non-SSL sockets).
with test_support.transient_internet("svn.python.org"):
s = ssl.wrap_socket(socket.socket(socket.AF_INET),
cert_reqs=ssl.CERT_REQUIRED,
ca_certs=SVN_PYTHON_ORG_ROOT_CERT,
do_handshake_on_connect=False)
try:
s.settimeout(0.0000001)
rc = s.connect_ex(('svn.python.org', 443))
if rc == 0:
self.skipTest("svn.python.org responded too quickly")
self.assertIn(rc, (errno.EAGAIN, errno.EWOULDBLOCK))
finally:
s.close()
def test_connect_ex_error(self):
with test_support.transient_internet("svn.python.org"):
s = ssl.wrap_socket(socket.socket(socket.AF_INET),
cert_reqs=ssl.CERT_REQUIRED,
ca_certs=SVN_PYTHON_ORG_ROOT_CERT)
try:
self.assertEqual(errno.ECONNREFUSED,
s.connect_ex(("svn.python.org", 444)))
finally:
s.close()
@unittest.skipIf(os.name == "nt", "Can't use a socket as a file under Windows")
def test_makefile_close(self):
# Issue #5238: creating a file-like object with makefile() shouldn't
# delay closing the underlying "real socket" (here tested with its
# file descriptor, hence skipping the test under Windows).
with test_support.transient_internet("svn.python.org"):
ss = ssl.wrap_socket(socket.socket(socket.AF_INET))
ss.connect(("svn.python.org", 443))
fd = ss.fileno()
f = ss.makefile()
f.close()
# The fd is still open
os.read(fd, 0)
# Closing the SSL socket should close the fd too
ss.close()
gc.collect()
with self.assertRaises(OSError) as e:
os.read(fd, 0)
self.assertEqual(e.exception.errno, errno.EBADF)
def test_non_blocking_handshake(self):
with test_support.transient_internet("svn.python.org"):
s = socket.socket(socket.AF_INET)
s.connect(("svn.python.org", 443))
s.setblocking(False)
s = ssl.wrap_socket(s,
cert_reqs=ssl.CERT_NONE,
do_handshake_on_connect=False)
count = 0
while True:
try:
count += 1
s.do_handshake()
break
except ssl.SSLError, err:
if err.args[0] == ssl.SSL_ERROR_WANT_READ:
select.select([s], [], [])
elif err.args[0] == ssl.SSL_ERROR_WANT_WRITE:
select.select([], [s], [])
else:
raise
s.close()
if test_support.verbose:
sys.stdout.write("\nNeeded %d calls to do_handshake() to establish session.\n" % count)
def test_get_server_certificate(self):
with test_support.transient_internet("svn.python.org"):
pem = ssl.get_server_certificate(("svn.python.org", 443))
if not pem:
self.fail("No server certificate on svn.python.org:443!")
try:
pem = ssl.get_server_certificate(("svn.python.org", 443), ca_certs=CERTFILE)
except ssl.SSLError:
#should fail
pass
else:
self.fail("Got server certificate %s for svn.python.org!" % pem)
pem = ssl.get_server_certificate(("svn.python.org", 443), ca_certs=SVN_PYTHON_ORG_ROOT_CERT)
if not pem:
self.fail("No server certificate on svn.python.org:443!")
if test_support.verbose:
sys.stdout.write("\nVerified certificate for svn.python.org:443 is\n%s\n" % pem)
def test_algorithms(self):
# Issue #8484: all algorithms should be available when verifying a
# certificate.
# SHA256 was added in OpenSSL 0.9.8
if ssl.OPENSSL_VERSION_INFO < (0, 9, 8, 0, 15):
self.skipTest("SHA256 not available on %r" % ssl.OPENSSL_VERSION)
self.skipTest("remote host needs SNI, only available on Python 3.2+")
# NOTE: https://sha2.hboeck.de is another possible test host
remote = ("sha256.tbs-internet.com", 443)
sha256_cert = os.path.join(os.path.dirname(__file__), "sha256.pem")
with test_support.transient_internet("sha256.tbs-internet.com"):
s = ssl.wrap_socket(socket.socket(socket.AF_INET),
cert_reqs=ssl.CERT_REQUIRED,
ca_certs=sha256_cert,)
try:
s.connect(remote)
if test_support.verbose:
sys.stdout.write("\nCipher with %r is %r\n" %
(remote, s.cipher()))
sys.stdout.write("Certificate is:\n%s\n" %
pprint.pformat(s.getpeercert()))
finally:
s.close()
try:
import threading
except ImportError:
_have_threads = False
else:
_have_threads = True
class ThreadedEchoServer(threading.Thread):
class ConnectionHandler(threading.Thread):
"""A mildly complicated class, because we want it to work both
with and without the SSL wrapper around the socket connection, so
that we can test the STARTTLS functionality."""
def __init__(self, server, connsock):
self.server = server
self.running = False
self.sock = connsock
self.sock.setblocking(1)
self.sslconn = None
threading.Thread.__init__(self)
self.daemon = True
def show_conn_details(self):
if self.server.certreqs == ssl.CERT_REQUIRED:
cert = self.sslconn.getpeercert()
if test_support.verbose and self.server.chatty:
sys.stdout.write(" client cert is " + pprint.pformat(cert) + "\n")
cert_binary = self.sslconn.getpeercert(True)
if test_support.verbose and self.server.chatty:
sys.stdout.write(" cert binary is " + str(len(cert_binary)) + " bytes\n")
cipher = self.sslconn.cipher()
if test_support.verbose and self.server.chatty:
sys.stdout.write(" server: connection cipher is now " + str(cipher) + "\n")
def wrap_conn(self):
try:
self.sslconn = ssl.wrap_socket(self.sock, server_side=True,
certfile=self.server.certificate,
ssl_version=self.server.protocol,
ca_certs=self.server.cacerts,
cert_reqs=self.server.certreqs,
ciphers=self.server.ciphers)
except ssl.SSLError as e:
# XXX Various errors can have happened here, for example
# a mismatching protocol version, an invalid certificate,
# or a low-level bug. This should be made more discriminating.
self.server.conn_errors.append(e)
if self.server.chatty:
handle_error("\n server: bad connection attempt from " +
str(self.sock.getpeername()) + ":\n")
self.close()
self.running = False
self.server.stop()
return False
else:
return True
def read(self):
if self.sslconn:
return self.sslconn.read()
else:
return self.sock.recv(1024)
def write(self, bytes):
if self.sslconn:
return self.sslconn.write(bytes)
else:
return self.sock.send(bytes)
def close(self):
if self.sslconn:
self.sslconn.close()
else:
self.sock._sock.close()
def run(self):
self.running = True
if not self.server.starttls_server:
if isinstance(self.sock, ssl.SSLSocket):
self.sslconn = self.sock
elif not self.wrap_conn():
return
self.show_conn_details()
while self.running:
try:
msg = self.read()
if not msg:
# eof, so quit this handler
self.running = False
self.close()
elif msg.strip() == 'over':
if test_support.verbose and self.server.connectionchatty:
sys.stdout.write(" server: client closed connection\n")
self.close()
return
elif self.server.starttls_server and msg.strip() == 'STARTTLS':
if test_support.verbose and self.server.connectionchatty:
sys.stdout.write(" server: read STARTTLS from client, sending OK...\n")
self.write("OK\n")
if not self.wrap_conn():
return
elif self.server.starttls_server and self.sslconn and msg.strip() == 'ENDTLS':
if test_support.verbose and self.server.connectionchatty:
sys.stdout.write(" server: read ENDTLS from client, sending OK...\n")
self.write("OK\n")
self.sslconn.unwrap()
self.sslconn = None
if test_support.verbose and self.server.connectionchatty:
sys.stdout.write(" server: connection is now unencrypted...\n")
else:
if (test_support.verbose and
self.server.connectionchatty):
ctype = (self.sslconn and "encrypted") or "unencrypted"
sys.stdout.write(" server: read %s (%s), sending back %s (%s)...\n"
% (repr(msg), ctype, repr(msg.lower()), ctype))
self.write(msg.lower())
except ssl.SSLError:
if self.server.chatty:
handle_error("Test server failure:\n")
self.close()
self.running = False
# normally, we'd just stop here, but for the test
# harness, we want to stop the server
self.server.stop()
def __init__(self, certificate, ssl_version=None,
certreqs=None, cacerts=None,
chatty=True, connectionchatty=False, starttls_server=False,
wrap_accepting_socket=False, ciphers=None):
if ssl_version is None:
ssl_version = ssl.PROTOCOL_TLSv1
if certreqs is None:
certreqs = ssl.CERT_NONE
self.certificate = certificate
self.protocol = ssl_version
self.certreqs = certreqs
self.cacerts = cacerts
self.ciphers = ciphers
self.chatty = chatty
self.connectionchatty = connectionchatty
self.starttls_server = starttls_server
self.sock = socket.socket()
self.flag = None
if wrap_accepting_socket:
self.sock = ssl.wrap_socket(self.sock, server_side=True,
certfile=self.certificate,
cert_reqs = self.certreqs,
ca_certs = self.cacerts,
ssl_version = self.protocol,
ciphers = self.ciphers)
if test_support.verbose and self.chatty:
sys.stdout.write(' server: wrapped server socket as %s\n' % str(self.sock))
self.port = test_support.bind_port(self.sock)
self.active = False
self.conn_errors = []
threading.Thread.__init__(self)
self.daemon = True
def __enter__(self):
self.start(threading.Event())
self.flag.wait()
return self
def __exit__(self, *args):
self.stop()
self.join()
def start(self, flag=None):
self.flag = flag
threading.Thread.start(self)
def run(self):
self.sock.settimeout(0.05)
self.sock.listen(5)
self.active = True
if self.flag:
# signal an event
self.flag.set()
while self.active:
try:
newconn, connaddr = self.sock.accept()
if test_support.verbose and self.chatty:
sys.stdout.write(' server: new connection from '
+ str(connaddr) + '\n')
handler = self.ConnectionHandler(self, newconn)
handler.start()
handler.join()
except socket.timeout:
pass
except KeyboardInterrupt:
self.stop()
self.sock.close()
def stop(self):
self.active = False
class AsyncoreEchoServer(threading.Thread):
class EchoServer(asyncore.dispatcher):
class ConnectionHandler(asyncore.dispatcher_with_send):
def __init__(self, conn, certfile):
asyncore.dispatcher_with_send.__init__(self, conn)
self.socket = ssl.wrap_socket(conn, server_side=True,
certfile=certfile,
do_handshake_on_connect=False)
self._ssl_accepting = True
def readable(self):
if isinstance(self.socket, ssl.SSLSocket):
while self.socket.pending() > 0:
self.handle_read_event()
return True
def _do_ssl_handshake(self):
try:
self.socket.do_handshake()
except ssl.SSLError, err:
if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
ssl.SSL_ERROR_WANT_WRITE):
return
elif err.args[0] == ssl.SSL_ERROR_EOF:
return self.handle_close()
raise
except socket.error, err:
if err.args[0] == errno.ECONNABORTED:
return self.handle_close()
else:
self._ssl_accepting = False
def handle_read(self):
if self._ssl_accepting:
self._do_ssl_handshake()
else:
data = self.recv(1024)
if data and data.strip() != 'over':
self.send(data.lower())
def handle_close(self):
self.close()
if test_support.verbose:
sys.stdout.write(" server: closed connection %s\n" % self.socket)
def handle_error(self):
raise
def __init__(self, certfile):
self.certfile = certfile
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.port = test_support.bind_port(self.socket)
self.listen(5)
def handle_accept(self):
sock_obj, addr = self.accept()
if test_support.verbose:
sys.stdout.write(" server: new connection from %s:%s\n" %addr)
self.ConnectionHandler(sock_obj, self.certfile)
def handle_error(self):
raise
def __init__(self, certfile):
self.flag = None
self.active = False
self.server = self.EchoServer(certfile)
self.port = self.server.port
threading.Thread.__init__(self)
self.daemon = True
def __str__(self):
return "<%s %s>" % (self.__class__.__name__, self.server)
def __enter__(self):
self.start(threading.Event())
self.flag.wait()
return self
def __exit__(self, *args):
if test_support.verbose:
sys.stdout.write(" cleanup: stopping server.\n")
self.stop()
if test_support.verbose:
sys.stdout.write(" cleanup: joining server thread.\n")
self.join()
if test_support.verbose:
sys.stdout.write(" cleanup: successfully joined.\n")
def start(self, flag=None):
self.flag = flag
threading.Thread.start(self)
def run(self):
self.active = True
if self.flag:
self.flag.set()
while self.active:
asyncore.loop(0.05)
def stop(self):
self.active = False
self.server.close()
class SocketServerHTTPSServer(threading.Thread):
class HTTPSServer(HTTPServer):
def __init__(self, server_address, RequestHandlerClass, certfile):
HTTPServer.__init__(self, server_address, RequestHandlerClass)
# we assume the certfile contains both private key and certificate
self.certfile = certfile
self.allow_reuse_address = True
def __str__(self):
return ('<%s %s:%s>' %
(self.__class__.__name__,
self.server_name,
self.server_port))
def get_request(self):
# override this to wrap socket with SSL
sock, addr = self.socket.accept()
sslconn = ssl.wrap_socket(sock, server_side=True,
certfile=self.certfile)
return sslconn, addr
class RootedHTTPRequestHandler(SimpleHTTPRequestHandler):
# need to override translate_path to get a known root,
# instead of using os.curdir, since the test could be
# run from anywhere
server_version = "TestHTTPS/1.0"
root = None
def translate_path(self, path):
"""Translate a /-separated PATH to the local filename syntax.
Components that mean special things to the local file system
(e.g. drive or directory names) are ignored. (XXX They should
probably be diagnosed.)
"""
# abandon query parameters
path = urlparse.urlparse(path)[2]
path = os.path.normpath(urllib.unquote(path))
words = path.split('/')
words = filter(None, words)
path = self.root
for word in words:
drive, word = os.path.splitdrive(word)
head, word = os.path.split(word)
if word in self.root: continue
path = os.path.join(path, word)
return path
def log_message(self, format, *args):
# we override this to suppress logging unless "verbose"
if test_support.verbose:
sys.stdout.write(" server (%s:%d %s):\n [%s] %s\n" %
(self.server.server_address,
self.server.server_port,
self.request.cipher(),
self.log_date_time_string(),
format%args))
def __init__(self, certfile):
self.flag = None
self.RootedHTTPRequestHandler.root = os.path.split(CERTFILE)[0]
self.server = self.HTTPSServer(
(HOST, 0), self.RootedHTTPRequestHandler, certfile)
self.port = self.server.server_port
threading.Thread.__init__(self)
self.daemon = True
def __str__(self):
return "<%s %s>" % (self.__class__.__name__, self.server)
def start(self, flag=None):
self.flag = flag
threading.Thread.start(self)
def run(self):
if self.flag:
self.flag.set()
self.server.serve_forever(0.05)
def stop(self):
self.server.shutdown()
def bad_cert_test(certfile):
"""
Launch a server with CERT_REQUIRED, and check that trying to
connect to it with the given client certificate fails.
"""
server = ThreadedEchoServer(CERTFILE,
certreqs=ssl.CERT_REQUIRED,
cacerts=CERTFILE, chatty=False)
with server:
try:
s = ssl.wrap_socket(socket.socket(),
certfile=certfile,
ssl_version=ssl.PROTOCOL_TLSv1)
s.connect((HOST, server.port))
except ssl.SSLError, x:
if test_support.verbose:
sys.stdout.write("\nSSLError is %s\n" % x[1])
except socket.error, x:
if test_support.verbose:
sys.stdout.write("\nsocket.error is %s\n" % x[1])
else:
raise AssertionError("Use of invalid cert should have failed!")
def server_params_test(certfile, protocol, certreqs, cacertsfile,
client_certfile, client_protocol=None, indata="FOO\n",
ciphers=None, chatty=True, connectionchatty=False,
wrap_accepting_socket=False):
"""
Launch a server, connect a client to it and try various reads
and writes.
"""
server = ThreadedEchoServer(certfile,
certreqs=certreqs,
ssl_version=protocol,
cacerts=cacertsfile,
ciphers=ciphers,
chatty=chatty,
connectionchatty=connectionchatty,
wrap_accepting_socket=wrap_accepting_socket)
with server:
# try to connect
if client_protocol is None:
client_protocol = protocol
s = ssl.wrap_socket(socket.socket(),
certfile=client_certfile,
ca_certs=cacertsfile,
ciphers=ciphers,
cert_reqs=certreqs,
ssl_version=client_protocol)
s.connect((HOST, server.port))
for arg in [indata, bytearray(indata), memoryview(indata)]:
if connectionchatty:
if test_support.verbose:
sys.stdout.write(
" client: sending %s...\n" % (repr(arg)))
s.write(arg)
outdata = s.read()
if connectionchatty:
if test_support.verbose:
sys.stdout.write(" client: read %s\n" % repr(outdata))
if outdata != indata.lower():
raise AssertionError(
"bad data <<%s>> (%d) received; expected <<%s>> (%d)\n"
% (outdata[:min(len(outdata),20)], len(outdata),
indata[:min(len(indata),20)].lower(), len(indata)))
s.write("over\n")
if connectionchatty:
if test_support.verbose:
sys.stdout.write(" client: closing connection.\n")
s.close()
def try_protocol_combo(server_protocol,
client_protocol,
expect_success,
certsreqs=None):
if certsreqs is None:
certsreqs = ssl.CERT_NONE
certtype = {
ssl.CERT_NONE: "CERT_NONE",
ssl.CERT_OPTIONAL: "CERT_OPTIONAL",
ssl.CERT_REQUIRED: "CERT_REQUIRED",
}[certsreqs]
if test_support.verbose:
formatstr = (expect_success and " %s->%s %s\n") or " {%s->%s} %s\n"
sys.stdout.write(formatstr %
(ssl.get_protocol_name(client_protocol),
ssl.get_protocol_name(server_protocol),
certtype))
try:
# NOTE: we must enable "ALL" ciphers, otherwise an SSLv23 client
# will send an SSLv3 hello (rather than SSLv2) starting from
# OpenSSL 1.0.0 (see issue #8322).
server_params_test(CERTFILE, server_protocol, certsreqs,
CERTFILE, CERTFILE, client_protocol,
ciphers="ALL", chatty=False)
# Protocol mismatch can result in either an SSLError, or a
# "Connection reset by peer" error.
except ssl.SSLError:
if expect_success:
raise
except socket.error as e:
if expect_success or e.errno != errno.ECONNRESET:
raise
else:
if not expect_success:
raise AssertionError(
"Client protocol %s succeeded with server protocol %s!"
% (ssl.get_protocol_name(client_protocol),
ssl.get_protocol_name(server_protocol)))
class ThreadedTests(unittest.TestCase):
def test_rude_shutdown(self):
"""A brutal shutdown of an SSL server should raise an IOError
in the client when attempting handshake.
"""
listener_ready = threading.Event()
listener_gone = threading.Event()
s = socket.socket()
port = test_support.bind_port(s, HOST)
# `listener` runs in a thread. It sits in an accept() until
# the main thread connects. Then it rudely closes the socket,
# and sets Event `listener_gone` to let the main thread know
# the socket is gone.
def listener():
s.listen(5)
listener_ready.set()
s.accept()
s.close()
listener_gone.set()
def connector():
listener_ready.wait()
c = socket.socket()
c.connect((HOST, port))
listener_gone.wait()
try:
ssl_sock = ssl.wrap_socket(c)
except IOError:
pass
else:
self.fail('connecting to closed SSL socket should have failed')
t = threading.Thread(target=listener)
t.start()
try:
connector()
finally:
t.join()
@skip_if_broken_ubuntu_ssl
def test_echo(self):
"""Basic test of an SSL client connecting to a server"""
if test_support.verbose:
sys.stdout.write("\n")
server_params_test(CERTFILE, ssl.PROTOCOL_TLSv1, ssl.CERT_NONE,
CERTFILE, CERTFILE, ssl.PROTOCOL_TLSv1,
chatty=True, connectionchatty=True)
def test_getpeercert(self):
if test_support.verbose:
sys.stdout.write("\n")
s2 = socket.socket()
server = ThreadedEchoServer(CERTFILE,
certreqs=ssl.CERT_NONE,
ssl_version=ssl.PROTOCOL_SSLv23,
cacerts=CERTFILE,
chatty=False)
with server:
s = ssl.wrap_socket(socket.socket(),
certfile=CERTFILE,
ca_certs=CERTFILE,
cert_reqs=ssl.CERT_REQUIRED,
ssl_version=ssl.PROTOCOL_SSLv23)
s.connect((HOST, server.port))
cert = s.getpeercert()
self.assertTrue(cert, "Can't get peer certificate.")
cipher = s.cipher()
if test_support.verbose:
sys.stdout.write(pprint.pformat(cert) + '\n')
sys.stdout.write("Connection cipher is " + str(cipher) + '.\n')
if 'subject' not in cert:
self.fail("No subject field in certificate: %s." %
pprint.pformat(cert))
if ((('organizationName', 'Python Software Foundation'),)
not in cert['subject']):
self.fail(
"Missing or invalid 'organizationName' field in certificate subject; "
"should be 'Python Software Foundation'.")
s.close()
def test_empty_cert(self):
"""Connecting with an empty cert file"""
bad_cert_test(os.path.join(os.path.dirname(__file__) or os.curdir,
"nullcert.pem"))
def test_malformed_cert(self):
"""Connecting with a badly formatted certificate (syntax error)"""
bad_cert_test(os.path.join(os.path.dirname(__file__) or os.curdir,
"badcert.pem"))
def test_nonexisting_cert(self):
"""Connecting with a non-existing cert file"""
bad_cert_test(os.path.join(os.path.dirname(__file__) or os.curdir,
"wrongcert.pem"))
def test_malformed_key(self):
"""Connecting with a badly formatted key (syntax error)"""
bad_cert_test(os.path.join(os.path.dirname(__file__) or os.curdir,
"badkey.pem"))
@skip_if_broken_ubuntu_ssl
def test_protocol_sslv2(self):
"""Connecting to an SSLv2 server with various client options"""
if test_support.verbose:
sys.stdout.write("\n")
if not hasattr(ssl, 'PROTOCOL_SSLv2'):
self.skipTest("PROTOCOL_SSLv2 needed")
try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True)
try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True, ssl.CERT_OPTIONAL)
try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True, ssl.CERT_REQUIRED)
try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, True)
try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv3, False)
try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_TLSv1, False)
@skip_if_broken_ubuntu_ssl
def test_protocol_sslv23(self):
"""Connecting to an SSLv23 server with various client options"""
if test_support.verbose:
sys.stdout.write("\n")
try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, True)
try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True)
try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, True)
try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, True, ssl.CERT_OPTIONAL)
try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True, ssl.CERT_OPTIONAL)
try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, True, ssl.CERT_OPTIONAL)
try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, True, ssl.CERT_REQUIRED)
try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True, ssl.CERT_REQUIRED)
try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, True, ssl.CERT_REQUIRED)
@skip_if_broken_ubuntu_ssl
def test_protocol_sslv3(self):
"""Connecting to an SSLv3 server with various client options"""
if test_support.verbose:
sys.stdout.write("\n")
try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, True)
try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, True, ssl.CERT_OPTIONAL)
try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, True, ssl.CERT_REQUIRED)
if hasattr(ssl, 'PROTOCOL_SSLv2'):
try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv2, False)
try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_TLSv1, False)
@skip_if_broken_ubuntu_ssl
def test_protocol_tlsv1(self):
"""Connecting to a TLSv1 server with various client options"""
if test_support.verbose:
sys.stdout.write("\n")
try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, True)
try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, True, ssl.CERT_OPTIONAL)
try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, True, ssl.CERT_REQUIRED)
if hasattr(ssl, 'PROTOCOL_SSLv2'):
try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv2, False)
try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv3, False)
def test_starttls(self):
"""Switching from clear text to encrypted and back again."""
msgs = ("msg 1", "MSG 2", "STARTTLS", "MSG 3", "msg 4", "ENDTLS", "msg 5", "msg 6")
server = ThreadedEchoServer(CERTFILE,
ssl_version=ssl.PROTOCOL_TLSv1,
starttls_server=True,
chatty=True,
connectionchatty=True)
wrapped = False
with server:
s = socket.socket()
s.setblocking(1)
s.connect((HOST, server.port))
if test_support.verbose:
sys.stdout.write("\n")
for indata in msgs:
if test_support.verbose:
sys.stdout.write(
" client: sending %s...\n" % repr(indata))
if wrapped:
conn.write(indata)
outdata = conn.read()
else:
s.send(indata)
outdata = s.recv(1024)
if (indata == "STARTTLS" and
outdata.strip().lower().startswith("ok")):
# STARTTLS ok, switch to secure mode
if test_support.verbose:
sys.stdout.write(
" client: read %s from server, starting TLS...\n"
% repr(outdata))
conn = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_TLSv1)
wrapped = True
elif (indata == "ENDTLS" and
outdata.strip().lower().startswith("ok")):
# ENDTLS ok, switch back to clear text
if test_support.verbose:
sys.stdout.write(
" client: read %s from server, ending TLS...\n"
% repr(outdata))
s = conn.unwrap()
wrapped = False
else:
if test_support.verbose:
sys.stdout.write(
" client: read %s from server\n" % repr(outdata))
if test_support.verbose:
sys.stdout.write(" client: closing connection.\n")
if wrapped:
conn.write("over\n")
else:
s.send("over\n")
s.close()
def test_socketserver(self):
"""Using a SocketServer to create and manage SSL connections."""
server = SocketServerHTTPSServer(CERTFILE)
flag = threading.Event()
server.start(flag)
# wait for it to start
flag.wait()
# try to connect
try:
if test_support.verbose:
sys.stdout.write('\n')
with open(CERTFILE, 'rb') as f:
d1 = f.read()
d2 = ''
# now fetch the same data from the HTTPS server
url = 'https://127.0.0.1:%d/%s' % (
server.port, os.path.split(CERTFILE)[1])
with test_support.check_py3k_warnings():
f = urllib.urlopen(url)
dlen = f.info().getheader("content-length")
if dlen and (int(dlen) > 0):
d2 = f.read(int(dlen))
if test_support.verbose:
sys.stdout.write(
" client: read %d bytes from remote server '%s'\n"
% (len(d2), server))
f.close()
self.assertEqual(d1, d2)
finally:
server.stop()
server.join()
def test_wrapped_accept(self):
"""Check the accept() method on SSL sockets."""
if test_support.verbose:
sys.stdout.write("\n")
server_params_test(CERTFILE, ssl.PROTOCOL_SSLv23, ssl.CERT_REQUIRED,
CERTFILE, CERTFILE, ssl.PROTOCOL_SSLv23,
chatty=True, connectionchatty=True,
wrap_accepting_socket=True)
def test_asyncore_server(self):
"""Check the example asyncore integration."""
indata = "TEST MESSAGE of mixed case\n"
if test_support.verbose:
sys.stdout.write("\n")
server = AsyncoreEchoServer(CERTFILE)
with server:
s = ssl.wrap_socket(socket.socket())
s.connect(('127.0.0.1', server.port))
if test_support.verbose:
sys.stdout.write(
" client: sending %s...\n" % (repr(indata)))
s.write(indata)
outdata = s.read()
if test_support.verbose:
sys.stdout.write(" client: read %s\n" % repr(outdata))
if outdata != indata.lower():
self.fail(
"bad data <<%s>> (%d) received; expected <<%s>> (%d)\n"
% (outdata[:min(len(outdata),20)], len(outdata),
indata[:min(len(indata),20)].lower(), len(indata)))
s.write("over\n")
if test_support.verbose:
sys.stdout.write(" client: closing connection.\n")
s.close()
def test_recv_send(self):
"""Test recv(), send() and friends."""
if test_support.verbose:
sys.stdout.write("\n")
server = ThreadedEchoServer(CERTFILE,
certreqs=ssl.CERT_NONE,
ssl_version=ssl.PROTOCOL_TLSv1,
cacerts=CERTFILE,
chatty=True,
connectionchatty=False)
with server:
s = ssl.wrap_socket(socket.socket(),
server_side=False,
certfile=CERTFILE,
ca_certs=CERTFILE,
cert_reqs=ssl.CERT_NONE,
ssl_version=ssl.PROTOCOL_TLSv1)
s.connect((HOST, server.port))
# helper methods for standardising recv* method signatures
def _recv_into():
b = bytearray("\0"*100)
count = s.recv_into(b)
return b[:count]
def _recvfrom_into():
b = bytearray("\0"*100)
count, addr = s.recvfrom_into(b)
return b[:count]
# (name, method, whether to expect success, *args)
send_methods = [
('send', s.send, True, []),
('sendto', s.sendto, False, ["some.address"]),
('sendall', s.sendall, True, []),
]
recv_methods = [
('recv', s.recv, True, []),
('recvfrom', s.recvfrom, False, ["some.address"]),
('recv_into', _recv_into, True, []),
('recvfrom_into', _recvfrom_into, False, []),
]
data_prefix = u"PREFIX_"
for meth_name, send_meth, expect_success, args in send_methods:
indata = data_prefix + meth_name
try:
send_meth(indata.encode('ASCII', 'strict'), *args)
outdata = s.read()
outdata = outdata.decode('ASCII', 'strict')
if outdata != indata.lower():
self.fail(
"While sending with <<%s>> bad data "
"<<%r>> (%d) received; "
"expected <<%r>> (%d)\n" % (
meth_name, outdata[:20], len(outdata),
indata[:20], len(indata)
)
)
except ValueError as e:
if expect_success:
self.fail(
"Failed to send with method <<%s>>; "
"expected to succeed.\n" % (meth_name,)
)
if not str(e).startswith(meth_name):
self.fail(
"Method <<%s>> failed with unexpected "
"exception message: %s\n" % (
meth_name, e
)
)
for meth_name, recv_meth, expect_success, args in recv_methods:
indata = data_prefix + meth_name
try:
s.send(indata.encode('ASCII', 'strict'))
outdata = recv_meth(*args)
outdata = outdata.decode('ASCII', 'strict')
if outdata != indata.lower():
self.fail(
"While receiving with <<%s>> bad data "
"<<%r>> (%d) received; "
"expected <<%r>> (%d)\n" % (
meth_name, outdata[:20], len(outdata),
indata[:20], len(indata)
)
)
except ValueError as e:
if expect_success:
self.fail(
"Failed to receive with method <<%s>>; "
"expected to succeed.\n" % (meth_name,)
)
if not str(e).startswith(meth_name):
self.fail(
"Method <<%s>> failed with unexpected "
"exception message: %s\n" % (
meth_name, e
)
)
# consume data
s.read()
s.write("over\n".encode("ASCII", "strict"))
s.close()
def test_handshake_timeout(self):
# Issue #5103: SSL handshake must respect the socket timeout
server = socket.socket(socket.AF_INET)
host = "127.0.0.1"
port = test_support.bind_port(server)
started = threading.Event()
finish = False
def serve():
server.listen(5)
started.set()
conns = []
while not finish:
r, w, e = select.select([server], [], [], 0.1)
if server in r:
# Let the socket hang around rather than having
# it closed by garbage collection.
conns.append(server.accept()[0])
t = threading.Thread(target=serve)
t.start()
started.wait()
try:
try:
c = socket.socket(socket.AF_INET)
c.settimeout(0.2)
c.connect((host, port))
# Will attempt handshake and time out
self.assertRaisesRegexp(ssl.SSLError, "timed out",
ssl.wrap_socket, c)
finally:
c.close()
try:
c = socket.socket(socket.AF_INET)
c.settimeout(0.2)
c = ssl.wrap_socket(c)
# Will attempt handshake and time out
self.assertRaisesRegexp(ssl.SSLError, "timed out",
c.connect, (host, port))
finally:
c.close()
finally:
finish = True
t.join()
server.close()
def test_default_ciphers(self):
with ThreadedEchoServer(CERTFILE,
ssl_version=ssl.PROTOCOL_SSLv23,
chatty=False) as server:
sock = socket.socket()
try:
# Force a set of weak ciphers on our client socket
try:
s = ssl.wrap_socket(sock,
ssl_version=ssl.PROTOCOL_SSLv23,
ciphers="DES")
except ssl.SSLError:
self.skipTest("no DES cipher available")
with self.assertRaises((OSError, ssl.SSLError)):
s.connect((HOST, server.port))
finally:
sock.close()
self.assertIn("no shared cipher", str(server.conn_errors[0]))
def test_main(verbose=False):
global CERTFILE, SVN_PYTHON_ORG_ROOT_CERT, NOKIACERT
CERTFILE = os.path.join(os.path.dirname(__file__) or os.curdir,
"keycert.pem")
SVN_PYTHON_ORG_ROOT_CERT = os.path.join(
os.path.dirname(__file__) or os.curdir,
"https_svn_python_org_root.pem")
NOKIACERT = os.path.join(os.path.dirname(__file__) or os.curdir,
"nokia.pem")
if (not os.path.exists(CERTFILE) or
not os.path.exists(SVN_PYTHON_ORG_ROOT_CERT) or
not os.path.exists(NOKIACERT)):
raise test_support.TestFailed("Can't read certificate files!")
tests = [BasicTests, BasicSocketTests]
if test_support.is_resource_enabled('network') and not test_support.is_jython:
# These tests need to be updated since they rely on CERT_NONE
# and in certain cases unavailable network resources
tests.append(NetworkedTests)
if _have_threads and not test_support.is_jython:
thread_info = test_support.threading_setup()
if thread_info and test_support.is_resource_enabled('network'):
tests.append(ThreadedTests)
try:
test_support.run_unittest(*tests)
finally:
if _have_threads and not test_support.is_jython:
test_support.threading_cleanup(*thread_info)
if __name__ == "__main__":
test_main()
|
tunnel.py | """Basic ssh tunnel utilities, and convenience functions for tunneling
zeromq connections.
"""
# Copyright (C) 2010-2011 IPython Development Team
# Copyright (C) 2011- PyZMQ Developers
#
# Redistributed from IPython under the terms of the BSD License.
import atexit
import os
import re
import signal
import socket
import sys
import warnings
from getpass import getpass
from getpass import getuser
from multiprocessing import Process
try:
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
import paramiko # type: ignore
SSHException = paramiko.ssh_exception.SSHException
except ImportError:
paramiko = None # type: ignore
class SSHException(Exception): # type: ignore
pass
else:
from .forward import forward_tunnel
try:
import pexpect # type: ignore
except ImportError:
pexpect = None
def select_random_ports(n):
"""Select and return n random ports that are available."""
ports = []
sockets = []
for _ in range(n):
sock = socket.socket()
sock.bind(("", 0))
ports.append(sock.getsockname()[1])
sockets.append(sock)
for sock in sockets:
sock.close()
return ports
# -----------------------------------------------------------------------------
# Check for passwordless login
# -----------------------------------------------------------------------------
_password_pat = re.compile((r"pass(word|phrase):".encode("utf8")), re.IGNORECASE)
def try_passwordless_ssh(server, keyfile, paramiko=None):
"""Attempt to make an ssh connection without a password.
This is mainly used for requiring password input only once
when many tunnels may be connected to the same server.
If paramiko is None, the default for the platform is chosen.
"""
if paramiko is None:
paramiko = sys.platform == "win32"
if not paramiko:
f = _try_passwordless_openssh
else:
f = _try_passwordless_paramiko
return f(server, keyfile)
def _try_passwordless_openssh(server, keyfile):
"""Try passwordless login with shell ssh command."""
if pexpect is None:
raise ImportError("pexpect unavailable, use paramiko")
cmd = "ssh -f " + server
if keyfile:
cmd += " -i " + keyfile
cmd += " exit"
# pop SSH_ASKPASS from env
env = os.environ.copy()
env.pop("SSH_ASKPASS", None)
ssh_newkey = "Are you sure you want to continue connecting"
p = pexpect.spawn(cmd, env=env)
while True:
try:
i = p.expect([ssh_newkey, _password_pat], timeout=0.1)
if i == 0:
raise SSHException("The authenticity of the host can't be established.")
except pexpect.TIMEOUT:
continue
except pexpect.EOF:
return True
else:
return False
def _try_passwordless_paramiko(server, keyfile):
"""Try passwordless login with paramiko."""
if paramiko is None:
msg = "Paramiko unavailable, "
if sys.platform == "win32":
msg += "Paramiko is required for ssh tunneled connections on Windows."
else:
msg += "use OpenSSH."
raise ImportError(msg)
username, server, port = _split_server(server)
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
try:
client.connect(server, port, username=username, key_filename=keyfile, look_for_keys=True)
except paramiko.AuthenticationException:
return False
else:
client.close()
return True
def tunnel_connection(socket, addr, server, keyfile=None, password=None, paramiko=None, timeout=60):
"""Connect a socket to an address via an ssh tunnel.
This is a wrapper for socket.connect(addr), when addr is not accessible
from the local machine. It simply creates an ssh tunnel using the remaining args,
and calls socket.connect('tcp://localhost:lport') where lport is the randomly
selected local port of the tunnel.
"""
new_url, tunnel = open_tunnel(
addr,
server,
keyfile=keyfile,
password=password,
paramiko=paramiko,
timeout=timeout,
)
socket.connect(new_url)
return tunnel
def open_tunnel(addr, server, keyfile=None, password=None, paramiko=None, timeout=60):
"""Open a tunneled connection from a 0MQ url.
For use inside tunnel_connection.
Returns
-------
(url, tunnel) : (str, object)
The 0MQ url that has been forwarded, and the tunnel object
"""
lport = select_random_ports(1)[0]
transport, addr = addr.split("://")
ip, rport = addr.split(":")
rport = int(rport)
if paramiko is None:
paramiko = sys.platform == "win32"
if paramiko:
tunnelf = paramiko_tunnel
else:
tunnelf = openssh_tunnel
tunnel = tunnelf(
lport,
rport,
server,
remoteip=ip,
keyfile=keyfile,
password=password,
timeout=timeout,
)
return "tcp://127.0.0.1:%i" % lport, tunnel
def openssh_tunnel(
lport, rport, server, remoteip="127.0.0.1", keyfile=None, password=None, timeout=60
):
"""Create an ssh tunnel using command-line ssh that connects port lport
on this machine to localhost:rport on server. The tunnel
will automatically close when not in use, remaining open
for a minimum of timeout seconds for an initial connection.
This creates a tunnel redirecting `localhost:lport` to `remoteip:rport`,
as seen from `server`.
keyfile and password may be specified, but ssh config is checked for defaults.
Parameters
----------
lport : int
local port for connecting to the tunnel from this machine.
rport : int
port on the remote machine to connect to.
server : str
The ssh server to connect to. The full ssh server string will be parsed.
user@server:port
remoteip : str [Default: 127.0.0.1]
The remote ip, specifying the destination of the tunnel.
Default is localhost, which means that the tunnel would redirect
localhost:lport on this machine to localhost:rport on the *server*.
keyfile : str; path to public key file
This specifies a key to be used in ssh login, default None.
Regular default ssh keys will be used without specifying this argument.
password : str;
Your ssh password to the ssh server. Note that if this is left None,
you will be prompted for it if passwordless key based login is unavailable.
timeout : int [default: 60]
The time (in seconds) after which no activity will result in the tunnel
closing. This prevents orphaned tunnels from running forever.
"""
if pexpect is None:
raise ImportError("pexpect unavailable, use paramiko_tunnel")
ssh = "ssh "
if keyfile:
ssh += "-i " + keyfile
if ":" in server:
server, port = server.split(":")
ssh += " -p %s" % port
cmd = "%s -O check %s" % (ssh, server)
(output, exitstatus) = pexpect.run(cmd, withexitstatus=True)
if not exitstatus:
pid = int(output[output.find(b"(pid=") + 5 : output.find(b")")]) # noqa
cmd = "%s -O forward -L 127.0.0.1:%i:%s:%i %s" % (
ssh,
lport,
remoteip,
rport,
server,
)
(output, exitstatus) = pexpect.run(cmd, withexitstatus=True)
if not exitstatus:
atexit.register(_stop_tunnel, cmd.replace("-O forward", "-O cancel", 1))
return pid
cmd = "%s -f -S none -L 127.0.0.1:%i:%s:%i %s sleep %i" % (
ssh,
lport,
remoteip,
rport,
server,
timeout,
)
# pop SSH_ASKPASS from env
env = os.environ.copy()
env.pop("SSH_ASKPASS", None)
ssh_newkey = "Are you sure you want to continue connecting"
tunnel = pexpect.spawn(cmd, env=env)
failed = False
while True:
try:
i = tunnel.expect([ssh_newkey, _password_pat], timeout=0.1)
if i == 0:
raise SSHException("The authenticity of the host can't be established.")
except pexpect.TIMEOUT:
continue
except pexpect.EOF as e:
if tunnel.exitstatus:
print(tunnel.exitstatus)
print(tunnel.before)
print(tunnel.after)
raise RuntimeError("tunnel '%s' failed to start" % (cmd)) from e
else:
return tunnel.pid
else:
if failed:
print("Password rejected, try again")
password = None
if password is None:
password = getpass("%s's password: " % (server))
tunnel.sendline(password)
failed = True
def _stop_tunnel(cmd):
pexpect.run(cmd)
def _split_server(server):
if "@" in server:
username, server = server.split("@", 1)
else:
username = getuser()
if ":" in server:
server, port = server.split(":")
port = int(port)
else:
port = 22
return username, server, port
def paramiko_tunnel(
lport, rport, server, remoteip="127.0.0.1", keyfile=None, password=None, timeout=60
):
"""launch a tunner with paramiko in a subprocess. This should only be used
when shell ssh is unavailable (e.g. Windows).
This creates a tunnel redirecting `localhost:lport` to `remoteip:rport`,
as seen from `server`.
If you are familiar with ssh tunnels, this creates the tunnel:
ssh server -L localhost:lport:remoteip:rport
keyfile and password may be specified, but ssh config is checked for defaults.
Parameters
----------
lport : int
local port for connecting to the tunnel from this machine.
rport : int
port on the remote machine to connect to.
server : str
The ssh server to connect to. The full ssh server string will be parsed.
user@server:port
remoteip : str [Default: 127.0.0.1]
The remote ip, specifying the destination of the tunnel.
Default is localhost, which means that the tunnel would redirect
localhost:lport on this machine to localhost:rport on the *server*.
keyfile : str; path to public key file
This specifies a key to be used in ssh login, default None.
Regular default ssh keys will be used without specifying this argument.
password : str;
Your ssh password to the ssh server. Note that if this is left None,
you will be prompted for it if passwordless key based login is unavailable.
timeout : int [default: 60]
The time (in seconds) after which no activity will result in the tunnel
closing. This prevents orphaned tunnels from running forever.
"""
if paramiko is None:
raise ImportError("Paramiko not available")
if password is None:
if not _try_passwordless_paramiko(server, keyfile):
password = getpass("%s's password: " % (server))
p = Process(
target=_paramiko_tunnel,
args=(lport, rport, server, remoteip),
kwargs=dict(keyfile=keyfile, password=password),
)
p.daemon = True
p.start()
return p
def _paramiko_tunnel(lport, rport, server, remoteip, keyfile=None, password=None):
"""Function for actually starting a paramiko tunnel, to be passed
to multiprocessing.Process(target=this), and not called directly.
"""
username, server, port = _split_server(server)
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
try:
client.connect(
server,
port,
username=username,
key_filename=keyfile,
look_for_keys=True,
password=password,
)
# except paramiko.AuthenticationException:
# if password is None:
# password = getpass("%s@%s's password: "%(username, server))
# client.connect(server, port, username=username, password=password)
# else:
# raise
except Exception as e:
print("*** Failed to connect to %s:%d: %r" % (server, port, e))
sys.exit(1)
# Don't let SIGINT kill the tunnel subprocess
signal.signal(signal.SIGINT, signal.SIG_IGN)
try:
forward_tunnel(lport, remoteip, rport, client.get_transport())
except KeyboardInterrupt:
print("SIGINT: Port forwarding stopped cleanly")
sys.exit(0)
except Exception as e:
print("Port forwarding stopped uncleanly: %s" % e)
sys.exit(255)
if sys.platform == "win32":
ssh_tunnel = paramiko_tunnel
else:
ssh_tunnel = openssh_tunnel
__all__ = [
"tunnel_connection",
"ssh_tunnel",
"openssh_tunnel",
"paramiko_tunnel",
"try_passwordless_ssh",
]
|
tello_driver_node_old.py | #!/usr/bin/env python2
import rospy
from std_msgs.msg import Empty, UInt8, Bool
from std_msgs.msg import UInt8MultiArray
from sensor_msgs.msg import Image
from geometry_msgs.msg import Twist
from nav_msgs.msg import Odometry
from dynamic_reconfigure.server import Server
# from h264_image_transport.msg import H264Packet
from tello_driver.msg import TelloStatus
from tello_driver.cfg import TelloConfig
from cv_bridge import CvBridge, CvBridgeError
import av
import math
import numpy as np
import threading
import time
from tellopy._internal import tello
from tellopy._internal import error
from tellopy._internal import protocol
from tellopy._internal import logger
class RospyLogger(logger.Logger):
def __init__(self, header=''):
super(RospyLogger, self).__init__(header)
def error(self, s):
if self.log_level < logger.LOG_ERROR:
return
rospy.logerr(s)
def warn(self, s):
if self.log_level < logger.LOG_WARN:
return
rospy.logwarn(s)
def info(self, s):
if self.log_level < logger.LOG_INFO:
return
rospy.loginfo(s)
def debug(self, s):
if self.log_level < logger.LOG_DEBUG:
return
rospy.logdebug(s)
def notify_cmd_success(cmd, success):
if success:
rospy.loginfo('%s command executed' % cmd)
else:
rospy.logwarn('%s command failed' % cmd)
class TelloNode(tello.Tello):
def __init__(self):
self.client_port = int(
rospy.get_param('~client_port', 8890))
self.vid_port = int(
rospy.get_param('~vid_port', 6038))
self.conn_port = int(
rospy.get_param('~conn_port', 9617))
self.tello_ip = rospy.get_param('~tello_ip', '192.168.10.1')
self.tello_port = int(
rospy.get_param('~tello_port', 8889))
self.connect_timeout_sec = float(
rospy.get_param('~connect_timeout_sec', 10.0))
self.frame_id = rospy.get_param('~frame_id', 'tello')
# self.stream_h264_video = bool(
# rospy.get_param('~stream_h264_video', False))
self.bridge = CvBridge()
self.frame_thread = None
# Connect to drone
log = RospyLogger('Tello')
log.set_level(self.LOG_WARN)
super(TelloNode, self).__init__(
client_port=self.client_port,
vid_port=self.vid_port,
conn_port=self.conn_port,
tello_ip=self.tello_ip,
tello_port=self.tello_port,
log=log)
rospy.loginfo('Connecting to drone @ %s:%d' % self.tello_addr)
self.connect()
try:
self.wait_for_connection(timeout=self.connect_timeout_sec)
except error.TelloError as err:
rospy.logerr(str(err))
rospy.signal_shutdown(str(err))
self.quit()
return
rospy.loginfo('Connected to drone')
rospy.on_shutdown(self.cb_shutdown)
# Setup dynamic reconfigure
self.cfg = None
self.srv_dyncfg = Server(TelloConfig, self.cb_dyncfg)
# Setup topics and services
# NOTE: ROS interface deliberately made to resemble bebop_autonomy
self.pub_status = rospy.Publisher(
'status', TelloStatus, queue_size=1, latch=True)
self.pub_image_raw = rospy.Publisher(
'image_raw', Image, queue_size=10)
# if self.stream_h264_video:
# self.pub_image_h264 = rospy.Publisher(
# 'image_raw/h264', H264Packet, queue_size=10)
# else:
# self.pub_image_raw = rospy.Publisher(
# 'image_raw', Image, queue_size=10)
self.sub_takeoff = rospy.Subscriber('takeoff', Empty, self.cb_takeoff)
self.sub_throw_takeoff = rospy.Subscriber(
'throw_takeoff', Empty, self.cb_throw_takeoff)
self.sub_land = rospy.Subscriber('land', Empty, self.cb_land)
self.sub_palm_land = rospy.Subscriber(
'palm_land', Empty, self.cb_palm_land)
self.sub_flip = rospy.Subscriber('flip', UInt8, self.cb_flip)
self.sub_cmd_vel = rospy.Subscriber('cmd_vel', Twist, self.cb_cmd_vel)
self.subscribe(self.EVENT_FLIGHT_DATA, self.cb_status_telem)
self.frame_thread = threading.Thread(target=self.framegrabber_loop)
self.frame_thread.start()
# if self.stream_h264_video:
# self.start_video()
# self.subscribe(self.EVENT_VIDEO_FRAME, self.cb_h264_frame)
# else:
# self.frame_thread = threading.Thread(target=self.framegrabber_loop)
# self.frame_thread.start()
rospy.loginfo('Tello driver node ready')
def cb_shutdown(self):
self.quit()
if self.frame_thread is not None:
self.frame_thread.join()
def cb_status_telem(self, event, sender, data, **args):
speed_horizontal_mps = math.sqrt(data.north_speed * data.north_speed + data.east_speed * data.east_speed) / 10.0
# TODO: verify outdoors: anecdotally, observed that:
# data.east_speed points to South
# data.north_speed points to East
msg = TelloStatus(
height_m=data.height / 10.,
speed_northing_mps=-data.east_speed / 10.,
speed_easting_mps=data.north_speed / 10.,
speed_horizontal_mps=speed_horizontal_mps,
speed_vertical_mps=-data.ground_speed / 10.,
flight_time_sec=data.fly_time / 10.,
imu_state=data.imu_state,
pressure_state=data.pressure_state,
down_visual_state=data.down_visual_state,
power_state=data.power_state,
battery_state=data.battery_state,
gravity_state=data.gravity_state,
wind_state=data.wind_state,
imu_calibration_state=data.imu_calibration_state,
battery_percentage=data.battery_percentage,
drone_fly_time_left_sec=data.drone_fly_time_left / 10.,
drone_battery_left_sec=data.drone_battery_left / 10.,
is_flying=data.em_sky,
is_on_ground=data.em_ground,
is_em_open=data.em_open,
is_drone_hover=data.drone_hover,
is_outage_recording=data.outage_recording,
is_battery_low=data.battery_low,
is_battery_lower=data.battery_lower,
is_factory_mode=data.factory_mode,
fly_mode=data.fly_mode,
throw_takeoff_timer_sec=data.throw_fly_timer / 10.,
camera_state=data.camera_state,
electrical_machinery_state=data.electrical_machinery_state,
front_in=data.front_in,
front_out=data.front_out,
front_lsc=data.front_lsc,
temperature_height_m=data.temperature_height / 10.,
cmd_roll_ratio=self.right_x,
cmd_pitch_ratio=self.right_y,
cmd_yaw_ratio=self.left_x,
cmd_vspeed_ratio=self.left_y,
cmd_fast_mode=False,
)
self.pub_status.publish(msg)
def cb_odom_log(self, event, sender, data, **args):
odom_msg = UInt8MultiArray()
odom_msg.data = str(data)
# self.pub_odom.publish(odom_msg)
# def cb_h264_frame(self, event, sender, data, **args):
# frame, seq_id, frame_secs = data
# pkt_msg = H264Packet()
# pkt_msg.header.seq = seq_id
# pkt_msg.header.frame_id = rospy.get_namespace()
# pkt_msg.header.stamp = rospy.Time.from_sec(frame_secs)
# pkt_msg.data = frame
# self.pub_image_h264.publish(pkt_msg)
def framegrabber_loop(self):
# delay start
rospy.sleep(2.0)
try:
container = None
while self.state != self.STATE_QUIT:
try:
container = av.open(self.get_video_stream())
break
except BaseException as err:
rospy.logerr('fgrab: pyav stream failed - %s' % str(err))
rospy.loginfo('pyav restart')
rospy.sleep(0.5)
continue
while self.state != self.STATE_QUIT:
for frame in container.decode(video=0):
img = np.array(frame.to_image())
img_msg = None
try:
img_msg = self.bridge.cv2_to_imgmsg(img, 'rgb8')
img_msg.header.frame_id = self.frame_id
except CvBridgeError as err:
rospy.logerr('fgrab: cv bridge failed - %s' % str(err))
continue
# rospy.loginfo('publish img')
self.pub_image_raw.publish(img_msg)
break
except BaseException as err:
rospy.logerr('fgrab: pyav decoder failed - %s' % str(err))
def cb_dyncfg(self, config, level):
update_all = False
req_sps_pps = False
if self.cfg is None:
self.cfg = config
update_all = True
if update_all or self.cfg.fixed_video_rate != config.fixed_video_rate:
self.set_video_encoder_rate(config.fixed_video_rate)
req_sps_pps = True
self.cfg = config
return self.cfg
def cb_takeoff(self, msg):
success = self.takeoff()
notify_cmd_success('Takeoff', success)
def cb_throw_takeoff(self, msg):
success = self.throw_and_go()
if success:
rospy.loginfo('Drone set to auto-takeoff when thrown')
else:
rospy.logwarn('ThrowTakeoff command failed')
def cb_land(self, msg):
success = self.land()
notify_cmd_success('Land', success)
def cb_palm_land(self, msg):
success = self.palm_land()
notify_cmd_success('PalmLand', success)
def cb_flip(self, msg):
if msg.data < 0 or msg.data > protocol.FlipForwardRight:
rospy.logwarn('Invalid flip direction: %d' % msg.data)
return
success = None
if msg.data is protocol.FlipFront:
success = self.flip_forward()
elif msg.data is protocol.FlipLeft:
success = self.flip_left()
elif msg.data is protocol.FlipBack:
success = self.flip_back()
elif msg.data is protocol.FlipRight:
success = self.flip_right()
elif msg.data is protocol.FlipForwardLeft:
success = self.flip_forwardleft()
elif msg.data is protocol.FlipBackLeft:
success = self.flip_backleft()
elif msg.data is protocol.FlipBackRight:
success = self.flip_backright()
elif msg.data is self.flip_forwardright():
success = self.flip_forwardright()
notify_cmd_success('Flip %d' % msg.data, success)
def cb_cmd_vel(self, msg):
self.set_pitch(msg.linear.x)
self.set_roll(-msg.linear.y)
self.set_yaw(-msg.angular.z)
self.set_throttle(msg.linear.z)
def main():
rospy.init_node('tello_node')
robot = TelloNode()
if robot.state != robot.STATE_QUIT:
rospy.spin()
if __name__ == '__main__':
main() |
database_throughput_test.py | #!/usr/bin/env python3
# Copyright 2017-2019 object_database 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, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import threading
import argparse
import sys
import time
from object_database import connect, Schema
def main(argv):
parser = argparse.ArgumentParser("Run a database throughput test")
parser.add_argument("host")
parser.add_argument("port")
parser.add_argument(
"--service-token",
type=str,
required=True,
help="the auth token to be used with this service",
)
parser.add_argument("seconds", type=float)
parser.add_argument("--threads", dest="threads", type=int, default=1)
parsedArgs = parser.parse_args(argv[1:])
db = connect(parsedArgs.host, parsedArgs.port, parsedArgs.service_token)
schema = Schema("database_throughput_test")
@schema.define
class Counter:
k = int
db.subscribeToSchema(schema)
t0 = time.time()
transactionCount = []
def doWork():
with db.transaction():
c = Counter()
while time.time() - t0 < parsedArgs.seconds:
with db.transaction():
c.k = c.k + 1
with db.view():
transactionCount.append(c.k)
threads = [threading.Thread(target=doWork) for _ in range(parsedArgs.threads)]
for t in threads:
t.start()
for t in threads:
t.join()
print(sum(transactionCount) / parsedArgs.seconds, " transactions per second")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
|
manual_control_test.py | import random
import time
import threading
def inp_handler(name):
from pynput.keyboard import Key, Controller as KeyboardController
keyboard = KeyboardController()
time.sleep(0.1)
choices = ['w', 'a', 's', 'd', 'j', 'k', Key.left, Key.right, Key.up, Key.down]
NUM_TESTS = 50
for x in range(NUM_TESTS):
i = random.choice(choices) if x != NUM_TESTS - 1 else Key.esc
keyboard.press(i)
time.sleep(0.1)
keyboard.release(i)
def manual_control_test(manual_control):
manual_in_thread = threading.Thread(target=inp_handler, args=(1,))
manual_in_thread.start()
try:
manual_control()
except Exception:
raise Exception("manual_control() has crashed. Please fix it.")
manual_in_thread.join()
|
api.py | # -*- coding: utf-8 -*-
"""
api
~~~
Implements API Server and Interface
:author: Feei <feei@feei.cn>
:homepage: https://github.com/wufeifei/cobra
:license: MIT, see LICENSE for more details.
:copyright: Copyright (c) 2017 Feei. All rights reserved
"""
import errno
import json
import multiprocessing
import os
import socket
import subprocess
import threading
import time
import traceback
import requests
from flask import Flask, request, render_template
from flask_restful import Api, Resource
from werkzeug.urls import url_unquote
from . import cli
from .cli import get_sid
from .config import Config, running_path, package_path
from .engine import Running
from .log import logger
from .utils import allowed_file, secure_filename, PY2
try:
# Python 3
import queue
except ImportError:
# Python 2
import Queue as queue
q = queue.Queue()
app = Flask(__name__, static_folder='templates/asset')
running_host = '0.0.0.0'
running_port = 5000
def producer(task):
q.put(task)
def consumer():
while True:
task = q.get()
p = multiprocessing.Process(target=cli.start, args=task)
p.start()
p.join()
q.task_done()
class AddJob(Resource):
@staticmethod
def post():
data = request.json
if not data or data == "":
return {"code": 1003, "msg": "Only support json, please post json data."}
target = data.get("target")
formatter = data.get("formatter")
output = data.get("output")
rule = data.get("rule")
is_valid_key = key_verify(data=data)
if is_valid_key is not True:
return is_valid_key
if not target or target == "":
return {"code": 1002, "msg": "URL cannot be empty."}
if not formatter or formatter == '':
formatter = 'json'
if not output or output == '':
output = ''
if not rule or rule == '':
rule = ''
# Report All Id
a_sid = get_sid(target, True)
running = Running(a_sid)
# Write a_sid running data
running.init_list(data=target)
# Write a_sid running status
data = {
'status': 'running',
'report': ''
}
running.status(data)
if isinstance(target, list):
for t in target:
# Scan
arg = (t, formatter, output, rule, a_sid)
producer(task=arg)
result = {
'msg': 'Add scan job successfully.',
'sid': a_sid,
'total_target_num': len(target),
}
else:
arg = (target, formatter, output, rule, a_sid)
producer(task=arg)
result = {
'msg': 'Add scan job successfully.',
'sid': a_sid,
'total_target_num': 1,
}
return {"code": 1001, "result": result}
class JobStatus(Resource):
@staticmethod
def post():
data = request.json
if not data or data == "":
return {"code": 1003, "msg": "Only support json, please post json data."}
sid = data.get("sid")
is_valid_key = key_verify(data=data)
if is_valid_key is not True:
return is_valid_key
if not sid or sid == "":
return {"code": 1002, "msg": "sid is required."}
sid = str(data.get("sid")) # ้่ฆๆผๆฅๅ
ฅ่ทฏๅพ๏ผ่ฝฌไธบๅญ็ฌฆไธฒ
running = Running(sid)
if running.is_file() is not True:
data = {
'code': 1004,
'msg': 'scan id does not exist!',
'sid': sid,
'status': 'no such scan',
'report': ''
}
return data
else:
result = running.status()
r_data = running.list()
if result['status'] == 'running':
ret = True
result['still_running'] = dict()
for s_sid, git in r_data['sids'].items():
if Running(s_sid).is_file(True) is False:
result['still_running'].update({s_sid: git})
ret = False
if ret:
result['status'] = 'done'
running.status(result)
data = {
'msg': 'success',
'sid': sid,
'status': result.get('status'),
'report': result.get('report'),
'still_running': result.get('still_running'),
'total_target_num': r_data.get('total_target_num'),
'not_finished': int(r_data.get('total_target_num')) - len(r_data.get('sids'))
+ len(result.get('still_running')),
}
return {"code": 1001, "result": data}
class FileUpload(Resource):
@staticmethod
def post():
"""
Scan by uploading compressed files
:return:
"""
if 'file' not in request.files:
return {'code': 1002, 'result': "File can't empty!"}
file_instance = request.files['file']
if file_instance.filename == '':
return {'code': 1002, 'result': "File name can't empty!"}
if file_instance and allowed_file(file_instance.filename):
filename = secure_filename(file_instance.filename)
dst_directory = os.path.join(package_path, filename)
file_instance.save(dst_directory)
# Start scan
a_sid = get_sid(dst_directory, True)
data = {
'status': 'running',
'report': ''
}
Running(a_sid).status(data)
try:
cli.start(dst_directory, None, 'stream', None, a_sid=a_sid)
except Exception as e:
traceback.print_exc()
code, result = 1001, {'sid': a_sid}
return {'code': code, 'result': result}
else:
return {'code': 1002, 'result': "This extension can't support!"}
class ResultData(Resource):
@staticmethod
def post():
"""
pull scan result data.
:return:
"""
data = request.json
if not data or data == "":
return {"code": 1003, "msg": "Only support json, please post json data."}
s_sid = data.get('sid')
if not s_sid or s_sid == "":
return {"code": 1002, "msg": "sid is required."}
s_sid_file = os.path.join(running_path, '{sid}_data'.format(sid=s_sid))
if not os.path.exists(s_sid_file):
return {'code': 1002, 'msg': 'No such target.'}
with open(s_sid_file, 'r') as f:
scan_data = json.load(f)
if scan_data.get('code') == 1001:
scan_data = scan_data.get('result')
else:
return {
'code': scan_data.get('code'),
'msg': scan_data.get('msg'),
}
rule_filter = dict()
for vul in scan_data.get('vulnerabilities'):
rule_filter[vul.get('id')] = vul.get('rule_name')
return {
'code': 1001,
'result': {
'scan_data': scan_data,
'rule_filter': rule_filter,
}
}
class ResultDetail(Resource):
@staticmethod
def post():
"""
get vulnerable file content
:return:
"""
data = request.json
if not data or data == "":
return {'code': 1003, 'msg': 'Only support json, please post json data.'}
sid = data.get('sid')
file_path = url_unquote(data.get('file_path'))
if not sid or sid == '':
return {"code": 1002, "msg": "sid is required."}
if not file_path or file_path == '':
return {'code': 1002, 'msg': 'file_path is required.'}
s_sid_file = os.path.join(running_path, '{sid}_data'.format(sid=sid))
if not os.path.exists(s_sid_file):
return {'code': 1002, 'msg': 'No such target.'}
with open(s_sid_file, 'r') as f:
target_directory = json.load(f).get('result').get('target_directory')
if not target_directory or target_directory == '':
return {'code': 1002, 'msg': 'No such directory'}
if PY2:
file_path = map(secure_filename, [path.decode('utf-8') for path in file_path.split('/')])
else:
file_path = map(secure_filename, [path for path in file_path.split('/')])
filename = target_directory
for _dir in file_path:
filename = os.path.join(filename, _dir)
if os.path.exists(filename):
extension = guess_type(filename)
if is_text(filename):
with open(filename, 'r') as f:
file_content = f.read()
else:
file_content = 'This is a binary file.'
else:
return {'code': 1002, 'msg': 'No such file.'}
return {'code': 1001, 'result': {'file_content': file_content,
'extension': extension}}
@app.route('/', methods=['GET', 'POST'])
def summary():
a_sid = request.args.get(key='sid')
key = Config(level1="cobra", level2="secret_key").value
if a_sid is None:
return render_template(template_name_or_list='index.html',
key=key)
status_url = 'http://{host}:{port}/api/status'.format(host=running_host, port=running_port)
logger.critical(status_url)
post_data = {
'key': key,
'sid': a_sid,
}
headers = {
"Content-Type": "application/json",
}
r = requests.post(url=status_url, headers=headers, data=json.dumps(post_data))
try:
scan_status = json.loads(r.text)
except ValueError as e:
return render_template(template_name_or_list='error.html',
msg='Check scan status failed: {0}'.format(e))
if scan_status.get('code') != 1001:
return render_template(template_name_or_list='error.html',
msg=scan_status.get('msg'))
else:
if scan_status.get('result').get('status') == 'running':
still_running = scan_status.get('result').get('still_running')
for s_sid, target_str in still_running.items():
split_target = target_str.split(':')
if len(split_target) == 3:
target, branch = '{p}:{u}'.format(p=split_target[0], u=split_target[1]), split_target[-1]
elif len(split_target) == 2:
target, branch = target_str, 'master'
else:
logger.critical('[API] Target url exception: {u}'.format(u=target_str))
target, branch = target_str, 'master'
still_running[s_sid] = {'target': target,
'branch': branch}
else:
still_running = dict()
scan_status_file = os.path.join(running_path, '{sid}_status'.format(sid=a_sid))
scan_list = Running(a_sid).list()
start_time = os.path.getctime(filename=scan_status_file)
start_time = time.localtime(start_time)
start_time = time.strftime('%Y-%m-%d %H:%M:%S', start_time)
total_targets_number = scan_status.get('result').get('total_target_num')
not_finished_number = scan_status.get('result').get('not_finished')
total_vul_number, critical_vul_number, high_vul_number, medium_vul_number, low_vul_number = 0, 0, 0, 0, 0
rule_filter = dict()
targets = list()
for s_sid, target_str in scan_list.get('sids').items():
if s_sid not in still_running:
target_info = dict()
# ๅๅฒ้กน็ฎๅฐๅไธๅๆฏ๏ผ้ป่ฎค master
split_target = target_str.split(':')
if len(split_target) == 3:
target, branch = '{p}:{u}'.format(p=split_target[0], u=split_target[1]), split_target[-1]
elif len(split_target) == 2:
target, branch = target_str, 'master'
else:
logger.critical('Target url exception: {u}'.format(u=target_str))
target, branch = target_str, 'master'
target_info.update({
'sid': s_sid,
'target': target,
'branch': branch,
})
s_sid_file = os.path.join(running_path, '{sid}_data'.format(sid=s_sid))
with open(s_sid_file, 'r') as f:
s_sid_data = json.load(f)
if s_sid_data.get('code') != 1001:
continue
else:
s_sid_data = s_sid_data.get('result')
total_vul_number += len(s_sid_data.get('vulnerabilities'))
target_info.update({'total_vul_number': len(s_sid_data.get('vulnerabilities'))})
target_info.update(s_sid_data)
targets.append(target_info)
for vul in s_sid_data.get('vulnerabilities'):
if 9 <= int(vul.get('level')) <= 10:
critical_vul_number += 1
elif 6 <= int(vul.get('level')) <= 8:
high_vul_number += 1
elif 3 <= int(vul.get('level')) <= 5:
medium_vul_number += 1
elif 1 <= int(vul.get('level')) <= 2:
low_vul_number += 1
try:
rule_filter[vul.get('rule_name')] += 1
except KeyError:
rule_filter[vul.get('rule_name')] = 1
return render_template(template_name_or_list='summary.html',
total_targets_number=total_targets_number,
not_finished_number=not_finished_number,
start_time=start_time,
targets=targets,
a_sid=a_sid,
total_vul_number=total_vul_number,
critical_vul_number=critical_vul_number,
high_vul_number=high_vul_number,
medium_vul_number=medium_vul_number,
low_vul_number=low_vul_number,
vuls=rule_filter,
running=still_running,)
def key_verify(data):
key = Config(level1="cobra", level2="secret_key").value
_key = data.get("key")
if _key == key:
return True
elif not _key or _key == "":
return {"code": 1002, "msg": "Key cannot be empty."}
elif not _key == key:
return {"code": 4002, "msg": "Key verify failed."}
else:
return {"code": 4002, "msg": "Unknown key verify error."}
def is_text(fn):
msg = subprocess.Popen(['file', fn], stdout=subprocess.PIPE).communicate()[0]
return 'text' in msg.decode('utf-8')
def guess_type(fn):
import mimetypes
extension = mimetypes.guess_type(fn)[0]
if extension:
"""text/x-python or text/x-java-source"""
# extension = extension.split('/')[1]
extension = extension.replace('-source', '')
else:
extension = fn.split('/')[-1].split('.')[-1]
custom_ext = {
'html': 'htmlmixed',
'md': 'markdown',
}
if custom_ext.get(extension) is not None:
extension = custom_ext.get(extension)
return extension.lower()
def start(host, port, debug):
logger.info('Start {host}:{port}'.format(host=host, port=port))
api = Api(app)
api.add_resource(AddJob, '/api/add')
api.add_resource(JobStatus, '/api/status')
api.add_resource(FileUpload, '/api/upload')
api.add_resource(ResultData, '/api/list')
api.add_resource(ResultDetail, '/api/detail')
# consumer
threads = []
for i in range(5):
threads.append(threading.Thread(target=consumer, args=()))
for i in threads:
i.setDaemon(daemonic=True)
i.start()
try:
global running_port, running_host
running_host = host if host != '0.0.0.0' else '127.0.0.1'
running_port = port
app.run(debug=debug, host=host, port=int(port), threaded=True, processes=1)
except socket.error as v:
if v.errno == errno.EACCES:
logger.critical('[{err}] must root permission for start API Server!'.format(err=v.strerror))
exit()
else:
logger.critical('{msg}'.format(msg=v.strerror))
logger.info('API Server start success')
|
base.py | import queue
import threading
import time
import requests
from requests.exceptions import ProxyError
from ..client import InstagramClient
from ..web import get_instagram_id, get_user_info
from ..exceptions import InstagramException
CONNECTION_MAX_ATTEMPTS = 100
class Actions:
followers = 'followers'
followings = 'followings'
actions = {
followers: InstagramClient.get_followers,
followings: InstagramClient.get_followings,
}
def get_users(username, password, victim_username, proxies=None, relation=Actions.followers):
input_queue = queue.Queue()
output_queue = queue.Queue()
proxies = proxies or [None]
workers_count = len(proxies)
class NoResponseMarker:
pass
def clean_queue(q):
with q.mutex:
q.queue.clear()
q.all_tasks_done.notify_all()
q.unfinished_tasks = 0
def queue_filler():
try:
sleep_time = 10 # Seconds
victim_id = get_instagram_id(victim_username)
insta_client = InstagramClient(username, password)
insta_client.login()
for user_pack in Actions.actions[relation](insta_client, victim_id):
for user_data in user_pack:
input_queue.put(user_data)
time.sleep(sleep_time)
except BaseException as exc:
clean_queue(output_queue)
output_queue.put(exc)
raise
finally:
list(map(lambda ii: input_queue.put(None), range(workers_count)))
def worker(proxy=None):
try:
while True:
user = input_queue.get()
if user is None:
break
attempts = 0
while True:
attempts += 1
try:
info = get_user_info(user['username'], proxy=proxy)
if info is None:
info = NoResponseMarker()
output_queue.put(info)
except (requests.exceptions.RequestException, InstagramException):
time.sleep(float(attempts) / 2)
if attempts >= CONNECTION_MAX_ATTEMPTS:
raise
else:
break
input_queue.task_done()
except BaseException as exc:
clean_queue(output_queue)
output_queue.put(exc)
raise
finally:
output_queue.put(None)
for proxy_settings in proxies:
t = threading.Thread(target=worker, args=(proxy_settings, ))
t.setDaemon(True)
t.start()
filler = threading.Thread(target=queue_filler)
filler.setDaemon(True)
filler.start()
active_threads_cnt = workers_count
while active_threads_cnt > 0:
user_info = output_queue.get()
if user_info is None:
active_threads_cnt -= 1
elif isinstance(user_info, NoResponseMarker):
continue
elif isinstance(user_info, BaseException):
raise user_info
else:
yield user_info
|
serve.py | # -*- coding: utf-8 -*-
from __future__ import print_function
import abc
import argparse
import json
import logging
import os
import platform
import signal
import socket
import sys
import threading
import time
import traceback
from six.moves import urllib
import uuid
from collections import defaultdict, OrderedDict
from itertools import chain, product
from multiprocessing import Process, Event
from localpaths import repo_root
from six.moves import reload_module
from manifest.sourcefile import read_script_metadata, js_meta_re, parse_variants
from wptserve import server as wptserve, handlers
from wptserve import stash
from wptserve import config
from wptserve.logger import set_logger
from wptserve.handlers import filesystem_path, wrap_pipeline
from wptserve.utils import get_port, HTTPException, http2_compatible
from mod_pywebsocket import standalone as pywebsocket
EDIT_HOSTS_HELP = ("Please ensure all the necessary WPT subdomains "
"are mapped to a loopback device in /etc/hosts. "
"See https://web-platform-tests.org/running-tests/from-local-system.html#system-setup "
"for instructions.")
def replace_end(s, old, new):
"""
Given a string `s` that ends with `old`, replace that occurrence of `old`
with `new`.
"""
assert s.endswith(old)
return s[:-len(old)] + new
def domains_are_distinct(a, b):
a_parts = a.split(".")
b_parts = b.split(".")
min_length = min(len(a_parts), len(b_parts))
slice_index = -1 * min_length
return a_parts[slice_index:] != b_parts[slice_index:]
class WrapperHandler(object):
__meta__ = abc.ABCMeta
headers = []
def __init__(self, base_path=None, url_base="/"):
self.base_path = base_path
self.url_base = url_base
self.handler = handlers.handler(self.handle_request)
def __call__(self, request, response):
self.handler(request, response)
def handle_request(self, request, response):
for header_name, header_value in self.headers:
response.headers.set(header_name, header_value)
self.check_exposure(request)
path = self._get_path(request.url_parts.path, True)
query = request.url_parts.query
if query:
query = "?" + query
meta = "\n".join(self._get_meta(request))
script = "\n".join(self._get_script(request))
response.content = self.wrapper % {"meta": meta, "script": script, "path": path, "query": query}
wrap_pipeline(path, request, response)
def _get_path(self, path, resource_path):
"""Convert the path from an incoming request into a path corresponding to an "unwrapped"
resource e.g. the file on disk that will be loaded in the wrapper.
:param path: Path from the HTTP request
:param resource_path: Boolean used to control whether to get the path for the resource that
this wrapper will load or the associated file on disk.
Typically these are the same but may differ when there are multiple
layers of wrapping e.g. for a .any.worker.html input the underlying disk file is
.any.js but the top level html file loads a resource with a
.any.worker.js extension, which itself loads the .any.js file.
If True return the path to the resource that the wrapper will load,
otherwise return the path to the underlying file on disk."""
for item in self.path_replace:
if len(item) == 2:
src, dest = item
else:
assert len(item) == 3
src = item[0]
dest = item[2 if resource_path else 1]
if path.endswith(src):
path = replace_end(path, src, dest)
return path
def _get_metadata(self, request):
"""Get an iterator over script metadata based on // META comments in the
associated js file.
:param request: The Request being processed.
"""
path = self._get_path(filesystem_path(self.base_path, request, self.url_base), False)
try:
with open(path, "rb") as f:
for key, value in read_script_metadata(f, js_meta_re):
yield key, value
except IOError:
raise HTTPException(404)
def _get_meta(self, request):
"""Get an iterator over strings to inject into the wrapper document
based on // META comments in the associated js file.
:param request: The Request being processed.
"""
for key, value in self._get_metadata(request):
replacement = self._meta_replacement(key, value)
if replacement:
yield replacement
def _get_script(self, request):
"""Get an iterator over strings to inject into the wrapper document
based on // META comments in the associated js file.
:param request: The Request being processed.
"""
for key, value in self._get_metadata(request):
replacement = self._script_replacement(key, value)
if replacement:
yield replacement
@abc.abstractproperty
def path_replace(self):
# A list containing a mix of 2 item tuples with (input suffix, output suffix)
# and 3-item tuples with (input suffix, filesystem suffix, resource suffix)
# for the case where we want a different path in the generated resource to
# the actual path on the filesystem (e.g. when there is another handler
# that will wrap the file).
return None
@abc.abstractproperty
def wrapper(self):
# String template with variables path and meta for wrapper document
return None
@abc.abstractmethod
def _meta_replacement(self, key, value):
# Get the string to insert into the wrapper document, given
# a specific metadata key: value pair.
pass
@abc.abstractmethod
def check_exposure(self, request):
# Raise an exception if this handler shouldn't be exposed after all.
pass
class HtmlWrapperHandler(WrapperHandler):
global_type = None
headers = [('Content-Type', 'text/html')]
def check_exposure(self, request):
if self.global_type:
globals = b""
for (key, value) in self._get_metadata(request):
if key == b"global":
globals = value
break
if self.global_type not in parse_variants(globals):
raise HTTPException(404, "This test cannot be loaded in %s mode" %
self.global_type)
def _meta_replacement(self, key, value):
if key == b"timeout":
if value == b"long":
return '<meta name="timeout" content="long">'
if key == b"title":
value = value.decode('utf-8').replace("&", "&").replace("<", "<")
return '<title>%s</title>' % value
return None
def _script_replacement(self, key, value):
if key == b"script":
attribute = value.decode('utf-8').replace("&", "&").replace('"', """)
return '<script src="%s"></script>' % attribute
return None
class WorkersHandler(HtmlWrapperHandler):
global_type = b"dedicatedworker"
path_replace = [(".any.worker.html", ".any.js", ".any.worker.js"),
(".worker.html", ".worker.js")]
wrapper = """<!doctype html>
<meta charset=utf-8>
%(meta)s
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<div id=log></div>
<script>
fetch_tests_from_worker(new Worker("%(path)s%(query)s"));
</script>
"""
class WindowHandler(HtmlWrapperHandler):
path_replace = [(".window.html", ".window.js")]
wrapper = """<!doctype html>
<meta charset=utf-8>
%(meta)s
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
%(script)s
<div id=log></div>
<script src="%(path)s"></script>
"""
class AnyHtmlHandler(HtmlWrapperHandler):
global_type = b"window"
path_replace = [(".any.html", ".any.js")]
wrapper = """<!doctype html>
<meta charset=utf-8>
%(meta)s
<script>
self.GLOBAL = {
isWindow: function() { return true; },
isWorker: function() { return false; },
};
</script>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
%(script)s
<div id=log></div>
<script src="%(path)s"></script>
"""
class SharedWorkersHandler(HtmlWrapperHandler):
global_type = b"sharedworker"
path_replace = [(".any.sharedworker.html", ".any.js", ".any.worker.js")]
wrapper = """<!doctype html>
<meta charset=utf-8>
%(meta)s
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<div id=log></div>
<script>
fetch_tests_from_worker(new SharedWorker("%(path)s%(query)s"));
</script>
"""
class ServiceWorkersHandler(HtmlWrapperHandler):
global_type = b"serviceworker"
path_replace = [(".any.serviceworker.html", ".any.js", ".any.worker.js")]
wrapper = """<!doctype html>
<meta charset=utf-8>
%(meta)s
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<div id=log></div>
<script>
(async function() {
const scope = 'does/not/exist';
let reg = await navigator.serviceWorker.getRegistration(scope);
if (reg) await reg.unregister();
reg = await navigator.serviceWorker.register("%(path)s%(query)s", {scope});
fetch_tests_from_worker(reg.installing);
})();
</script>
"""
class AnyWorkerHandler(WrapperHandler):
headers = [('Content-Type', 'text/javascript')]
path_replace = [(".any.worker.js", ".any.js")]
wrapper = """%(meta)s
self.GLOBAL = {
isWindow: function() { return false; },
isWorker: function() { return true; },
};
importScripts("/resources/testharness.js");
%(script)s
importScripts("%(path)s");
done();
"""
def _meta_replacement(self, key, value):
return None
def _script_replacement(self, key, value):
if key == b"script":
attribute = value.decode('utf-8').replace("\\", "\\\\").replace('"', '\\"')
return 'importScripts("%s")' % attribute
if key == b"title":
value = value.decode('utf-8').replace("\\", "\\\\").replace('"', '\\"')
return 'self.META_TITLE = "%s";' % value
return None
rewrites = [("GET", "/resources/WebIDLParser.js", "/resources/webidl2/lib/webidl2.js")]
class RoutesBuilder(object):
def __init__(self):
self.forbidden_override = [("GET", "/tools/runner/*", handlers.file_handler),
("POST", "/tools/runner/update_manifest.py",
handlers.python_script_handler)]
self.forbidden = [("*", "/_certs/*", handlers.ErrorHandler(404)),
("*", "/tools/*", handlers.ErrorHandler(404)),
("*", "{spec}/tools/*", handlers.ErrorHandler(404))]
self.extra = []
self.mountpoint_routes = OrderedDict()
self.add_mount_point("/", None)
def get_routes(self):
routes = self.forbidden_override + self.forbidden + self.extra
# Using reversed here means that mount points that are added later
# get higher priority. This makes sense since / is typically added
# first.
for item in reversed(self.mountpoint_routes.values()):
routes.extend(item)
return routes
def add_handler(self, method, route, handler):
self.extra.append((str(method), str(route), handler))
def add_static(self, path, format_args, content_type, route, headers=None):
if headers is None:
headers = {}
handler = handlers.StaticHandler(path, format_args, content_type, **headers)
self.add_handler("GET", str(route), handler)
def add_mount_point(self, url_base, path):
url_base = "/%s/" % url_base.strip("/") if url_base != "/" else "/"
self.mountpoint_routes[url_base] = []
routes = [
("GET", "*.worker.html", WorkersHandler),
("GET", "*.window.html", WindowHandler),
("GET", "*.any.html", AnyHtmlHandler),
("GET", "*.any.sharedworker.html", SharedWorkersHandler),
("GET", "*.any.serviceworker.html", ServiceWorkersHandler),
("GET", "*.any.worker.js", AnyWorkerHandler),
("GET", "*.asis", handlers.AsIsHandler),
("GET", "/.well-known/origin-policy", handlers.PythonScriptHandler),
("*", "*.py", handlers.PythonScriptHandler),
("GET", "*", handlers.FileHandler)
]
for (method, suffix, handler_cls) in routes:
self.mountpoint_routes[url_base].append(
(method,
"%s%s" % (url_base if url_base != "/" else "", suffix),
handler_cls(base_path=path, url_base=url_base)))
def add_file_mount_point(self, file_url, base_path):
assert file_url.startswith("/")
url_base = file_url[0:file_url.rfind("/") + 1]
self.mountpoint_routes[file_url] = [("GET", file_url, handlers.FileHandler(base_path=base_path, url_base=url_base))]
def build_routes(aliases):
builder = RoutesBuilder()
for alias in aliases:
url = alias["url-path"]
directory = alias["local-dir"]
if not url.startswith("/") or len(directory) == 0:
logger.error("\"url-path\" value must start with '/'.")
continue
if url.endswith("/"):
builder.add_mount_point(url, directory)
else:
builder.add_file_mount_point(url, directory)
return builder.get_routes()
class ServerProc(object):
def __init__(self, scheme=None):
self.proc = None
self.daemon = None
self.stop = Event()
self.scheme = scheme
def start(self, init_func, host, port, paths, routes, bind_address, config, **kwargs):
self.proc = Process(target=self.create_daemon,
args=(init_func, host, port, paths, routes, bind_address,
config),
name='%s on port %s' % (self.scheme, port),
kwargs=kwargs)
self.proc.daemon = True
self.proc.start()
def create_daemon(self, init_func, host, port, paths, routes, bind_address,
config, **kwargs):
try:
self.daemon = init_func(host, port, paths, routes, bind_address, config, **kwargs)
except socket.error:
print("Socket error on port %s" % port, file=sys.stderr)
raise
except Exception:
print(traceback.format_exc(), file=sys.stderr)
raise
if self.daemon:
try:
self.daemon.start(block=False)
try:
self.stop.wait()
except KeyboardInterrupt:
pass
except Exception:
print(traceback.format_exc(), file=sys.stderr)
raise
def wait(self):
self.stop.set()
self.proc.join()
def kill(self):
self.stop.set()
self.proc.terminate()
self.proc.join()
def is_alive(self):
return self.proc.is_alive()
def check_subdomains(config):
paths = config.paths
bind_address = config.bind_address
aliases = config.aliases
host = config.server_host
port = get_port()
logger.debug("Going to use port %d to check subdomains" % port)
wrapper = ServerProc()
wrapper.start(start_http_server, host, port, paths, build_routes(aliases),
bind_address, config)
url = "http://{}:{}/".format(host, port)
connected = False
for i in range(10):
try:
urllib.request.urlopen(url)
connected = True
break
except urllib.error.URLError:
time.sleep(1)
if not connected:
logger.critical("Failed to connect to test server "
"on {}. {}".format(url, EDIT_HOSTS_HELP))
sys.exit(1)
for domain in config.domains_set:
if domain == host:
continue
try:
urllib.request.urlopen("http://%s:%d/" % (domain, port))
except Exception:
logger.critical("Failed probing domain {}. {}".format(domain, EDIT_HOSTS_HELP))
sys.exit(1)
wrapper.wait()
def make_hosts_file(config, host):
rv = []
for domain in config.domains_set:
rv.append("%s\t%s\n" % (host, domain))
# Windows interpets the IP address 0.0.0.0 as non-existent, making it an
# appropriate alias for non-existent hosts. However, UNIX-like systems
# interpret the same address to mean any IP address, which is inappropraite
# for this context. These systems do not reserve any value for this
# purpose, so the inavailability of the domains must be taken for granted.
#
# https://github.com/web-platform-tests/wpt/issues/10560
if platform.uname()[0] == "Windows":
for not_domain in config.not_domains_set:
rv.append("0.0.0.0\t%s\n" % not_domain)
return "".join(rv)
def start_servers(host, ports, paths, routes, bind_address, config, **kwargs):
servers = defaultdict(list)
for scheme, ports in ports.items():
assert len(ports) == {"http": 2}.get(scheme, 1)
# If trying to start HTTP/2.0 server, check compatibility
if scheme == 'h2' and not http2_compatible():
logger.error('Cannot start HTTP/2.0 server as the environment is not compatible. ' +
'Requires Python 2.7.10+ (< 3.0) and OpenSSL 1.0.2+')
continue
for port in ports:
if port is None:
continue
init_func = {"http": start_http_server,
"https": start_https_server,
"h2": start_http2_server,
"ws": start_ws_server,
"wss": start_wss_server}[scheme]
server_proc = ServerProc(scheme=scheme)
server_proc.start(init_func, host, port, paths, routes, bind_address,
config, **kwargs)
servers[scheme].append((port, server_proc))
return servers
def start_http_server(host, port, paths, routes, bind_address, config, **kwargs):
return wptserve.WebTestHttpd(host=host,
port=port,
doc_root=paths["doc_root"],
routes=routes,
rewrites=rewrites,
bind_address=bind_address,
config=config,
use_ssl=False,
key_file=None,
certificate=None,
latency=kwargs.get("latency"))
def start_https_server(host, port, paths, routes, bind_address, config, **kwargs):
return wptserve.WebTestHttpd(host=host,
port=port,
doc_root=paths["doc_root"],
routes=routes,
rewrites=rewrites,
bind_address=bind_address,
config=config,
use_ssl=True,
key_file=config.ssl_config["key_path"],
certificate=config.ssl_config["cert_path"],
encrypt_after_connect=config.ssl_config["encrypt_after_connect"],
latency=kwargs.get("latency"))
def start_http2_server(host, port, paths, routes, bind_address, config, **kwargs):
return wptserve.WebTestHttpd(host=host,
port=port,
handler_cls=wptserve.Http2WebTestRequestHandler,
doc_root=paths["doc_root"],
routes=routes,
rewrites=rewrites,
bind_address=bind_address,
config=config,
use_ssl=True,
key_file=config.ssl_config["key_path"],
certificate=config.ssl_config["cert_path"],
encrypt_after_connect=config.ssl_config["encrypt_after_connect"],
latency=kwargs.get("latency"),
http2=True)
class WebSocketDaemon(object):
def __init__(self, host, port, doc_root, handlers_root, bind_address, ssl_config):
self.host = host
cmd_args = ["-p", port,
"-d", doc_root,
"-w", handlers_root]
if ssl_config is not None:
cmd_args += ["--tls",
"--private-key", ssl_config["key_path"],
"--certificate", ssl_config["cert_path"]]
if (bind_address):
cmd_args = ["-H", host] + cmd_args
opts, args = pywebsocket._parse_args_and_config(cmd_args)
opts.cgi_directories = []
opts.is_executable_method = None
self.server = pywebsocket.WebSocketServer(opts)
ports = [item[0].getsockname()[1] for item in self.server._sockets]
assert all(item == ports[0] for item in ports)
self.port = ports[0]
self.started = False
self.server_thread = None
def start(self, block=False):
self.started = True
if block:
self.server.serve_forever()
else:
self.server_thread = threading.Thread(target=self.server.serve_forever)
self.server_thread.setDaemon(True) # don't hang on exit
self.server_thread.start()
def stop(self):
"""
Stops the server.
If the server is not running, this method has no effect.
"""
if self.started:
try:
self.server.shutdown()
self.server.server_close()
self.server_thread.join()
self.server_thread = None
except AttributeError:
pass
self.started = False
self.server = None
def release_mozlog_lock():
try:
from mozlog.structuredlog import StructuredLogger
try:
StructuredLogger._lock.release()
except threading.ThreadError:
pass
except ImportError:
pass
def start_ws_server(host, port, paths, routes, bind_address, config, **kwargs):
# Ensure that when we start this in a new process we have the global lock
# in the logging module unlocked
reload_module(logging)
release_mozlog_lock()
return WebSocketDaemon(host,
str(port),
repo_root,
config.paths["ws_doc_root"],
bind_address,
ssl_config=None)
def start_wss_server(host, port, paths, routes, bind_address, config, **kwargs):
# Ensure that when we start this in a new process we have the global lock
# in the logging module unlocked
reload_module(logging)
release_mozlog_lock()
return WebSocketDaemon(host,
str(port),
repo_root,
config.paths["ws_doc_root"],
bind_address,
config.ssl_config)
def start(config, routes, **kwargs):
host = config["server_host"]
ports = config.ports
paths = config.paths
bind_address = config["bind_address"]
logger.debug("Using ports: %r" % ports)
servers = start_servers(host, ports, paths, routes, bind_address, config, **kwargs)
return servers
def iter_procs(servers):
for servers in servers.values():
for port, server in servers:
yield server.proc
def build_config(override_path=None, **kwargs):
rv = ConfigBuilder()
enable_http2 = kwargs.get("h2")
if enable_http2 is None:
enable_http2 = True
if enable_http2:
rv._default["ports"]["h2"] = [9000]
if override_path and os.path.exists(override_path):
with open(override_path) as f:
override_obj = json.load(f)
rv.update(override_obj)
if kwargs.get("config_path"):
other_path = os.path.abspath(os.path.expanduser(kwargs.get("config_path")))
if os.path.exists(other_path):
with open(other_path) as f:
override_obj = json.load(f)
rv.update(override_obj)
else:
raise ValueError("Config path %s does not exist" % other_path)
overriding_path_args = [("doc_root", "Document root"),
("ws_doc_root", "WebSockets document root")]
for key, title in overriding_path_args:
value = kwargs.get(key)
if value is None:
continue
value = os.path.abspath(os.path.expanduser(value))
if not os.path.exists(value):
raise ValueError("%s path %s does not exist" % (title, value))
setattr(rv, key, value)
return rv
def _make_subdomains_product(s, depth=2):
return {u".".join(x) for x in chain(*(product(s, repeat=i) for i in range(1, depth+1)))}
def _make_origin_policy_subdomains(limit):
return {u"op%d" % x for x in range(1,limit+1)}
_subdomains = {u"www",
u"www1",
u"www2",
u"ๅคฉๆฐใฎ่ฏใๆฅ",
u"รฉlรจve"}
_not_subdomains = {u"nonexistent"}
_subdomains = _make_subdomains_product(_subdomains)
# Origin policy subdomains need to not be reused by any other tests, since origin policies have
# origin-wide impacts like installing a CSP or Feature Policy that could interfere with features
# under test.
# See https://github.com/web-platform-tests/rfcs/pull/44.
_subdomains |= _make_origin_policy_subdomains(99)
_not_subdomains = _make_subdomains_product(_not_subdomains)
class ConfigBuilder(config.ConfigBuilder):
"""serve config
This subclasses wptserve.config.ConfigBuilder to add serve config options.
"""
_default = {
"browser_host": "web-platform.test",
"alternate_hosts": {
"alt": "not-web-platform.test"
},
"doc_root": repo_root,
"ws_doc_root": os.path.join(repo_root, "websockets", "handlers"),
"server_host": None,
"ports": {
"http": [8000, "auto"],
"https": [8443],
"ws": ["auto"],
"wss": ["auto"],
},
"check_subdomains": True,
"log_level": "debug",
"bind_address": True,
"ssl": {
"type": "pregenerated",
"encrypt_after_connect": False,
"openssl": {
"openssl_binary": "openssl",
"base_path": "_certs",
"password": "web-platform-tests",
"force_regenerate": False,
"duration": 30,
"base_conf_path": None
},
"pregenerated": {
"host_key_path": os.path.join(repo_root, "tools", "certs", "web-platform.test.key"),
"host_cert_path": os.path.join(repo_root, "tools", "certs", "web-platform.test.pem")
},
"none": {}
},
"aliases": []
}
computed_properties = ["ws_doc_root"] + config.ConfigBuilder.computed_properties
def __init__(self, *args, **kwargs):
if "subdomains" not in kwargs:
kwargs["subdomains"] = _subdomains
if "not_subdomains" not in kwargs:
kwargs["not_subdomains"] = _not_subdomains
super(ConfigBuilder, self).__init__(
*args,
**kwargs
)
with self as c:
browser_host = c.get("browser_host")
alternate_host = c.get("alternate_hosts", {}).get("alt")
if not domains_are_distinct(browser_host, alternate_host):
raise ValueError(
"Alternate host must be distinct from browser host"
)
def _get_ws_doc_root(self, data):
if data["ws_doc_root"] is not None:
return data["ws_doc_root"]
else:
return os.path.join(data["doc_root"], "websockets", "handlers")
def ws_doc_root(self, v):
self._ws_doc_root = v
ws_doc_root = property(None, ws_doc_root)
def _get_paths(self, data):
rv = super(ConfigBuilder, self)._get_paths(data)
rv["ws_doc_root"] = data["ws_doc_root"]
return rv
def get_parser():
parser = argparse.ArgumentParser()
parser.add_argument("--latency", type=int,
help="Artificial latency to add before sending http responses, in ms")
parser.add_argument("--config", action="store", dest="config_path",
help="Path to external config file")
parser.add_argument("--doc_root", action="store", dest="doc_root",
help="Path to document root. Overrides config.")
parser.add_argument("--ws_doc_root", action="store", dest="ws_doc_root",
help="Path to WebSockets document root. Overrides config.")
parser.add_argument("--alias_file", action="store", dest="alias_file",
help="File with entries for aliases/multiple doc roots. In form of `/ALIAS_NAME/, DOC_ROOT\\n`")
parser.add_argument("--h2", action="store_true", dest="h2", default=None,
help=argparse.SUPPRESS)
parser.add_argument("--no-h2", action="store_false", dest="h2", default=None,
help="Disable the HTTP/2.0 server")
return parser
def run(**kwargs):
received_signal = threading.Event()
with build_config(os.path.join(repo_root, "config.json"),
**kwargs) as config:
global logger
logger = config.logger
set_logger(logger)
# Configure the root logger to cover third-party libraries.
logging.getLogger().setLevel(config.log_level)
def handle_signal(signum, frame):
logger.debug("Received signal %s. Shutting down.", signum)
received_signal.set()
bind_address = config["bind_address"]
if kwargs.get("alias_file"):
with open(kwargs["alias_file"], 'r') as alias_file:
for line in alias_file:
alias, doc_root = [x.strip() for x in line.split(',')]
config["aliases"].append({
'url-path': alias,
'local-dir': doc_root,
})
if config["check_subdomains"]:
check_subdomains(config)
stash_address = None
if bind_address:
stash_address = (config.server_host, get_port(""))
logger.debug("Going to use port %d for stash" % stash_address[1])
with stash.StashServer(stash_address, authkey=str(uuid.uuid4())):
servers = start(config, build_routes(config["aliases"]), **kwargs)
signal.signal(signal.SIGTERM, handle_signal)
signal.signal(signal.SIGINT, handle_signal)
while all(item.is_alive() for item in iter_procs(servers)) and not received_signal.is_set():
for item in iter_procs(servers):
item.join(1)
exited = [item for item in iter_procs(servers) if not item.is_alive()]
subject = "subprocess" if len(exited) == 1 else "subprocesses"
logger.info("%s %s exited:" % (len(exited), subject))
for item in iter_procs(servers):
logger.info("Status of %s:\t%s" % (item.name, "running" if item.is_alive() else "not running"))
def main():
kwargs = vars(get_parser().parse_args())
return run(**kwargs)
|
Hiwin_RT605_ArmCommand_Socket_20190627160850.py | #!/usr/bin/env python3
# license removed for brevity
import rospy
import os
import numpy as np
from std_msgs.msg import String
from ROS_Socket.srv import *
from ROS_Socket.msg import *
import math
import enum
pos_feedback_times = 0
mode_feedback_times = 0
msg_feedback = 1
#ๆฅๆถ็ญ็ฅ็ซฏๅฝไปค ็จSocketๅณ่ผธ่ณๆงๅถ็ซฏ้ป่
ฆ
import socket
##ๅคๅท่กๅบ
import threading
import time
import sys
import matplotlib as plot
import HiwinRA605_socket_TCPcmd as TCP
import HiwinRA605_socket_Taskcmd as Taskcmd
Socket = 0
data = '0' #่จญๅฎๅณ่ผธ่ณๆๅๅงๅผ
Arm_feedback = 1 #ๅ่จญๆ่ๅฟ็ข
state_feedback = 0
NAME = 'socket_server'
client_response = 0 #ๅๅณๆฌกๆธๅๅงๅผ
point_data_flag = False
arm_mode_flag = False
speed_mode_flag = False
Socket_sent_flag = False
##------------class pos-------
class point():
def __init__(self, x, y, z, pitch, roll, yaw):
self.x = x
self.y = y
self.z = z
self.pitch = pitch
self.roll = roll
self.yaw = yaw
pos = point(0,36.8,11.35,-90,0,0)
##------------class socket_cmd---------
class socket_cmd():
def __init__(self, grip, setvel, ra, delay, setboth, action,Speedmode):
self.grip = grip
self.setvel = setvel
self.ra = ra
self.delay = delay
self.setboth = setboth
self.action = action
self.Speedmode = Speedmode
##-----------switch define------------##
class switch(object):
def __init__(self, value):
self.value = value
self.fall = False
def __iter__(self):
"""Return the match method once, then stop"""
yield self.match
raise StopIteration
def match(self, *args):
"""Indicate whether or not to enter a case suite"""
if self.fall or not args:
return True
elif self.value in args: # changed for v1.5, see below
self.fall = True
return True
else:
return False
##-----------client feedback arm state----------
class state_feedback():
def _init_(self,ArmState,SentFlag):
self.ArmState = ArmState
self.SentFlag = SentFlag
# def socket_client_arm_state(Arm_state):
# global state_feedback
# rospy.wait_for_service('arm_state')
# try:
# Arm_state_client = rospy.ServiceProxy('arm_state', arm_state)
# state_feedback = Arm_state_client(Arm_state)
# #pos_feedback_times = pos_feedback.response
# return state_feedback
# except rospy.ServiceException as e:
# print ("Service call failed: %s"%e)
# ##----------socket sent data flag-------------
# def socket_client_sent_flag(Sent_flag):
# global sent_feedback
# rospy.wait_for_service('sent_flag')
# try:
# Sent_flag_client = rospy.ServiceProxy('sent_flag', sent_flag)
# sent_feedback = Sent_flag_client(Sent_flag)
# #pos_feedback_times = pos_feedback.response
# return sent_feedback
# except rospy.ServiceException as e:
# print ("Service call failed: %s"%e)
##-----------client feedback arm state end----------
##------------server ็ซฏ-------
def point_data(x,y,z,pitch,roll,yaw): ##ๆฅๆถ็ญ็ฅ็ซฏๅณ้ไฝๅงฟ่ณๆ
global client_response,point_data_flag
pos.x = x
pos.y = y
pos.z = z
pos.pitch = pitch
pos.roll = roll
pos.yaw = yaw
point_data_flag = True
##----------Arm Mode-------------###
def Arm_Mode(action,grip,ra,setvel,setboth): ##ๆฅๆถ็ญ็ฅ็ซฏๅณ้ๆ่ๆจกๅผ่ณๆ
global arm_mode_flag
socket_cmd.action = action
socket_cmd.grip = grip
socket_cmd.ra = ra
socket_cmd.setvel = setvel
socket_cmd.setboth = setboth
arm_mode_flag = True
Socket_command()
##-------Arm Speed Mode------------###
def Speed_Mode(speedmode): ##ๆฅๆถ็ญ็ฅ็ซฏๅณ้ๆ่ๆจกๅผ่ณๆ
global speed_mode_flag
socket_cmd.Speedmode = speedmode
speed_mode_flag = True
# def Grip_Mode(req): ##ๆฅๆถ็ญ็ฅ็ซฏๅณ้ๅคพ็ชๅไฝ่ณๆ
# socket_cmd.grip = int('%s'%req.grip)
# return(1)
def socket_server(): ##ๅตๅปบServer node
rospy.init_node(NAME)
# a = rospy.Service('arm_mode',arm_mode, Arm_Mode) ##server arm mode data
# s = rospy.Service('arm_pos',arm_data, point_data) ##server arm point data
# b = rospy.Service('speed_mode',speed_mode, Speed_Mode) ##server speed mode data
#c = rospy.Service('grip_mode',grip_mode, Grip_Mode) ##server grip mode data
print ("Ready to connect")
rospy.spin() ## spin one
##------------server ็ซฏ end-------
##----------socket ๅฐๅ
ๅณ่ผธ--------------##
##---------------socket ๅณ่ผธๆ่ๅฝไปค-----------------
def Socket_command():
global arm_mode_flag,speed_mode_flag,point_data_flag
if arm_mode_flag == True:
arm_mode_flag = False
for case in switch(socket_cmd.action):
#-------PtP Mode--------
if case(Taskcmd.Action_Type.PtoP):
for case in switch(socket_cmd.setboth):
if case(Taskcmd.Ctrl_Mode.CTRL_POS):
data = TCP.SetPtoP(socket_cmd.grip,Taskcmd.RA.ABS,Taskcmd.Ctrl_Mode.CTRL_POS,pos.x,pos.y,pos.z,pos.pitch,pos.roll,pos.yaw,socket_cmd.setvel)
break
if case(Taskcmd.Ctrl_Mode.CTRL_EULER):
data = TCP.SetPtoP(socket_cmd.grip,Taskcmd.RA.ABS,Taskcmd.Ctrl_Mode.CTRL_EULER,pos.x,pos.y,pos.z,pos.pitch,pos.roll,pos.yaw,socket_cmd.setvel)
break
if case(Taskcmd.Ctrl_Mode.CTRL_BOTH):
data = TCP.SetPtoP(socket_cmd.grip,Taskcmd.RA.ABS,Taskcmd.Ctrl_Mode.CTRL_BOTH,pos.x,pos.y,pos.z,pos.pitch,pos.roll,pos.yaw,socket_cmd.setvel)
break
break
#-------Line Mode--------
if case(Taskcmd.Action_Type.Line):
for case in switch(socket_cmd.setboth):
if case(Taskcmd.Ctrl_Mode.CTRL_POS):
data = TCP.SetLine(socket_cmd.grip,Taskcmd.RA.ABS,Taskcmd.Ctrl_Mode.CTRL_POS,pos.x,pos.y,pos.z,pos.pitch,pos.roll,pos.yaw,socket_cmd.setvel)
break
if case(Taskcmd.Ctrl_Mode.CTRL_EULER):
data = TCP.SetLine(socket_cmd.grip,Taskcmd.RA.ABS,Taskcmd.Ctrl_Mode.CTRL_EULER,pos.x,pos.y,pos.z,pos.pitch,pos.roll,pos.yaw,socket_cmd.setvel )
break
if case(Taskcmd.Ctrl_Mode.CTRL_BOTH):
data = TCP.SetLine(socket_cmd.grip,Taskcmd.RA.ABS,Taskcmd.Ctrl_Mode.CTRL_BOTH,pos.x,pos.y,pos.z,pos.pitch,pos.roll,pos.yaw,socket_cmd.setvel )
break
break
#-------่จญๅฎๆ่้ๅบฆ--------
if case(Taskcmd.Action_Type.SetVel):
data = TCP.SetVel(socket_cmd.grip, socket_cmd.setvel)
break
#-------่จญๅฎๆ่Delayๆ้--------
if case(Taskcmd.Action_Type.Delay):
data = TCP.SetDelay(socket_cmd.grip,0)
break
#-------่จญๅฎๆ่ๆฅ้&ๅฎๅ
จๆจกๅผ--------
if case(Taskcmd.Action_Type.Mode):
data = TCP.Set_SpeedMode(socket_cmd.grip,socket_cmd.Speedmode)
break
socket_cmd.action= 5 ##ๅๆๅๅงmode็ๆ
Socket.send(data.encode('utf-8'))#socketๅณ้for python to translate str
# Socket_sent_flag = True
# socket_client_sent_flag(Socket_sent_flag)
##-----------socket client--------
def socket_client():
global Socket,Arm_feedback,data,Socket_sent_flag
try:
Socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Socket.connect(('192.168.0.1', 8080))#iclab 5 ๏ผ iclab hiwin
#s.connect(('192.168.1.102', 8080))#iclab computerx
except socket.error as msg:
print(msg)
sys.exit(1)
print('Connection has been successful')
print(Socket.recv(1024))
while 1:
feedback_str = Socket.recv(1024)
#ๆ่็ซฏๅณ้ๆ่็ๆ
if str(feedback_str[2]) == '48':# F ๆ่็บReady็ๆ
ๆบๅๆฅๆถไธไธๅ้ๅๆไปค
Arm_feedback = 0
socket_client_arm_state(Arm_feedback)
#print("isbusy false")
if str(feedback_str[2]) == '49':# T ๆ่็บๅฟ็ข็ๆ
็กๆณๅท่กไธไธๅ้ๅๆไปค
Arm_feedback = 1
socket_client_arm_state(Arm_feedback)
#print("isbusy true")
if str(feedback_str[2]) == '54':# 6 ็ญ็ฅๅฎๆ
Arm_feedback = 6
socket_client_arm_state(Arm_feedback)
print("shutdown")
#็ขบ่ชๅณ้ๆๆจ
if str(feedback_str[4]) == '48':#ๅๅณ0 false
#print(2222222222)
Socket_sent_flag = False
socket_client_sent_flag(Socket_sent_flag)
if str(feedback_str[4]) == '49':#ๅๅณ1 true
#print(111111111111)
Socket_sent_flag = True
socket_client_sent_flag(Socket_sent_flag)
##---------------socket ๅณ่ผธๆ่ๅฝไปค end-----------------
if Arm_feedback == Taskcmd.Arm_feedback_Type.shutdown:
break
rospy.on_shutdown(myhook)
Socket.close()
##-----------socket client end--------
##-------------socket ๅฐๅ
ๅณ่ผธ end--------------##
## ๅคๅท่ก็ท
def thread_test():
socket_client()
## ๅคๅท่กๅบ end
def myhook():
print ("shutdown time!")
if __name__ == '__main__':
socket_cmd.action = 5##ๅๆๅๅงmode็ๆ
t = threading.Thread(target=thread_test)
t.start() # ้ๅๅคๅท่ก็ท
socket_server()
t.join() |
copy_.py | import os
# os.environ["CUDA_VISIBLE_DEVICES"]="-1" # ใณใกใณใใขใฆใใๅคใใจGPUใ็กๅนๅ
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"]="0" #GPU
###GeForce GTX 1660 config###
from tensorflow.compat.v1 import ConfigProto
from tensorflow.compat.v1 import InteractiveSession
config = ConfigProto()
config.gpu_options.allow_growth = True
session = InteractiveSession(config=config)
from tensorflow.keras.models import load_model, Model
from tensorflow.python.compiler.tensorrt import trt_convert as trt
from utils import decode_prob, weighted_crossentropy_wrapper, \
make_overlay, calc_IoU, binarize_label, \
get_paths_in_dir, divide_image, put_image_together,\
decompose_labels, divide_image_borderless,\
put_image_together_borderless
import numpy as np
import collections
import tensorflow as tf
from pathlib import Path
from typing import Tuple, Optional
import imageio
from threading import Thread
from tqdm import tqdm
import time
from tensorflow.python.saved_model import tag_constants
from tensorflow.keras.preprocessing import image
from configuration import BaseConfig
def main32():
# load pre-trained model
weight_path = Path("/home/ubuntu/Desktop/o-semantic-segmentation-feature-batch/weights/test2/final_model.h5")
# weight_path = Path("/home/ubuntu/Desktop/o-semantic-segmentation-feature-batch/src/saved_model")
# inference_targetใฎไธญใฎใใฉใซใๅ
target_name = "0630"
target_dir_path = Path(__file__).resolve().parent.parent.joinpath("inference_target", target_name)
# assert weight_path.is_file() and target_dir_path.is_dir()
# model: Model = load_model(str(weight_path),
# custom_objects={"weighted_cross_entropy": weighted_crossentropy_wrapper([1., 60., 60.]), 'tf': tf})
# model = load_model(weight_path)
# model.save('saved_model/')
# model = tf.keras.models.load_model('saved_model/')
result_name = "0630"
result_path = Path(__file__).resolve().parent.parent.joinpath("inference_result", result_name)
# model.summary()
batch_size = 14
img_shape=(512, 2048, 3)
train_img_size=(512, 2048)
label_info = collections.OrderedDict()
label_info["background"] = (0, 0, 0)
label_info["kizu"] = (128, 0, 0)
result_path.mkdir(exist_ok=True)
image_paths = get_paths_in_dir(target_dir_path)
image_paths.sort()
# print('Converting to TF-TRT FP32...')
# conversion_params = trt.DEFAULT_TRT_CONVERSION_PARAMS._replace(precision_mode=trt.TrtPrecisionMode.FP32,
# max_workspace_size_bytes=8000000000)
# converter = trt.TrtGraphConverterV2(input_saved_model_dir=str(weight_path),
# conversion_params=conversion_params)
# converter.convert()
# converter.save(output_saved_model_dir='saved_model_TFTRT_FP32')
# print('Done Converting to TF-TRT FP32')
saved_model_loaded = tf.saved_model.load('saved_model_TFTRT_FP32', tags=[tag_constants.SERVING])
signature_keys = list(saved_model_loaded.signatures.keys())
print(signature_keys)
infer = saved_model_loaded.signatures['serving_default']
print(infer.structured_outputs)
print(infer)
# labeling = infer(x)
for target_img_path in tqdm(image_paths):
target_img = imageio.imread(str(target_img_path), as_gray=False, pilmode="RGB")
target_float_img = target_img.astype(np.float32) / 255.
divided_image =divide_image(target_float_img, train_img_size)
# x = tf.constant(divided_image)
divided_image = tf.convert_to_tensor(divided_image, dtype=tf.float32)
# print("##################################################### divided_image", x.shape)
print("##################################################### divided_image", divided_image[1])
t1 = time.time()
# inputs = {}
# inputs['input_1']=x
# results = model.predict(np.array(divided_image),batch_size=batch_size)
outputs = infer(input_1=divided_image[1:3])
# outputs['activation_81']
t2 = time.time()
elapsed_time = t2-t1
print(f"########## ็ต้ๆ้_batch{batch_size}๏ผ{elapsed_time}")
# y = put_image_together(outputs, (target_img.shape[0], target_img.shape[1]))
# for label_name, decoded_label in zip(label_info.keys(), decode_prob(binarize_label(y))):
# overlay_img = make_overlay(target_img, decoded_label, label_color='r')
# Thread(target=imageio.imwrite, args=(str(result_path / f"label_{target_img_path.stem}_{label_name}.jpg"), overlay_img), daemon=False).start()
def main16():
# load pre-trained model
# weight_path = Path("/home/ubuntu/Desktop/o-semantic-segmentation-feature-batch/weights/test2/final_model.h5")
weight_path = Path("/home/ubuntu/Desktop/o-semantic-segmentation-feature-batch/src/saved_model")
# inference_targetใฎไธญใฎใใฉใซใๅ
target_name = "0630"
target_dir_path = Path(__file__).resolve().parent.parent.parent.joinpath("inference_target", target_name)
# assert weight_path.is_file() and target_dir_path.is_dir()
# model: Model = load_model(str(weight_path),
# custom_objects={"weighted_cross_entropy": weighted_crossentropy_wrapper([1., 60., 60.]), 'tf': tf})
# model = load_model(weight_path)
# model.save('saved_model/')
# model = tf.keras.models.load_model('saved_model/')
result_name = "0630"
result_path = Path(__file__).resolve().parent.parent.parent.joinpath("inference_result", result_name)
# model.summary()
batch_size = 14
img_shape=(512, 2048, 3)
train_img_size=(512, 2048)
label_info = collections.OrderedDict()
label_info["background"] = (0, 0, 0)
label_info["kizu"] = (128, 0, 0)
result_path.mkdir(exist_ok=True)
image_paths = get_paths_in_dir(target_dir_path)
image_paths.sort()
print('Converting to TF-TRT FP16...')
conversion_params = trt.DEFAULT_TRT_CONVERSION_PARAMS._replace(
precision_mode=trt.TrtPrecisionMode.FP16,
max_workspace_size_bytes=8000000000)
converter = trt.TrtGraphConverterV2(
input_saved_model_dir=str(weight_path), conversion_params=conversion_params)
converter.convert()
converter.save(output_saved_model_dir='saved_model_TFTRT_FP16')
print('Done Converting to TF-TRT FP16')
saved_model_loaded = tf.saved_model.load('saved_model_TFTRT_FP16', tags=[tag_constants.SERVING])
signature_keys = list(saved_model_loaded.signatures.keys())
print(signature_keys)
infer = saved_model_loaded.signatures['serving_default']
print(infer.structured_outputs)
print(infer)
# labeling = infer(x)
for target_img_path in tqdm(image_paths):
target_img = imageio.imread(str(target_img_path), as_gray=False, pilmode="RGB")
target_float_img = target_img.astype(np.float32) / 255.
divided_image =divide_image(target_float_img, train_img_size)
# x = tf.constant(divided_image)
divided_image = tf.convert_to_tensor(divided_image, dtype=tf.float32)
# print("##################################################### divided_image", x.shape)
# print("##################################################### divided_image", divided_image[1])
for i in range(int(divided_image.shape[0])):
sigle_image = divided_image[i:i+2]
t1 = time.time()
# inputs = {}
# inputs['input_1']=x
# results = model.predict(np.array(divided_image),batch_size=batch_size)
outputs = infer(input_1=sigle_image)
# print("###########################################", outputs['activation_81'].shape)
t2 = time.time()
elapsed_time = t2-t1
print(f"########## ็ต้ๆ้_batch{batch_size}๏ผ{elapsed_time}")
# y = put_image_together(outputs, (target_img.shape[0], target_img.shape[1]))
# for label_name, decoded_label in zip(label_info.keys(), decode_prob(binarize_label(y))):
# overlay_img = make_overlay(target_img, decoded_label, label_color='r')
# Thread(target=imageio.imwrite, args=(str(result_path / f"label_{target_img_path.stem}_{label_name}.jpg"), overlay_img), daemon=False).start()
if __name__ == "__main__":
# main32()
main16()
|
play_song.py | #!/usr/bin/env python3
from gmusicapi import Mobileclient
from gmusicapi import Musicmanager
import re
import os
import threading
import aiy.assistant.auth_helpers
from aiy.assistant.library import Assistant
import aiy.voicehat
from google.assistant.library.event import EventType
import vlc
import time
finish = 0
__author__ = 'Jordan Page'
__license__ = 'MIT'
__version__ = '1.0.1'
gpm = Mobileclient()
# *** Change EXAMPLE and PASSWORD to your own Gmail login. ***
# If using the device on more than one network, you'll need an android_id
# Otherwise, you may use Mobileclient.FROM_MAC_ADDRESS as the third argument.
gpm.login('EXAMPLE@gmail.com', 'PASSWORD',
Mobileclient.FROM_MAC_ADDRESS)
# If using Windows, always 'escape' the backslashes, or we may get special characters
# 'D:\testfolder' would translate the \t into a tab, for example:
# 'D: estfolder'
song_location = '/home/pi/Music/'
def play_song(song):
if Mobileclient.is_authenticated(gpm):
mm = Musicmanager()
mm.login('/home/pi/oauth.cred')
if Musicmanager.is_authenticated(mm):
song_dict = mm.get_purchased_songs()
song_pattern = re.compile(r'(?:.)*\s?(' + re.escape(song)
+ r')\s?(?:.)*', re.IGNORECASE)
btn = OnButtonPress()
btn.start()
for song in song_dict:
m = re.match(song_pattern, song['title'])
print(m)
if re.match(song_pattern, song['title']) is not None:
print('Song found!')
song_id = song['id']
(filename, audio) = mm.download_song(song_id)
# get rid of non-ascii characters in file name
filename = filename.encode('ascii', errors='ignore')
# check if song is already downloaded
# path will look something like:
# /home/pi/Music/02 - Raindrop Prelude.mp3
# forces filename to be a string
filename = filename.decode('ascii')
path = song_location + filename
try:
if os.path.isfile(path):
print('Song is already downloaded...')
print(path)
print('Playing song.')
vlc_instance = vlc.Instance()
p = vlc_instance.media_player_new()
media = vlc_instance.media_new(path)
p.set_media(media)
events = p.event_manager()
events.event_attach(vlc.EventType.MediaPlayerEndReached,
SongFinished)
p.play()
p.audio_set_volume(58)
while finish == 0:
duration = p.get_time() / 1000
(m, s) = divmod(duration, 60)
print('Current song is: ', path)
print('Length:', '%02d:%02d' % (m, s))
time.sleep(5)
p.stop()
break
else:
with open(path, 'wb') as f:
f.write(audio)
print('Song has been added to: ' + path)
print('Playing song.')
vlc_instance = vlc.Instance()
p = vlc_instance.media_player_new()
media = vlc_instance.media_new(path)
p.set_media(media)
events = p.event_manager()
events.event_attach(vlc.EventType.MediaPlayerEndReached,
SongFinished)
p.play()
p.audio_set_volume(58)
while finish == 0:
duration = p.get_time() / 1000
(m, s) = divmod(duration, 60)
print('Current song is: ', path)
print('Length:', '%02d:%02d' % (m, s))
time.sleep(5)
p.stop()
break
except (OSError, IOError):
print('An error has occurred.')
break
else:
print('Song not found yet.')
else:
print('Looks like you need to authenticate.')
mm.perform_oauth('/home/pi/oauth.cred')
print('Logging out.')
Mobileclient.logout(gpm)
mm.logout()
else:
print('Mobileclient could not authenticate.')
Mobileclient.logout(gpm)
class OnButtonPress(object):
def __init__(self):
self._task = threading.Thread(target=self._run_task)
def start(self):
self._task.start()
def _run_task(self):
print('Button press thread running...')
credentials = aiy.assistant.auth_helpers.get_assistant_credentials()
with Assistant(credentials) as assistant:
self._assistant = assistant
for event in assistant.start():
self._process_event(event)
def _process_event(self, event):
if event.type == EventType.ON_START_FINISHED:
aiy.voicehat.get_button().on_press(self._on_button_pressed)
def _on_button_pressed(_):
print('Button was pressed.')
global finish
finish = 1
def SongFinished(event):
global finish
print('Finished playing song.')
finish = 1
# Useful if you want to test this function independently of cloudspeech
# Replace 'Never Forget' with some other song you may have
if __name__ == '__main__':
play_song('Never Forget')
|
ZBlock.py | import time
import threading
import config
from config import *
class ZBlock:
def __init__(self):
self.cells = 4 # Number of cells occupied by the block
config.block_count += 1
config.item_id["blocks"][f"{config.block_count}"] = {} # Add a new key to dictionary to add block IDs
for n in range(self.cells - 2):
# Loop draws the bottom cells of the block on the top of the board
# Generate an ID for each cell occupied by the block
config.item_id["blocks"][f"{config.block_count}"][f"{n}"] = dpg.generate_uuid()
# Make a list of the initial cells occupied by the blocks
config.cells_occupied.append([3 + n, 19])
# Draw the cell
dpg.draw_image(texture_tag=item_id["block_texture"]["Z_block"], pmin=[3 + n, 20], pmax=[4 + n, 19],
parent=item_id["windows"]["tetris_board"],
id=config.item_id["blocks"][f"{config.block_count}"][f"{n}"])
for n in range(self.cells - 2):
# Draw the final cells on the top
# Generate an ID for the top cell occupied by the block
config.item_id["blocks"][f"{config.block_count}"][f"{n + 2}"] = dpg.generate_uuid()
# Add point to cells_occupied list
config.cells_occupied.append([4 + n, 18])
# Draw the cell
dpg.draw_image(texture_tag=item_id["block_texture"]["Z_block"], pmin=[4 + n, 19], pmax=[5 + n, 18],
parent=item_id["windows"]["tetris_board"],
id=config.item_id["blocks"][f"{config.block_count}"][f"{n + 2}"])
# Update statistics
# Take the value shown, add 1 and set value
dpg.configure_item(item=item_id["displays"]["Z_block_stat"],
text=int(dpg.get_item_configuration(item=item_id["displays"]["Z_block_stat"])["text"]) + 1)
dpg.set_value(item=item_id["displays"]["Total_block_stat"],
value=int(dpg.get_value(item=item_id["displays"]["Total_block_stat"])) + 1)
def move_blockDispatcher(self):
# Function creates a new thread that controls the continuous movement of the new blocks
move_block_thread = threading.Thread(name="move block", target=self.move_block, args=(), daemon=True)
move_block_thread.start()
def move_block(self):
# Function controls the continuous downward movement of the blocks
config.block_moving_flag = 7 # Set to 5=SBlock. Block is moving
while True:
for n in range(self.cells):
config.cells_occupied[-1 - n][1] -= 1 # Shift the Y Coordinate down by 1 unit
if any(item in config.cells_occupied[-self.cells:] for item in config.cell_boundary) or \
any(item in config.cells_occupied[-self.cells:] for item in config.cells_occupied[:-self.cells]):
# Check if any cells have touched the wall or other blocks. If so, stop the movement
for n in range(self.cells):
config.cells_occupied[-1 - n][1] += 1 # Reset the Y coordinate
config.block_moving_flag = 0 # Block has stopped moving
return
for n in range(self.cells):
# Draw after all cells are updated
dpg.configure_item(item=config.item_id["blocks"][f"{config.block_count}"][f"{n}"],
pmin=[config.cells_occupied[-1 - n][0], config.cells_occupied[-1 - n][1] + 1],
pmax=[config.cells_occupied[-1 - n][0] + 1, config.cells_occupied[-1 - n][1]])
time.sleep(config.speed) # Wait at each cell
def draw_next_ZBlock():
for n in range(2):
# Loop draws the bottom layer of the complete block on the "next" board
dpg.draw_image(texture_tag=item_id["block_texture"]["Z_block"], pmin=[4 + n, 3], pmax=[5 + n, 2],
parent=item_id["windows"]["next_block_board"])
for n in range(2):
# Loop draws the top layer of the complete block on the "next" board
dpg.draw_image(texture_tag=item_id["block_texture"]["Z_block"], pmin=[3 + n, 4], pmax=[4 + n, 3],
parent=item_id["windows"]["next_block_board"])
def draw_statistics_ZBlock():
for n in range(2):
# Loop draws the bottom layer of the complete block on the "next" board
dpg.draw_image(texture_tag=item_id["block_texture"]["Z_block"], pmin=[1 + n, 8], pmax=[2 + n, 7],
parent=item_id["windows"]["statistics_window"])
for n in range(2):
# Loop draws the top layer of the complete block on the "next" board
dpg.draw_image(texture_tag=item_id["block_texture"]["Z_block"], pmin=[2 + n, 7], pmax=[3 + n, 6],
parent=item_id["windows"]["statistics_window"])
dpg.draw_line(p1=[6.5, 7], p2=[7.5, 7], thickness=0.1, color=[168, 168, 168],
parent=item_id["windows"]["statistics_window"])
dpg.draw_text(pos=[8.5, 7.3], text="0", size=0.5, color=[168, 168, 168],
id=item_id["displays"]["Z_block_stat"])
|
node.py | # Ant
#
# Copyright (c) 2012, Gustav Tiger <gustav@tiger.name>
#
# 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, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
import collections
import threading
import logging
try:
# Python 3
import queue
except ImportError:
# Python 2
import Queue as queue
from ant.base.ant import Ant
from ant.base.message import Message
from ant.easy.channel import Channel
from ant.easy.filter import wait_for_event, wait_for_response, wait_for_special
_logger = logging.getLogger("ant.easy.node")
class Node:
def __init__(self):
self._responses_cond = threading.Condition()
self._responses = collections.deque()
self._event_cond = threading.Condition()
self._events = collections.deque()
self._datas = queue.Queue()
self.channels = {}
self.ant = Ant()
self._running = True
self._worker_thread = threading.Thread(target=self._worker, name="ant.easy")
self._worker_thread.start()
def new_channel(self, ctype, network_number=0x00, ext_assign=None):
size = len(self.channels)
channel = Channel(size, self, self.ant)
self.channels[size] = channel
channel._assign(ctype, network_number, ext_assign)
return channel
def request_message(self, messageId):
_logger.debug("requesting message %#02x", messageId)
self.ant.request_message(0, messageId)
_logger.debug("done requesting message %#02x", messageId)
return self.wait_for_special(messageId)
def set_network_key(self, network, key):
self.ant.set_network_key(network, key)
return self.wait_for_response(Message.ID.SET_NETWORK_KEY)
def set_led(self, enabled):
self.ant.set_led(enabled)
return self.wait_for_response(Message.ID.ENABLE_LED)
def wait_for_event(self, ok_codes):
return wait_for_event(ok_codes, self._events, self._event_cond)
def wait_for_response(self, event_id):
return wait_for_response(event_id, self._responses, self._responses_cond)
def wait_for_special(self, event_id):
return wait_for_special(event_id, self._responses, self._responses_cond)
def _worker_response(self, channel, event, data):
self._responses_cond.acquire()
self._responses.append((channel, event, data))
self._responses_cond.notify()
self._responses_cond.release()
def _worker_event(self, channel, event, data):
if event == Message.Code.EVENT_RX_BURST_PACKET:
self._datas.put(("burst", channel, data))
elif event == Message.Code.EVENT_RX_BROADCAST:
self._datas.put(("broadcast", channel, data))
elif event == Message.Code.EVENT_TX:
self._datas.put(("broadcast_tx", channel, data))
elif event == Message.Code.EVENT_RX_ACKNOWLEDGED:
self._datas.put(("acknowledge", channel, data))
else:
self._event_cond.acquire()
self._events.append((channel, event, data))
self._event_cond.notify()
self._event_cond.release()
def _worker(self):
self.ant.response_function = self._worker_response
self.ant.channel_event_function = self._worker_event
# TODO: check capabilities
self.ant.start()
def _main(self):
while self._running:
try:
(data_type, channel, data) = self._datas.get(True, 1.0)
self._datas.task_done()
if data_type == "broadcast":
self.channels[channel].on_broadcast_data(data)
elif data_type == "burst":
self.channels[channel].on_burst_data(data)
elif data_type == "broadcast_tx":
self.channels[channel].on_broadcast_tx_data(data)
elif data_type == "acknowledge":
self.channels[channel].on_acknowledge_data(data)
else:
_logger.warning("Unknown data type '%s': %r", data_type, data)
except queue.Empty as e:
pass
def start(self):
self._main()
def stop(self):
if self._running:
_logger.debug("Stoping ant.easy")
self._running = False
self.ant.stop()
self._worker_thread.join()
|
test_batchupload.py | # coding: utf-8
import os
import threading
import uuid
from collections import defaultdict
from unittest.mock import patch
from uuid import uuid4
import pytest
import responses
from nuxeo.constants import IDEMPOTENCY_KEY, UP_AMAZON_S3
from nuxeo.exceptions import (
CorruptedFile,
HTTPError,
InvalidBatch,
InvalidUploadHandler,
OngoingRequestError,
UploadError,
)
from nuxeo.models import Batch, BufferBlob, Document, FileBlob
from requests.exceptions import ConnectionError
from sentry_sdk import configure_scope
from .constants import WORKSPACE_ROOT
from .server import Server
new_doc = Document(name="Document", type="File", properties={"dc:title": "foo"})
def get_batch(server):
batch = server.uploads.batch()
assert batch
assert repr(batch)
assert batch.uid
assert batch.upload_idx == 0
assert not server.uploads.get(batch.uid)
blob = BufferBlob(data="data", name="Test.txt", mimetype="text/plain")
assert repr(blob)
batch.upload(blob)
assert batch.upload_idx == 1
blob2 = BufferBlob(data="data2", name="Test2.txt", mimetype="text/plain")
batch.upload(blob2)
assert batch.upload_idx == 2
return batch
def test_token_callback(server):
original_creds = {
"bucket": "my-bucket",
"baseKey": "directupload/",
"endpoint": None,
"expiration": 1621345126000,
"usePathStyleAccess": False,
"region": "eu-west-1",
"useS3Accelerate": False,
"awsSecretKeyId": "...",
"awsSessionToken": "...",
"awsSecretAccessKey": "...",
}
batch = Batch(batchId=str(uuid4()), extraInfo=original_creds)
check = {batch.uid: None}
def callback(my_batch, creds):
check[my_batch.uid] = creds.copy()
# Using the default upload provider
# => the callback is not even called
creds = server.uploads.refresh_token(batch, token_callback=callback)
assert creds == {}
assert check[batch.uid] is None
url = f"{server.client.host}{server.uploads.endpoint}/{batch.uid}/refreshToken"
batch.provider = UP_AMAZON_S3
# Using S3 third-party upload provider, with credentials not expired
# => new credentials are then the same as current ones
with responses.RequestsMock() as rsps:
rsps.add(responses.POST, url, json=original_creds)
creds = server.uploads.refresh_token(batch, token_callback=callback)
assert creds == original_creds
assert check[batch.uid] is None
# Using S3 third-party upload provider, with credentials expired
# => new credentials are recieved
with responses.RequestsMock() as rsps:
new_creds = {
"awsSecretKeyId": "updated 1",
"awsSessionToken": "updated 2",
"awsSecretAccessKey": "updated 3",
}
rsps.add(responses.POST, url, json=new_creds)
creds = server.uploads.refresh_token(batch, token_callback=callback)
assert creds == new_creds
assert check[batch.uid] == new_creds
assert batch.extraInfo["awsSecretKeyId"] == "updated 1"
assert batch.extraInfo["awsSessionToken"] == "updated 2"
assert batch.extraInfo["awsSecretAccessKey"] == "updated 3"
def test_batch_handler_default(server):
server.uploads.batch(handler="default")
def test_batch_handler_inexistant(server):
with pytest.raises(InvalidUploadHandler) as exc:
server.uploads.batch(handler="light")
error = str(exc.value)
assert "light" in error
assert "default" in error
def test_batch__post_with_kwarg(server):
server.uploads.batch(headers={"upload-provider": "nuxeo"})
def test_cancel(server):
batch = get_batch(server)
batch.cancel()
assert batch.uid is None
batch.cancel()
with pytest.raises(InvalidBatch) as e:
batch.get(0)
assert str(e.value)
batch.delete(0)
def test_data(tmp_path):
blob = BufferBlob(data="data", name="Test.txt", mimetype="text/plain")
with blob:
assert blob.data
file_in = tmp_path / "file_in"
file_in.write_bytes(b"\x00" + os.urandom(1024 * 1024) + b"\x00")
blob = FileBlob(str(file_in))
with blob:
assert blob.data
@pytest.mark.parametrize(
"hash, is_valid",
[
# Raises CorruptedFile
("0" * 32, False),
# Bypasses checksum validation
(None, True),
("", True),
("foo", True),
],
)
def test_digester(tmp_path, hash, is_valid, server):
file_out = tmp_path / "file_out"
doc = server.documents.create(new_doc, parent_path=WORKSPACE_ROOT)
try:
batch = get_batch(server)
operation = server.operations.new("Blob.AttachOnDocument")
operation.params = {"document": WORKSPACE_ROOT + "/Document"}
operation.input_obj = batch.get(0)
operation.execute(void_op=True)
operation = server.operations.new("Blob.Get")
operation.input_obj = WORKSPACE_ROOT + "/Document"
if is_valid:
operation.execute(file_out=file_out, digest=hash)
else:
with pytest.raises(CorruptedFile) as e, configure_scope() as scope:
scope._should_capture = False
operation.execute(file_out=file_out, digest=hash)
assert str(e.value)
finally:
doc.delete()
@pytest.mark.parametrize("chunked", [False, True])
def test_empty_file(chunked, server):
batch = server.uploads.batch()
batch.upload(BufferBlob(data="", name="Test.txt"), chunked=chunked)
def test_execute(server):
server.client.set(schemas=["dublincore", "file"])
doc = server.documents.create(new_doc, parent_path=WORKSPACE_ROOT)
try:
batch = get_batch(server)
assert not doc.properties["file:content"]
batch.execute(
"Blob.AttachOnDocument",
file_idx=0,
params={"document": WORKSPACE_ROOT + "/Document"},
)
doc = server.documents.get(path=WORKSPACE_ROOT + "/Document")
assert doc.properties["file:content"]
blob = doc.fetch_blob()
assert isinstance(blob, bytes)
assert blob == b"data"
finally:
doc.delete()
def test_fetch(server):
batch = get_batch(server)
blob = batch.get(0)
assert not blob.fileIdx
assert blob.uploadType == "normal"
assert blob.name == "Test.txt"
assert blob.size == 4 # "data"
blob = batch.blobs[0]
assert blob.fileIdx == 0
assert blob.uploadType == "normal"
assert blob.uploaded
assert blob.uploadedSize == 4 # "data"
batch.delete(0)
assert not batch.blobs[0]
blob = batch.get(1)
assert blob.fileIdx == 1
assert blob.uploadType == "normal"
assert blob.name == "Test2.txt"
assert blob.size == 5 # "data2"
blob = batch.blobs[1]
assert blob.fileIdx == 1
assert blob.uploadType == "normal"
assert blob.uploaded
assert blob.uploadedSize == 5 # "data2"
batch.delete(1)
assert not batch.blobs[1]
def test_handlers(server):
server.uploads._API__handlers = None
handlers = server.uploads.handlers()
assert isinstance(handlers, list)
assert "default" in handlers
if UP_AMAZON_S3 in handlers:
assert server.uploads.has_s3()
else:
assert not server.uploads.has_s3()
# Test the second call does not recall the endpoint, it is cached
assert server.uploads.handlers() is handlers
# Test forcing the recall to the endpoint
forced_handlers = server.uploads.handlers(force=True)
assert forced_handlers is not handlers
def test_handlers_server_error(server):
def bad_request(*args, **kwargs):
raise HTTPError(500, "Server Error", "Mock'ed error")
with patch.object(server.client, "request", new=bad_request):
assert server.uploads.handlers(force=True) == []
def test_handlers_custom(server):
server.uploads._API__handlers = ["custom"]
with pytest.raises(HTTPError):
server.uploads.batch(handler="custom")
@pytest.mark.parametrize(
"filename, mimetypes",
[
("file.bmp", ["image/bmp", "image/x-ms-bmp"]),
("file.pdf", ["application/pdf"]),
],
)
def test_mimetype(filename, mimetypes, tmp_path, server):
file_in = tmp_path / filename
file_in.write_bytes(b"0" * 42)
blob = FileBlob(str(file_in))
assert blob.mimetype in mimetypes
doc = server.documents.create(new_doc, parent_path=WORKSPACE_ROOT)
try:
# Upload the blob
batch = server.uploads.batch()
uploader = batch.get_uploader(blob)
uploader.upload()
# Attach the blob to the doc
operation = server.operations.new("Blob.AttachOnDocument")
operation.params = {"document": doc.path}
operation.input_obj = batch.get(0)
operation.execute(void_op=True)
# Fetch doc metadata
operation = server.operations.new("Document.Fetch")
operation.params = {"value": doc.path}
info = operation.execute()
# Check the mimetype set by the server is correct
mimetype = info["properties"]["file:content"]["mime-type"]
assert mimetype in mimetypes
finally:
doc.delete()
@pytest.mark.parametrize(
"bad_mimetype, expected_mimetype",
[
(None, "application/pdf"),
("", "application/pdf"),
("pdf", "application/pdf"),
],
)
def test_bad_mimetype(bad_mimetype, expected_mimetype, tmp_path, server):
file_in = tmp_path / "file.pdf"
file_in.write_bytes(b"0" * 42)
blob = FileBlob(str(file_in), mimetype=bad_mimetype)
assert blob.mimetype == (bad_mimetype or expected_mimetype)
doc = server.documents.create(new_doc, parent_path=WORKSPACE_ROOT)
try:
# Upload the blob
batch = server.uploads.batch()
uploader = batch.get_uploader(blob)
uploader.upload()
# Attach the blob to the doc
operation = server.operations.new("Blob.AttachOnDocument")
operation.params = {"document": doc.path}
operation.input_obj = batch.get(0)
operation.execute(void_op=True)
# Fetch doc metadata
operation = server.operations.new("Document.Fetch")
operation.params = {"value": doc.path}
info = operation.execute()
# Check the mimetype set by the server is correct
mimetype = info["properties"]["file:content"]["mime-type"]
assert mimetype == expected_mimetype
finally:
doc.delete()
def test_operation(server):
batch = get_batch(server)
server.client.set(schemas=["dublincore", "file"])
doc = server.documents.create(new_doc, parent_path=WORKSPACE_ROOT)
try:
assert not doc.properties["file:content"]
operation = server.operations.new("Blob.AttachOnDocument")
operation.params = {"document": WORKSPACE_ROOT + "/Document"}
operation.input_obj = batch.get(0)
operation.execute()
doc = server.documents.get(path=WORKSPACE_ROOT + "/Document")
assert doc.properties["file:content"]
blob = doc.fetch_blob()
assert isinstance(blob, bytes)
assert blob == b"data"
finally:
doc.delete()
@pytest.mark.parametrize("chunked", [False, True])
def test_upload_chunk_timeout(tmp_path, chunked, server):
chunk_size = 1024
file_size = 4096 if chunked else chunk_size
file_in = tmp_path / "file_in"
file_in.write_bytes(b"\x00" * file_size)
blob = FileBlob(str(file_in), mimetype="application/octet-stream")
batch = server.uploads.batch()
uploader = batch.get_uploader(blob, chunked=chunked, chunk_size=chunk_size)
assert uploader.timeout(-1) == 60.0
assert uploader.timeout(0.000001) == 60.0
assert uploader.timeout(0) == 60.0
assert uploader.timeout(1) == 60.0
assert uploader.timeout(1024) == 60.0
assert uploader.timeout(1024 * 1024) == 60.0 * 1 # 1 MiB
assert uploader.timeout(1024 * 1024 * 5) == 60.0 * 5 # 5 MiB
assert uploader.timeout(1024 * 1024 * 10) == 60.0 * 10 # 10 MiB
assert uploader.timeout(1024 * 1024 * 20) == 60.0 * 20 # 20 MiB
uploader._timeout = 0.00001
assert uploader.timeout(chunk_size) == 0.00001
with pytest.raises(ConnectionError) as exc:
uploader.upload()
error = str(exc.value)
assert "timed out" in error
@pytest.mark.parametrize("chunked", [False, True])
def test_upload(tmp_path, chunked, server):
def callback(upload):
assert upload
assert isinstance(upload.blob.uploadedChunkIds, list)
assert isinstance(upload.blob.uploadedSize, int)
if not chunked:
assert upload.blob.uploadedSize == file_size
assert upload.blob.uploadType == "normal"
else:
# In chunked mode, we should have 1024, 2048, 3072 and 4096 respectively
sizes = {1: 1024, 2: 1024 * 2, 3: 1024 * 3, 4: 1024 * 4}
assert upload.blob.uploadedSize == sizes[len(upload.blob.uploadedChunkIds)]
assert upload.blob.uploadType == "chunked"
batch = server.uploads.batch()
chunk_size = 1024
file_size = 4096 if chunked else 1024
file_in, file_out = tmp_path / "file_in", tmp_path / "file_out"
file_in.write_bytes(b"\x00" * file_size)
doc = server.documents.create(new_doc, parent_path=WORKSPACE_ROOT)
try:
blob = FileBlob(str(file_in), mimetype="application/octet-stream")
assert repr(blob)
assert batch.upload(
blob, chunked=chunked, callback=callback, chunk_size=chunk_size
)
operation = server.operations.new("Blob.AttachOnDocument")
operation.params = {"document": WORKSPACE_ROOT + "/Document"}
operation.input_obj = batch.get(0)
operation.execute(void_op=True)
operation = server.operations.new("Document.Fetch")
operation.params = {"value": WORKSPACE_ROOT + "/Document"}
info = operation.execute()
digest = info["properties"]["file:content"]["digest"]
operation = server.operations.new("Blob.Get")
operation.input_obj = WORKSPACE_ROOT + "/Document"
file_out = operation.execute(file_out=file_out, digest=digest)
finally:
doc.delete()
@pytest.mark.parametrize("chunked", [False, True])
def test_upload_several_callbacks(tmp_path, chunked, server):
check = 0
def callback1(upload):
nonlocal check
check += 1
def callback2(upload):
assert upload
assert isinstance(upload.blob.uploadedChunkIds, list)
assert isinstance(upload.blob.uploadedSize, int)
if not chunked:
assert upload.blob.uploadedSize == file_size
assert upload.blob.uploadType == "normal"
else:
# In chunked mode, we should have 1024, 2048, 3072 and 4096 respectively
sizes = {1: 1024, 2: 1024 * 2, 3: 1024 * 3, 4: 1024 * 4}
assert upload.blob.uploadedSize == sizes[len(upload.blob.uploadedChunkIds)]
assert upload.blob.uploadType == "chunked"
batch = server.uploads.batch()
chunk_size = 1024
file_size = 4096 if chunked else 1024
file_in, file_out = tmp_path / "file_in", tmp_path / "file_out"
file_in.write_bytes(b"\x00" * file_size)
callbacks = [callback1, callback2, "callback3"]
doc = server.documents.create(new_doc, parent_path=WORKSPACE_ROOT)
try:
blob = FileBlob(str(file_in), mimetype="application/octet-stream")
assert repr(blob)
assert batch.upload(
blob, chunked=chunked, callback=callbacks, chunk_size=chunk_size
)
operation = server.operations.new("Blob.AttachOnDocument")
operation.params = {"document": WORKSPACE_ROOT + "/Document"}
operation.input_obj = batch.get(0)
operation.execute(void_op=True)
operation = server.operations.new("Document.Fetch")
operation.params = {"value": WORKSPACE_ROOT + "/Document"}
info = operation.execute()
digest = info["properties"]["file:content"]["digest"]
operation = server.operations.new("Blob.Get")
operation.input_obj = WORKSPACE_ROOT + "/Document"
file_out = operation.execute(file_out=file_out, digest=digest)
finally:
doc.delete()
# Check the callback count (1 for not chucked)
assert check == 4 if chunked else 1
def test_get_uploader(tmp_path, server):
def callback(*args):
assert args
batch = server.uploads.batch()
file_in = tmp_path / "file_in"
file_in.write_bytes(b"\x00" + os.urandom(1024 * 1024) + b"\x00")
blob = FileBlob(str(file_in), mimetype="application/octet-stream")
uploader = batch.get_uploader(
blob, chunked=True, chunk_size=256 * 1024, callback=callback
)
assert str(uploader)
for idx, _ in enumerate(uploader.iter_upload(), 1):
assert idx == len(uploader.blob.uploadedChunkIds)
assert batch.get(0)
def test_upload_error(tmp_path, server):
batch = server.uploads.batch()
file_in = tmp_path / "file_in"
file_in.write_bytes(b"\x00" + os.urandom(1024 * 1024) + b"\x00")
blob = FileBlob(str(file_in), mimetype="application/octet-stream")
assert repr(blob)
uploader = batch.get_uploader(blob, chunked=True, chunk_size=256 * 1024)
gen = uploader.iter_upload()
# Upload chunks 0 and 1
next(gen)
next(gen)
# Retry the chunk 0, it should end on a error
backup = uploader._to_upload
uploader._to_upload = [0]
with pytest.raises(UploadError) as e:
next(gen)
assert e.value
assert "already exists" in e.value.info
# Finish the upload, it must succeed
uploader._to_upload = backup
list(uploader.iter_upload())
def test_upload_retry(tmp_path, retry_server):
server = retry_server
close_server = threading.Event()
file_in = tmp_path / "ฯฯฯ
ฯฮฑฯแฝถ"
file_in.write_bytes(b"\x00" + os.urandom(1024 * 1024) + b"\x00")
with patch.object(server.client, "host", new="http://localhost:8081/nuxeo/"):
serv = Server.upload_response_server(
wait_to_close_event=close_server,
port=8081,
requests_to_handle=20,
fail_args={"fail_at": 4, "fail_number": 1},
)
with serv:
batch = server.uploads.batch()
blob = FileBlob(str(file_in), mimetype="application/octet-stream")
batch.upload(blob, chunked=True, chunk_size=256 * 1024)
close_server.set() # release server block
def test_upload_resume(tmp_path, server):
file_in = tmp_path / "file_in"
file_in.write_bytes(b"\x00" + os.urandom(1024 * 1024) + b"\x00")
with patch.object(server.client, "host", new="http://localhost:8081/nuxeo/"):
close_server = threading.Event()
serv = Server.upload_response_server(
wait_to_close_event=close_server,
port=8081,
requests_to_handle=20,
fail_args={"fail_at": 4, "fail_number": 1},
)
with serv:
batch = server.uploads.batch()
blob = FileBlob(str(file_in), mimetype="application/octet-stream")
with pytest.raises(UploadError) as e:
batch.upload(blob, chunked=True, chunk_size=256 * 1024)
assert str(e.value)
# Resume the upload
batch.upload(blob, chunked=True, chunk_size=256 * 1024)
# No-op
batch.complete()
# Release the server block
close_server.set()
def test_wrong_batch_id(server):
batch = server.uploads.batch()
batch.uid = "1234"
with pytest.raises(HTTPError):
batch.get(0)
def test_idempotent_requests(tmp_path, server):
"""
- upload a file in chunked mode
- call 5 times (concurrently) the FileManager.Import operation with that file
- check there are both conflict errors and only one created document
"""
file_in = tmp_path / "file_in"
file_in.write_bytes(os.urandom(1024 * 1024 * 10))
batch = server.uploads.batch()
blob = FileBlob(str(file_in))
batch.upload(blob, chunked=True, chunk_size=1024 * 1024)
idempotency_key = str(uuid.uuid4())
res = defaultdict(int)
def func():
try:
op = server.operations.execute(
command="FileManager.Import",
context={"currentDocument": doc.path},
input_obj=blob,
headers={
IDEMPOTENCY_KEY: idempotency_key,
"X-Batch-No-Drop": "true",
},
)
res[op["uid"]] += 1
except OngoingRequestError as exc:
res[str(exc)] += 1
# Create a folder
name = str(uuid.uuid4())
folder = Document(name=name, type="Folder", properties={"dc:title": name})
doc = server.documents.create(folder, parent_path=WORKSPACE_ROOT)
try:
# Concurrent calls to the same endpoint
threads = [threading.Thread(target=func) for _ in range(5)]
threads[0].start()
threads[0].join(0.001)
for thread in threads[1:]:
thread.start()
for thread in threads:
thread.join()
# Checks
# 1 docid + 1 error (both can be present multiple times)
assert len(res.keys()) == 2
error = (
"OngoingRequestError: a request with the idempotency key"
f" {idempotency_key!r} is already being processed."
)
assert error in res
# Ensure there is only 1 doc on the server
children = server.documents.get_children(path=doc.path)
assert len(children) == 1
assert children[0].title == file_in.name
# Check calling the same request with the same idempotency key returns always the same result
current_identical_doc = res[children[0].uid]
current_identical_errors = res[error]
for _ in range(10):
func()
assert res[error] == current_identical_errors
assert res[children[0].uid] == current_identical_doc + 10
finally:
doc.delete()
|
TFLite_detection_webcam.py |
# Credit: Evan Juras
# Description:
# This program uses a TensorFlow Lite model to perform object detection on a live webcam
# feed. It draws boxes and scores around the objects of interest in each frame from the
# webcam. To improve FPS, the webcam object runs in a separate thread from the main program.
# This script will work with either a Picamera or regular USB webcam.
# Import packages
import os
import argparse
import cv2
import numpy as np
import sys
import time
from threading import Thread
import importlib.util
# Define VideoStream class to handle streaming of video from webcam in separate processing thread
# Source - Adrian Rosebrock, PyImageSearch: https://www.pyimagesearch.com/2015/12/28/increasing-raspberry-pi-fps-with-python-and-opencv/
class VideoStream:
"""Camera object that controls video streaming from the Picamera"""
def __init__(self,resolution=(640,480),framerate=30):
# Initialize the PiCamera and the camera image stream
self.stream = cv2.VideoCapture(0)
ret = self.stream.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc(*'MJPG'))
ret = self.stream.set(3,resolution[0])
ret = self.stream.set(4,resolution[1])
# Read first frame from the stream
(self.grabbed, self.frame) = self.stream.read()
# Variable to control when the camera is stopped
self.stopped = False
def start(self):
# Start the thread that reads frames from the video stream
Thread(target=self.update,args=()).start()
return self
def update(self):
# Keep looping indefinitely until the thread is stopped
while True:
# If the camera is stopped, stop the thread
if self.stopped:
# Close camera resources
self.stream.release()
return
# Otherwise, grab the next frame from the stream
(self.grabbed, self.frame) = self.stream.read()
def read(self):
# Return the most recent frame
return self.frame
def stop(self):
# Indicate that the camera and thread should be stopped
self.stopped = True
# Define and parse input arguments
parser = argparse.ArgumentParser()
parser.add_argument('--modeldir', help='Folder the .tflite file is located in',
required=True)
parser.add_argument('--graph', help='Name of the .tflite file, if different than detect.tflite',
default='detect.tflite')
parser.add_argument('--labels', help='Name of the labelmap file, if different than labelmap.txt',
default='labelmap.txt')
parser.add_argument('--threshold', help='Minimum confidence threshold for displaying detected objects',
default=0.5)
parser.add_argument('--resolution', help='Desired webcam resolution in WxH. If the webcam does not support the resolution entered, errors may occur.',
default='1280x720')
parser.add_argument('--edgetpu', help='Use Coral Edge TPU Accelerator to speed up detection',
action='store_true')
args = parser.parse_args()
MODEL_NAME = args.modeldir
GRAPH_NAME = args.graph
LABELMAP_NAME = args.labels
min_conf_threshold = float(args.threshold)
resW, resH = args.resolution.split('x')
imW, imH = int(resW), int(resH)
use_TPU = args.edgetpu
# Import TensorFlow libraries
# If tflite_runtime is installed, import interpreter from tflite_runtime, else import from regular tensorflow
# If using Coral Edge TPU, import the load_delegate library
pkg = importlib.util.find_spec('tflite_runtime')
if pkg:
from tflite_runtime.interpreter import Interpreter
if use_TPU:
from tflite_runtime.interpreter import load_delegate
else:
from tensorflow.lite.python.interpreter import Interpreter
if use_TPU:
from tensorflow.lite.python.interpreter import load_delegate
# If using Edge TPU, assign filename for Edge TPU model
if use_TPU:
# If user has specified the name of the .tflite file, use that name, otherwise use default 'edgetpu.tflite'
if (GRAPH_NAME == 'detect.tflite'):
GRAPH_NAME = 'edgetpu.tflite'
# Get path to current working directory
CWD_PATH = os.getcwd()
# Path to .tflite file, which contains the model that is used for object detection
PATH_TO_CKPT = os.path.join(CWD_PATH,MODEL_NAME,GRAPH_NAME)
# Path to label map file
PATH_TO_LABELS = os.path.join(CWD_PATH,MODEL_NAME,LABELMAP_NAME)
# Load the label map
with open(PATH_TO_LABELS, 'r') as f:
labels = [line.strip() for line in f.readlines()]
# Have to do a weird fix for label map if using the COCO "starter model" from
# https://www.tensorflow.org/lite/models/object_detection/overview
# First label is '???', which has to be removed.
if labels[0] == '???':
del(labels[0])
# Load the Tensorflow Lite model.
# If using Edge TPU, use special load_delegate argument
if use_TPU:
interpreter = Interpreter(model_path=PATH_TO_CKPT,
experimental_delegates=[load_delegate('libedgetpu.so.1.0')])
print(PATH_TO_CKPT)
else:
interpreter = Interpreter(model_path=PATH_TO_CKPT)
interpreter.allocate_tensors()
# Get model details
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
height = input_details[0]['shape'][1]
width = input_details[0]['shape'][2]
floating_model = (input_details[0]['dtype'] == np.float32)
input_mean = 127.5
input_std = 127.5
# Initialize frame rate calculation
frame_rate_calc = 1
freq = cv2.getTickFrequency()
# Initialize video stream
videostream = VideoStream(resolution=(imW,imH),framerate=30).start()
time.sleep(1)
#for frame1 in camera.capture_continuous(rawCapture, format="bgr",use_video_port=True):
while True:
# Start timer (for calculating frame rate)
t1 = cv2.getTickCount()
# Grab frame from video stream
frame1 = videostream.read()
# Acquire frame and resize to expected shape [1xHxWx3]
frame = frame1.copy()
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frame_resized = cv2.resize(frame_rgb, (width, height))
input_data = np.expand_dims(frame_resized, axis=0)
# Normalize pixel values if using a floating model (i.e. if model is non-quantized)
if floating_model:
input_data = (np.float32(input_data) - input_mean) / input_std
# Perform the actual detection by running the model with the image as input
interpreter.set_tensor(input_details[0]['index'],input_data)
interpreter.invoke()
# Retrieve detection results
boxes = interpreter.get_tensor(output_details[0]['index'])[0] # Bounding box coordinates of detected objects
classes = interpreter.get_tensor(output_details[1]['index'])[0] # Class index of detected objects
scores = interpreter.get_tensor(output_details[2]['index'])[0] # Confidence of detected objects
#num = interpreter.get_tensor(output_details[3]['index'])[0] # Total number of detected objects (inaccurate and not needed)
# Loop over all detections and draw detection box if confidence is above minimum threshold
for i in range(len(scores)):
if ((scores[i] > min_conf_threshold) and (scores[i] <= 1.0)):
# Get bounding box coordinates and draw box
# Interpreter can return coordinates that are outside of image dimensions, need to force them to be within image using max() and min()
ymin = int(max(1,(boxes[i][0] * imH)))
xmin = int(max(1,(boxes[i][1] * imW)))
ymax = int(min(imH,(boxes[i][2] * imH)))
xmax = int(min(imW,(boxes[i][3] * imW)))
cv2.rectangle(frame, (xmin,ymin), (xmax,ymax), (10, 255, 0), 2)
# Draw label
object_name = labels[int(classes[i])] # Look up object name from "labels" array using class index
label = '%s: %d%%' % (object_name, int(scores[i]*100)) # Example: 'person: 72%'
labelSize, baseLine = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.7, 2) # Get font size
label_ymin = max(ymin, labelSize[1] + 10) # Make sure not to draw label too close to top of window
cv2.rectangle(frame, (xmin, label_ymin-labelSize[1]-10), (xmin+labelSize[0], label_ymin+baseLine-10), (255, 255, 255), cv2.FILLED) # Draw white box to put label text in
cv2.putText(frame, label, (xmin, label_ymin-7), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 0), 2) # Draw label text
# Draw framerate in corner of frame
cv2.putText(frame,'FPS: {0:.2f}'.format(frame_rate_calc),(30,50),cv2.FONT_HERSHEY_SIMPLEX,1,(255,255,0),2,cv2.LINE_AA)
# All the results have been drawn on the frame, so it's time to display it.
cv2.imshow('Object detector', frame)
# Calculate framerate
t2 = cv2.getTickCount()
time1 = (t2-t1)/freq
frame_rate_calc= 1/time1
# Press 'q' to quit
if cv2.waitKey(1) == ord('q'):
break
# Clean up
cv2.destroyAllWindows()
videostream.stop()
|
__init__.py | # Copyright 2018 Mycroft AI 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 writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import astral
import time
import arrow
from pytz import timezone
from datetime import datetime
from mycroft.messagebus.message import Message
from mycroft.skills.core import MycroftSkill
from mycroft.util import connected, find_input_device, get_ipc_directory
from mycroft.util.log import LOG
from mycroft.util.parse import normalize
from mycroft.audio import wait_while_speaking
from mycroft import intent_file_handler
import os
import pyaudio
import struct
import math
from threading import Thread
FORMAT = pyaudio.paInt16
SHORT_NORMALIZE = (1.0/32768.0)
CHANNELS = 2
RATE = 44100
INPUT_BLOCK_TIME = 0.05
INPUT_FRAMES_PER_BLOCK = int(RATE*INPUT_BLOCK_TIME)
def get_rms(block):
""" RMS amplitude is defined as the square root of the
mean over time of the square of the amplitude.
so we need to convert this string of bytes into
a string of 16-bit samples...
"""
# we will get one short out for each
# two chars in the string.
count = len(block) / 2
format = "%dh" % (count)
shorts = struct.unpack(format, block)
# iterate over the block.
sum_squares = 0.0
for sample in shorts:
# sample is a signed short in +/- 32768.
# normalize it to 1.0
n = sample * SHORT_NORMALIZE
sum_squares += n * n
return math.sqrt(sum_squares / count)
def open_mic_stream(pa, device_index, device_name):
""" Open microphone stream from first best microphone device. """
if not device_index and device_name:
device_index = find_input_device(device_name)
stream = pa.open(format=FORMAT, channels=CHANNELS, rate=RATE,
input=True, input_device_index=device_index,
frames_per_buffer=INPUT_FRAMES_PER_BLOCK)
return stream
def read_file_from(filename, bytefrom):
""" Read listener level from offset. """
with open(filename, 'r') as fh:
meter_cur = None
fh.seek(bytefrom)
while True:
line = fh.readline()
if line == "":
break
# Just adjust meter settings
# Ex:Energy: cur=4 thresh=1.5
parts = line.split("=")
meter_thresh = float(parts[-1])
meter_cur = float(parts[-2].split(" ")[0])
return meter_cur
class Mark2(MycroftSkill):
IDLE_CHECK_FREQUENCY = 6 # in seconds
def __init__(self):
super().__init__("Mark2")
self.idle_count = 99
self.idle_screens = {}
self.override_idle = None
self.hourglass_info = {}
self.interaction_id = 0
self.settings['auto_brightness'] = False
self.settings['auto_dim_eyes'] = True
self.settings['use_listening_beep'] = True
self.has_show_page = False # resets with each handler
# Volume indicatior
self.setup_mic_listening()
self.listener_file = os.path.join(get_ipc_directory(), "mic_level")
self.st_results = os.stat(self.listener_file)
self.max_amplitude = 0
def setup_mic_listening(self):
""" Initializes PyAudio, starts an input stream and launches the
listening thread.
"""
self.pa = pyaudio.PyAudio()
listener_conf = self.config_core['listener']
self.stream = open_mic_stream(self.pa,
listener_conf.get('device_index'),
listener_conf.get('device_name'))
self.amplitude = 0
def initialize(self):
# Initialize...
self.brightness_dict = self.translate_namedvalues('brightness.levels')
self.color_dict = self.translate_namedvalues('colors')
self.gui['volume'] = 0
# Prepare GUI Viseme structure
self.gui['viseme'] = {'start': 0, 'visemes': []}
# Preselect Time and Date as resting screen
self.gui['selected'] = self.settings.get('selected', 'Time and Date')
self.gui.set_on_gui_changed(self.save_resting_screen)
# Start listening thread
self.running = True
self.thread = Thread(target=self.listen_thread)
self.thread.daemon = True
self.thread.start()
try:
self.add_event('mycroft.internet.connected',
self.handle_internet_connected)
# Handle the 'waking' visual
self.add_event('recognizer_loop:record_begin',
self.handle_listener_started)
self.add_event('recognizer_loop:record_end',
self.handle_listener_ended)
self.add_event('mycroft.speech.recognition.unknown',
self.handle_failed_stt)
self.start_idle_check()
# Handle the 'busy' visual
self.bus.on('mycroft.skill.handler.start',
self.on_handler_started)
self.bus.on('mycroft.skill.handler.complete',
self.on_handler_complete)
self.bus.on('recognizer_loop:sleep',
self.on_handler_sleep)
self.bus.on('mycroft.awoken',
self.on_handler_awoken)
self.bus.on('recognizer_loop:audio_output_start',
self.on_handler_interactingwithuser)
self.bus.on('enclosure.mouth.think',
self.on_handler_interactingwithuser)
self.bus.on('enclosure.mouth.reset',
self.on_handler_mouth_reset)
self.bus.on('recognizer_loop:audio_output_end',
self.on_handler_mouth_reset)
self.bus.on('enclosure.mouth.events.deactivate',
self.on_handler_interactingwithuser)
self.bus.on('enclosure.mouth.text',
self.on_handler_interactingwithuser)
self.bus.on('enclosure.mouth.viseme_list',
self.on_handler_speaking)
self.bus.on('gui.page.show',
self.on_gui_page_show)
self.bus.on('gui.page_interaction', self.on_gui_page_interaction)
self.bus.on('mycroft.skills.initialized', self.reset_face)
self.bus.on('mycroft.mark2.register_idle',
self.on_register_idle)
# Handle device settings events
self.add_event('mycroft.device.settings',
self.handle_device_settings) #Use Legacy for QuickSetting delegate
self.gui.register_handler('mycroft.device.settings',
self.handle_device_settings)
self.gui.register_handler('mycroft.device.settings.brightness',
self.handle_device_brightness_settings)
self.gui.register_handler('mycroft.device.settings.homescreen',
self.handle_device_homescreen_settings)
self.gui.register_handler('mycroft.device.settings.ssh',
self.handle_device_ssh_settings)
self.gui.register_handler('mycroft.device.settings.reset',
self.handle_device_factory_reset_settings)
self.gui.register_handler('mycroft.device.settings.update',
self.handle_device_update_settings)
self.gui.register_handler('mycroft.device.settings.restart',
self.handle_device_restart_action)
self.gui.register_handler('mycroft.device.settings.poweroff',
self.handle_device_poweroff_action)
self.gui.register_handler('mycroft.device.settings.wireless',
self.handle_show_wifi_screen_intent)
self.gui.register_handler('mycroft.device.show.idle', self.show_idle_screen)
# Handle networking events sequence
self.gui.register_handler('networkConnect.wifi',
self.handle_show_wifi_pass_screen_intent)
self.gui.register_handler('networkConnect.connecting',
self.handle_show_network_connecting_screen_intent)
self.gui.register_handler('networkConnect.connected',
self.handle_show_network_connected_screen_intent)
self.gui.register_handler('networkConnect.failed',
self.handle_show_network_fail_screen_intent)
self.gui.register_handler('networkConnect.return',
self.handle_return_to_networkselection)
# Show sleeping face while starting up skills.
self.gui['state'] = 'resting'
self.gui.show_page('all.qml')
# Collect Idle screens and display if skill is restarted
self.collect_resting_screens()
except Exception:
LOG.exception('In Mark 1 Skill')
# Update use of wake-up beep
self._sync_wake_beep_setting()
self.settings.set_changed_callback(self.on_websettings_changed)
def save_resting_screen(self):
""" Handler to be called if the settings are changed by
the GUI.
Stores the selected idle screen.
"""
self.log.debug("Saving resting screen")
self.settings['selected'] = self.gui['selected']
def collect_resting_screens(self):
""" Trigger collection and then show the resting screen. """
self.bus.emit(Message('mycroft.mark2.collect_idle'))
time.sleep(0.1)
self.show_idle_screen()
def on_register_idle(self, message):
""" Handler for catching incoming idle screens. """
if 'name' in message.data and 'id' in message.data:
self.idle_screens[message.data['name']] = message.data['id']
self.log.info('Registered {}'.format(message.data['name']))
else:
self.log.error('Malformed idle screen registration received')
def reset_face(self, message):
""" Triggered after skills are initialized.
Sets switches from resting "face" to a registered resting screen.
"""
time.sleep(1)
self.collect_resting_screens()
def listen_thread(self):
""" listen on mic input until self.running is False. """
while(self.running):
self.listen()
def get_audio_level(self):
""" Get level directly from audio device. """
try:
block = self.stream.read(INPUT_FRAMES_PER_BLOCK)
except IOError as e:
# damn
self.errorcount += 1
self.log.error("(%d) Error recording: %s"%(self.errorcount,e))
self.noisycount = 1
return None
amplitude = get_rms(block)
if amplitude > self.max_amplitude:
self.max_amplitude = amplitude
return int(amplitude / self.max_amplitude * 10)
def get_listener_level(self):
""" Get level from IPC file created by listener. """
time.sleep(0.05)
try:
st_results = os.stat(self.listener_file)
if (not st_results.st_ctime == self.st_results.st_ctime or
not st_results.st_mtime == self.st_results.st_mtime):
ret = read_file_from(self.listener_file, 0)
self.st_results = st_results
if ret is not None:
if ret > self.max_amplitude:
self.max_amplitude = ret
ret = int(ret / self.max_amplitude * 10)
return ret
except Exception as e:
self.log.error(repr(e))
return None
def listen(self):
""" Read microphone level and store rms into self.gui['volume']. """
#amplitude = self.get_audio_level()
amplitude = self.get_listener_level()
if (self.gui and ('volume' not in self.gui
or self.gui['volume'] != amplitude) and
amplitude is not None):
self.gui['volume'] = amplitude
def stop(self, message=None):
""" Clear override_idle and stop visemes. """
if (self.override_idle and
time.monotonic() - self.override_idle[1] > 2):
self.override_idle = None
self.gui['viseme'] = {'start': 0, 'visemes': []}
return False
def shutdown(self):
# Gotta clean up manually since not using add_event()
self.bus.remove('mycroft.skill.handler.start',
self.on_handler_started)
self.bus.remove('mycroft.skill.handler.complete',
self.on_handler_complete)
self.bus.remove('recognizer_loop:audio_output_start',
self.on_handler_interactingwithuser)
self.bus.remove('recognizer_loop:sleep',
self.on_handler_sleep)
self.bus.remove('mycroft.awoken',
self.on_handler_awoken)
self.bus.remove('enclosure.mouth.think',
self.on_handler_interactingwithuser)
self.bus.remove('enclosure.mouth.reset',
self.on_handler_mouth_reset)
self.bus.remove('recognizer_loop:audio_output_end',
self.on_handler_mouth_reset)
self.bus.remove('enclosure.mouth.events.deactivate',
self.on_handler_interactingwithuser)
self.bus.remove('enclosure.mouth.text',
self.on_handler_interactingwithuser)
self.bus.remove('enclosure.mouth.viseme_list',
self.on_handler_speaking)
self.bus.remove('gui.page_interaction', self.on_gui_page_interaction)
self.bus.remove('mycroft.mark2.register_idle', self.on_register_idle)
self.running = False
self.thread.join()
self.stream.close()
#####################################################################
# Manage "busy" visual
def on_handler_started(self, message):
handler = message.data.get("handler", "")
# Ignoring handlers from this skill and from the background clock
if "Mark2" in handler:
return
if "TimeSkill.update_display" in handler:
return
self.hourglass_info[handler] = self.interaction_id
# time.sleep(0.25)
if self.hourglass_info[handler] == self.interaction_id:
# Nothing has happend within a quarter second to indicate to the
# user that we are active, so start a thinking visual
self.hourglass_info[handler] = -1
# SSP: No longer need this logic since we show "thinking.qml"
# immediately after the record_end?
# self.gui.show_page("thinking.qml")
def on_gui_page_interaction(self, message):
self.idle_count = 0
def on_gui_page_show(self, message):
if "mark-2" not in message.data.get("__from", ""):
# Some skill other than the handler is showing a page
self.has_show_page = True
# If a skill overrides the idle do not switch page
override_idle = message.data.get('__idle')
if override_idle is not None:
self.log.debug("cancelling idle")
self.cancel_scheduled_event('IdleCheck')
self.idle_count = 0
self.override_idle = (message, time.monotonic())
def on_handler_mouth_reset(self, message):
""" Restore viseme to a smile. """
pass
def on_handler_interactingwithuser(self, message):
""" Every time we do something that the user would notice,
increment an interaction counter.
"""
self.interaction_id += 1
def on_handler_sleep(self, message):
""" Show resting face when going to sleep. """
self.gui['state'] = 'resting'
self.gui.show_page("all.qml")
def on_handler_awoken(self, message):
""" Show awake face when sleep ends. """
self.gui['state'] = 'awake'
self.gui.show_page("all.qml")
def on_handler_complete(self, message):
handler = message.data.get("handler", "")
# Ignoring handlers from this skill and from the background clock
if "Mark2" in handler:
return
if "TimeSkill.update_display" in handler:
return
self.has_show_page = False
try:
if self.hourglass_info[handler] == -1:
self.enclosure.reset()
del self.hourglass_info[handler]
except:
# There is a slim chance the self.hourglass_info might not
# be populated if this skill reloads at just the right time
# so that it misses the mycroft.skill.handler.start but
# catches the mycroft.skill.handler.complete
pass
#####################################################################
# Manage "speaking" visual
def on_handler_speaking(self, message):
self.gui["viseme"] = message.data
if not self.has_show_page and self.gui['state'] != 'speaking':
self.gui['state'] = 'speaking'
self.gui.show_page("all.qml")
#####################################################################
# Manage "idle" visual state
def start_idle_check(self):
# Clear any existing checker
self.cancel_scheduled_event('IdleCheck')
self.idle_count = 0
# Schedule a check every few seconds
self.schedule_repeating_event(self.check_for_idle, None,
Mark2.IDLE_CHECK_FREQUENCY,
name='IdleCheck')
def check_for_idle(self):
# No activity, start to fall asleep
self.idle_count += 1
if self.idle_count == 5:
# Go into a 'sleep' visual state
self.show_idle_screen()
elif self.idle_count > 5:
self.cancel_scheduled_event('IdleCheck')
def show_idle_screen(self):
""" Show the idle screen or return to the skill that's overriding idle.
"""
screen = None
if self.override_idle:
self.log.debug("Returning to override")
# Restore the page overriding idle instead of the normal idle
self.bus.emit(self.override_idle[0])
elif len(self.idle_screens) > 0:
# TODO remove hard coded value
self.log.debug('Showing Idle screen for '
'{}'.format(self.gui['selected']))
screen = self.idle_screens.get(self.gui['selected'])
if screen:
self.bus.emit(Message('{}.idle'.format(screen)))
def handle_listener_started(self, message):
""" Shows listener page after wakeword is triggered.
Starts countdown to show the idle page.
"""
# Start idle timer
self.start_idle_check()
# Show listening page
self.gui['state'] = 'listening'
self.gui.show_page('all.qml')
def handle_listener_ended(self, message):
""" When listening has ended show the thinking animation. """
self.gui['state'] = 'thinking'
self.gui.show_page('all.qml')
def handle_failed_stt(self, message):
# No discernable words were transcribed
pass
#####################################################################
# Manage network connction feedback
def handle_internet_connected(self, message):
# System came online later after booting
self.enclosure.mouth_reset()
#####################################################################
# Web settings
def on_websettings_changed(self):
# Update eye state if auto_dim_eyes changes...
# if self.settings.get("auto_dim_eyes"):
# self.start_idle_check()
# else:
# # No longer dimming, show open eyes if closed...
# self.cancel_scheduled_event('IdleCheck')
# if self.idle_count > 2:
# self.idle_count = 0
# self.enclosure.eyes_color(self._current_color)
# Update use of wake-up beep
self._sync_wake_beep_setting()
def _sync_wake_beep_setting(self):
from mycroft.configuration.config import (
LocalConf, USER_CONFIG, Configuration
)
config = Configuration.get()
use_beep = self.settings.get("use_listening_beep") is True
if not config['confirm_listening'] == use_beep:
# Update local (user) configuration setting
new_config = {
'confirm_listening': use_beep
}
user_config = LocalConf(USER_CONFIG)
user_config.merge(new_config)
user_config.store()
self.bus.emit(Message('configuration.updated'))
#####################################################################
# Brightness intent interaction
def percent_to_level(self, percent):
""" converts the brigtness value from percentage to
a value arduino can read
Args:
percent (int): interger value from 0 to 100
return:
(int): value form 0 to 30
"""
return int(float(percent)/float(100)*30)
def parse_brightness(self, brightness):
""" parse text for brightness percentage
Args:
brightness (str): string containing brightness level
return:
(int): brightness as percentage (0-100)
"""
try:
# Handle "full", etc.
name = normalize(brightness)
if name in self.brightness_dict:
return self.brightness_dict[name]
if '%' in brightness:
brightness = brightness.replace("%", "").strip()
return int(brightness)
if 'percent' in brightness:
brightness = brightness.replace("percent", "").strip()
return int(brightness)
i = int(brightness)
if i < 0 or i > 100:
return None
if i < 30:
# Assmume plain 0-30 is "level"
return int((i*100.0)/30.0)
# Assume plain 31-100 is "percentage"
return i
except:
return None # failed in an int() conversion
def set_eye_brightness(self, level, speak=True):
""" Actually change hardware eye brightness
Args:
level (int): 0-30, brightness level
speak (bool): when True, speak a confirmation
"""
self.enclosure.eyes_brightness(level)
if speak is True:
percent = int(float(level)*float(100)/float(30))
self.speak_dialog(
'brightness.set', data={'val': str(percent)+'%'})
def _set_brightness(self, brightness):
# brightness can be a number or word like "full", "half"
percent = self.parse_brightness(brightness)
if percent is None:
self.speak_dialog('brightness.not.found.final')
elif int(percent) is -1:
self.handle_auto_brightness(None)
else:
self.auto_brightness = False
self.set_eye_brightness(self.percent_to_level(percent))
@intent_file_handler('brightness.intent')
def handle_brightness(self, message):
""" Intent Callback to set custom eye brightness
Args:
message (dict): messagebus message from intent parser
"""
brightness = (message.data.get('brightness', None) or
self.get_response('brightness.not.found'))
if brightness:
self._set_brightness(brightness)
def _get_auto_time(self):
""" get dawn, sunrise, noon, sunset, and dusk time
returns:
times (dict): dict with associated (datetime, level)
"""
tz = self.location['timezone']['code']
lat = self.location['coordinate']['latitude']
lon = self.location['coordinate']['longitude']
ast_loc = astral.Location()
ast_loc.timezone = tz
ast_loc.lattitude = lat
ast_loc.longitude = lon
user_set_tz = \
timezone(tz).localize(datetime.now()).strftime('%Z')
device_tz = time.tzname
if user_set_tz in device_tz:
sunrise = ast_loc.sun()['sunrise']
noon = ast_loc.sun()['noon']
sunset = ast_loc.sun()['sunset']
else:
secs = int(self.location['timezone']['offset']) / -1000
sunrise = arrow.get(
ast_loc.sun()['sunrise']).shift(
seconds=secs).replace(tzinfo='UTC').datetime
noon = arrow.get(
ast_loc.sun()['noon']).shift(
seconds=secs).replace(tzinfo='UTC').datetime
sunset = arrow.get(
ast_loc.sun()['sunset']).shift(
seconds=secs).replace(tzinfo='UTC').datetime
return {
'Sunrise': (sunrise, 20), # high
'Noon': (noon, 30), # full
'Sunset': (sunset, 5) # dim
}
def schedule_brightness(self, time_of_day, pair):
""" schedule auto brightness with the event scheduler
Args:
time_of_day (str): Sunrise, Noon, Sunset
pair (tuple): (datetime, brightness)
"""
d_time = pair[0]
brightness = pair[1]
now = arrow.now()
arw_d_time = arrow.get(d_time)
data = (time_of_day, brightness)
if now.timestamp > arw_d_time.timestamp:
d_time = arrow.get(d_time).shift(hours=+24)
self.schedule_event(self._handle_eye_brightness_event, d_time,
data=data, name=time_of_day)
else:
self.schedule_event(self._handle_eye_brightness_event, d_time,
data=data, name=time_of_day)
# TODO: this is currently set by voice.
# allow setting from faceplate and web ui
@intent_file_handler('brightness.auto.intent')
def handle_auto_brightness(self, message):
""" brightness varies depending on time of day
Args:
message (dict): messagebus message from intent parser
"""
self.auto_brightness = True
auto_time = self._get_auto_time()
nearest_time_to_now = (float('inf'), None, None)
for time_of_day, pair in auto_time.items():
self.schedule_brightness(time_of_day, pair)
now = arrow.now().timestamp
t = arrow.get(pair[0]).timestamp
if abs(now - t) < nearest_time_to_now[0]:
nearest_time_to_now = (abs(now - t), pair[1], time_of_day)
self.set_eye_brightness(nearest_time_to_now[1], speak=False)
# SSP: I'm disabling this for now. I don't think we
# should announce this every day, it'll get tedious.
#
# tod = nearest_time_to_now[2]
# if tod == 'Sunrise':
# self.speak_dialog('auto.sunrise')
# elif tod == 'Sunset':
# self.speak_dialog('auto.sunset')
# elif tod == 'Noon':
# self.speak_dialog('auto.noon')
def _handle_eye_brightness_event(self, message):
""" wrapper for setting eye brightness from
eventscheduler
Args:
message (dict): messagebus message
"""
if self.auto_brightness is True:
time_of_day = message.data[0]
level = message.data[1]
self.cancel_scheduled_event(time_of_day)
self.set_eye_brightness(level, speak=False)
pair = self._get_auto_time()[time_of_day]
self.schedule_brightness(time_of_day, pair)
#####################################################################
# Device Settings
@intent_file_handler('device.settings.intent')
def handle_device_settings(self, message):
"""
display device settings page
"""
self.gui['state'] = 'settings/settingspage'
self.gui.show_page('all.qml')
@intent_file_handler('device.wifi.settings.intent')
def handle_show_wifi_screen_intent(self, message):
"""
display network selection page
"""
self.gui.clear()
self.gui['state'] = "settings/networking/SelectNetwork"
self.gui.show_page('all.qml')
@intent_file_handler('device.brightness.settings.intent')
def handle_device_brightness_settings(self, message):
"""
display brightness settings page
"""
self.gui['state'] = 'settings/brightness_settings'
self.gui.show_page('all.qml')
@intent_file_handler('device.homescreen.settings.intent')
def handle_device_homescreen_settings(self, message):
"""
display homescreen settings page
"""
screens = [{"screenName": s, "screenID": self.idle_screens[s]}
for s in self.idle_screens]
self.gui['idleScreenList'] = {'screenBlob': screens}
print(self.gui['idleScreenList'])
self.gui['state'] = 'settings/homescreen_settings'
self.gui.show_page('all.qml')
@intent_file_handler('device.ssh.settings.intent')
def handle_device_ssh_settings(self, message):
"""
display ssh settings page
"""
self.gui['state'] = 'settings/ssh_settings'
self.gui.show_page('all.qml')
@intent_file_handler('device.reset.settings.intent')
def handle_device_factory_reset_settings(self, message):
"""
display device factory reset settings page
"""
self.gui['state'] = 'settings/factoryreset_settings'
self.gui.show_page('all.qml')
def handle_device_update_settings(self, message):
"""
display device update settings page
"""
self.gui['state'] = 'settings/updatedevice_settings'
self.gui.show_page('all.qml')
def handle_device_restart_action(self, message):
"""
device restart action
"""
print("PlaceholderRestartAction")
def handle_device_poweroff_action(self, message):
"""
device poweroff action
"""
print("PlaceholderShutdownAction")
#####################################################################
# Device Networking Settings
def handle_show_wifi_pass_screen_intent(self, message):
"""
display network setup page
"""
self.gui['state'] = "settings/networking/NetworkConnect"
self.gui.show_page('all.qml')
self.gui["ConnectionName"] = message.data["ConnectionName"]
self.gui["SecurityType"] = message.data["SecurityType"]
self.gui["DevicePath"] = message.data["DevicePath"]
self.gui["SpecificPath"] = message.data["SpecificPath"]
def handle_show_network_connecting_screen_intent(self, message):
"""
display network connecting state
"""
self.gui['state'] = "settings/networking/Connecting"
self.gui.show_page("all.qml")
def handle_show_network_connected_screen_intent(self, message):
"""
display network connected state
"""
self.gui['state'] = "settings/networking/Success"
self.gui.show_page("all.qml")
def handle_show_network_fail_screen_intent(self, message):
"""
display network failed state
"""
self.gui['state'] = "settings/networking/Fail"
self.gui.show_page("all.qml")
def handle_return_to_networkselection(self):
"""
return to network selection on failure
"""
self.gui['state'] = "settings/networking/SelectNetwork"
self.gui.show_page("all.qml")
def create_skill():
return Mark2()
|
launcher.py | """
Simple experiment implementation
"""
from hops import util
from hops import hdfs as hopshdfs
from hops import tensorboard
from hops import devices
import pydoop.hdfs
import threading
import six
import datetime
import os
run_id = 0
def _launch(sc, map_fun, args_dict=None, local_logdir=False, name="no-name"):
"""
Args:
sc:
map_fun:
args_dict:
local_logdir:
name:
Returns:
"""
global run_id
app_id = str(sc.applicationId)
if args_dict == None:
num_executions = 1
else:
arg_lists = list(args_dict.values())
currentLen = len(arg_lists[0])
for i in range(len(arg_lists)):
if currentLen != len(arg_lists[i]):
raise ValueError('Length of each function argument list must be equal')
num_executions = len(arg_lists[i])
sc.setJobGroup("Launcher", "{} | Running experiment".format(name))
#Each TF task should be run on 1 executor
nodeRDD = sc.parallelize(range(num_executions), num_executions)
#Force execution on executor, since GPU is located on executor global run_id
nodeRDD.foreachPartition(_prepare_func(app_id, run_id, map_fun, args_dict, local_logdir))
print('Finished Experiment \n')
if args_dict == None:
path_to_metric = _get_logdir(app_id) + '/metric'
if pydoop.hdfs.path.exists(path_to_metric):
with pydoop.hdfs.open(path_to_metric, "r") as fi:
metric = float(fi.read())
fi.close()
return metric, _get_logdir(app_id), None
elif num_executions == 1 and not args_dict == None:
arg_count = six.get_function_code(map_fun).co_argcount
arg_names = six.get_function_code(map_fun).co_varnames
argIndex = 0
param_string = ''
while arg_count > 0:
param_name = arg_names[argIndex]
param_val = args_dict[param_name][0]
param_string += str(param_name) + '=' + str(param_val) + '.'
arg_count -= 1
argIndex += 1
param_string = param_string[:-1]
path_to_metric = _get_logdir(app_id) + '/' + param_string + '/metric'
if pydoop.hdfs.path.exists(path_to_metric):
with pydoop.hdfs.open(path_to_metric, "r") as fi:
metric = float(fi.read())
fi.close()
return metric, _get_logdir(app_id), param_string
else:
return None, _get_logdir(app_id), param_string
return None, _get_logdir(app_id), None
def _get_logdir(app_id):
"""
Args:
app_id:
Returns:
"""
global run_id
return hopshdfs._get_experiments_dir() + '/' + app_id + '/launcher/run.' + str(run_id)
#Helper to put Spark required parameter iter in function signature
def _prepare_func(app_id, run_id, map_fun, args_dict, local_logdir):
"""
Args:
app_id:
run_id:
map_fun:
args_dict:
local_logdir:
Returns:
"""
def _wrapper_fun(iter):
"""
Args:
iter:
Returns:
"""
for i in iter:
executor_num = i
tb_pid = 0
tb_hdfs_path = ''
hdfs_exec_logdir = ''
t = threading.Thread(target=devices._print_periodic_gpu_utilization)
if devices.get_num_gpus() > 0:
t.start()
try:
#Arguments
if args_dict:
argcount = six.get_function_code(map_fun).co_argcount
names = six.get_function_code(map_fun).co_varnames
args = []
argIndex = 0
param_string = ''
while argcount > 0:
#Get args for executor and run function
param_name = names[argIndex]
param_val = args_dict[param_name][executor_num]
param_string += str(param_name) + '=' + str(param_val) + '.'
args.append(param_val)
argcount -= 1
argIndex += 1
param_string = param_string[:-1]
hdfs_exec_logdir, hdfs_appid_logdir = hopshdfs._create_directories(app_id, run_id, param_string, 'launcher')
pydoop.hdfs.dump('', os.environ['EXEC_LOGFILE'], user=hopshdfs.project_user())
hopshdfs._init_logger()
tb_hdfs_path, tb_pid = tensorboard._register(hdfs_exec_logdir, hdfs_appid_logdir, executor_num, local_logdir=local_logdir)
gpu_str = '\nChecking for GPUs in the environment' + devices._get_gpu_info()
hopshdfs.log(gpu_str)
print(gpu_str)
print('-------------------------------------------------------')
print('Started running task ' + param_string + '\n')
hopshdfs.log('Started running task ' + param_string)
task_start = datetime.datetime.now()
retval = map_fun(*args)
task_end = datetime.datetime.now()
if retval:
_handle_return(retval, hdfs_exec_logdir)
time_str = 'Finished task ' + param_string + ' - took ' + util._time_diff(task_start, task_end)
print('\n' + time_str)
print('-------------------------------------------------------')
hopshdfs.log(time_str)
else:
hdfs_exec_logdir, hdfs_appid_logdir = hopshdfs._create_directories(app_id, run_id, None, 'launcher')
pydoop.hdfs.dump('', os.environ['EXEC_LOGFILE'], user=hopshdfs.project_user())
hopshdfs._init_logger()
tb_hdfs_path, tb_pid = tensorboard._register(hdfs_exec_logdir, hdfs_appid_logdir, executor_num, local_logdir=local_logdir)
gpu_str = '\nChecking for GPUs in the environment' + devices._get_gpu_info()
hopshdfs.log(gpu_str)
print(gpu_str)
print('-------------------------------------------------------')
print('Started running task\n')
hopshdfs.log('Started running task')
task_start = datetime.datetime.now()
retval = map_fun()
task_end = datetime.datetime.now()
if retval:
_handle_return(retval, hdfs_exec_logdir)
time_str = 'Finished task - took ' + util._time_diff(task_start, task_end)
print('\n' + time_str)
print('-------------------------------------------------------')
hopshdfs.log(time_str)
except:
#Always do cleanup
_cleanup(tb_hdfs_path)
if devices.get_num_gpus() > 0:
t.do_run = False
t.join(20)
raise
finally:
try:
if local_logdir:
local_tb = tensorboard.local_logdir_path
util._store_local_tensorboard(local_tb, hdfs_exec_logdir)
except:
pass
_cleanup(tb_hdfs_path)
if devices.get_num_gpus() > 0:
t.do_run = False
t.join(20)
return _wrapper_fun
def _cleanup(tb_hdfs_path):
"""
Args:
tb_hdfs_path:
Returns:
"""
global experiment_json
handle = hopshdfs.get()
if not tb_hdfs_path == None and not tb_hdfs_path == '' and handle.exists(tb_hdfs_path):
handle.delete(tb_hdfs_path)
hopshdfs._kill_logger()
def _handle_return(val, hdfs_exec_logdir):
"""
Args:
val:
hdfs_exec_logdir:
Returns:
"""
try:
test = int(val)
except:
raise ValueError('Your function needs to return a metric (number) which should be maximized or minimized')
metric_file = hdfs_exec_logdir + '/metric'
fs_handle = hopshdfs.get_fs()
try:
fd = fs_handle.open_file(metric_file, mode='w')
except:
fd = fs_handle.open_file(metric_file, flags='w')
fd.write(str(float(val)).encode())
fd.flush()
fd.close()
|
guitarbot.py | import time, os
import cv2
import numpy as np
import matplotlib.pyplot as plt
from pynput.keyboard import Key, Controller
from modules import screenshot
from queue import Queue
from threading import Thread
def PCA(M, k=2):
x1, x2 = M.shape
if (x1 >= x2): M = M.T
R = np.cov(M - mean(M))
lamb, Vy = np.linalg.eigh(R)
return lamb, Vy[:,:k]
def imshow(A, grid=True):
fig, axs = plt.subplots(1, len(A))
for ax, im in zip(axs, A):
ax.imshow(im, cmap=plt.cm.gray_r)
ax.grid(grid)
def linfit(set):
M = np.matrix([np.ones(len(set)), range(len(set))]).T
theta = (np.linalg.inv(M.T * M) * M.T).dot(set)
return M*theta.T
def euclidian_dist(V, Vt=None):
return np.linalg.norm(V - Vt)
def set_plt_params(figsize=[5,5], figdpi=150, style='default'):
plt.rcParams['figure.figsize'] = figsize
plt.rcParams['figure.dpi'] = figdpi
plt.style.use(style)
def adjust_to_plot(X, i, dim, orientation='horizontal'):
M = []
if orientation == 'horizontal':
for j in range(i):
M.append(X[j:j+1,:].reshape(dim[0], dim[1]))
elif orientation == 'vertical':
for j in range(i):
M.append(X[:,j:j+1].reshape(dim[0], dim[1]))
return M
def normalize(M):
return M/np.linalg.norm(M)
def mean(M):
ux = np.zeros(M[:1,].shape)
for m in M:
ux += m
return ux/len(M)
def cut_img(U, pos, size=(60,80)):
return U[pos[0]:size[0]+pos[0],pos[1]:size[1]+pos[1]]
def pre_processing():
frame = np.array(img)
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) / 255
def perspective_transform(frame, x1, x2, width, height):
M = cv2.getPerspectiveTransform(x1, x2)
return cv2.warpPerspective(frame, M, (width, height))
def play_note(q):
while True:
note = q.get()
keyboard.press(note)
time.sleep(0.012)
keyboard.release(note)
q.task_done()
def sensor(notes):
pressed = False
for detection in notes:
x, y, h, w = detection
centroid = (x + int(w/2), y + int(h/2))
if centroid[1] >= 435 and centroid[1] <= 445:
pressed = True
print(38*'-' + '\nDETECTED: ({}, {})'.format(centroid[0], centroid[1]))
if centroid[0] >= 0 and centroid[0] <= 85:
print('GREEN\n' + 38*'-')
q1.put('a')
return pressed, centroid
elif centroid[0] >= 90 and centroid[0] <= 155:
print('RED\n' + 38*'-')
q1.put('s')
return pressed, centroid
elif centroid[0] >= 160 and centroid[0] <= 225:
print('YELLOW\n' + 38*'-')
q1.put('j')
return pressed, centroid
elif centroid[0] >= 230 and centroid[0] <= 295:
print('BLUE\n' + 38*'-')
q1.put('k')
return pressed, centroid
elif centroid[0] >= 300 and centroid[0] <= 370:
print('ORANGE\n' + 38*'-')
q1.put('l')
return pressed, centroid
return pressed, (0,0)
if __name__ == '__main__':
keyboard = Controller()
nq = 1
q1 = Queue()
worker = Thread(target=play_note, args=(q1,))
worker.setDaemon(True)
worker.start()
q1.join()
# size of the template
w, h = (50, 60)
print(38*'-' + '\nLoading templates...')
templates_path = '../images/classification/'
files = os.listdir(templates_path)
A = np.zeros([len(files), w * h])
for index, file in enumerate(files):
note = os.path.join(templates_path, file)
imgc = cv2.imread(note, cv2.IMREAD_GRAYSCALE) / 256
imgc = cv2.resize(imgc, (h, w), interpolation = cv2.INTER_AREA)
A[index:w*h] = imgc.reshape(w*h)
print('{} templates loaded & ready for classification'.format(len(A)))
print(38*'-' + '\nCalculating a base for templates...')
lamb, V = PCA(A.T, k=20)
U = mean(V.T.dot(A))
R = mean(A)
# coords of the top left corner
# screen resolution of the area to be recorded
# width and height of the processed frame
x0, y0 = (40, 300)
res = (820, 580)
W, H = (380, 550)
# position of the inner stage, where the notes are placed
t1 = [330,230]
t2 = [490,230]
t3 = [205,530]
t4 = [615,530]
pts1 = np.float32([t1, t2, t3, t4])
pts2 = np.float32([[0,0], [W,0], [0,H], [W,H]])
# this is the frame search, if stepx, stepy < w, h the exceeding sizes
# will overlap the search window making the classification more accurate
# in exchange for computing power
stepx, stepy = (20, 20)
maxx, maxy = (17, 26)
threshold = 11.15
grouping = 0.62
factor = 1
pr = 1
dim = (int(W * (pr)), int(H * pr))
print('Starting classification...')
start = time.time(); l = 0; avgt = 0.0
detected = 0
while True:
locations = []
d = np.zeros(maxx*maxy); k = 0
start = time.time(); l += 1
img = screenshot.grab_screen(x0, y0, res[0] + x0, res[1] + y0)
frame = np.array(img)
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) / 256
img_pad = perspective_transform(frame, pts1, pts2, W, H)
img_screenshot = img_pad.copy()
for i in range(maxy):
for j in range(maxx):
dx = (stepx*i, w + (stepx*i))
dy = (stepy*j, h + (stepy*j))
im = img_pad[dx[0]:dx[1], dy[0]:dy[1]]
L = mean(U * (im.reshape(w*h) - R))
dist = euclidian_dist(U, L)
d[k] = dist; k += 1
if dist < threshold:
locations.append([dy[0]+5, dx[0]+5, int(w*0.7), int(h*0.78)])
locations.append([dy[0]+5, dx[0]+5, int(w*0.7), int(h*0.78)])
rects, _ = cv2.groupRectangles(locations, factor, grouping)
for (x, y, w1, h1) in rects:
top_left = (x, y)
bottom_right = (x + h1, y + w1)
cv2.rectangle(img_pad, top_left, bottom_right, (255,255,255), 2)
# pos, center = sensor(rects)
#
# if pos:
# cv2.circle(img_pad, center, 15, (255,255,255), thickness=3)
# detected += 1
avgt += (time.time() - start)
out = cv2.resize(img_pad, dim, interpolation = cv2.INTER_AREA)
key = cv2.waitKey(1)
if key == ord('q'):
print(38*'-' + '\nFrame time = {:.2f}s; average FPS = {:.2f}'.format(avgt/l, l/(avgt)))
print('Dist. = {:.2f}'.format(d.mean()))
print('{} notes detected'.format(detected))
print('End program.\n'+ 38*'-')
cv2.destroyAllWindows()
break
elif key == ord('s'):
path = '../images/screenshots/screenshot_{}_stage.png'.format(int(time.time()))
output = np.array(img_screenshot * 256, dtype=np.uint8)
cv2.imwrite(path, output)
print('Screenshot taken saved at ' + path)
title = 'Screen Capture (Guitar Flash 3) {}x{}'.format(dim[0], dim[1])
cv2.imshow(title, out)
|
stubs.py | from pytest import fixture
@fixture(scope="session", autouse=True)
def stub_server(request):
from multiprocessing import Process
from stubilous.server import run
from stubilous.builder import Builder
builder = Builder()
builder.server(host="localhost", port=9998)
builder.route("GET", "/health")("Ok", 200)
config = builder.build()
proc = Process(target=run, args=(config,))
def on_close():
proc.terminate()
proc.join()
request.addfinalizer(on_close)
proc.start()
return proc
|
__init__.py |
import websocket
import threading
import time
class DanmuClient:
def __init__(self):
self.reg_datas = None
self.ws = None
self.cb = None
def start(self, url, cb):
ws_url, self.reg_datas = self.get_ws_info(url)
self.cb = cb
self.ws = self.connect(ws_url)
def stop(self):
if self.ws:
self.ws.close()
print("self.ws.close()~~~~~~~~~~~~~~")
def connect(self, ws_url):
return websocket.WebSocketApp(ws_url,
on_open=self.on_open,
on_message=self.on_message,
on_error=self.on_error,
on_close=self.on_close)
def on_open(self, ws):
print("### opened ###")
for reg_data in self.reg_datas:
self.ws.send(reg_data)
t = threading.Thread(target=self.heartbeat_thread, daemon=True)
t.start()
def on_message(self, ws, message):
msgs = self.decode_msg(message)
for m in msgs:
# print(m)
if m["msg_type"] == 'danmaku':
if self.cb:
self.cb(m["content"])
def on_error(self, ws, error):
print(error)
def on_close(self, ws, close_status_code, close_msg):
print(f"### closed ### {close_status_code=}, {close_msg=}")
self.ws = None
def heartbeat_thread(self):
t = 0.0
while not self.ws is None:
if time.time() - t > self.heartbeatInterval:
self.ws.send(self.heartbeat)
t = time.time()
print(f'send heartbeat~~~~~~~~~~~~~~~')
time.sleep(0.1)
def run(self):
t = threading.Thread(target=self.ws.run_forever, daemon=True)
t.start()
|
main.py | #! /usr/bin/env python
# -*- coding: UTF-8 -*-
import wx
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import os
import time
import threading
import inspect
import ctypes
from run import runcore
from ui import uidef
from ui import uilang
g_main_win = None
g_task_detectUsbhid = None
g_task_uartAllInOneAction = None
g_task_usbAllInOneAction = [None] * uidef.kMaxMfgBoards
g_task_increaseGauge = None
g_usbAutoDownloadResult_success = [0] * uidef.kMaxMfgBoards
g_usbAutoDownloadResult_total = [0] * uidef.kMaxMfgBoards
kRetryPingTimes = 5
kBootloaderType_Rom = 0
kBootloaderType_Flashloader = 1
def _async_raise(tid, exctype):
tid = ctypes.c_long(tid)
if not inspect.isclass(exctype):
exctype = type(exctype)
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
if res == 0:
raise ValueError("invalid thread id")
elif res != 1:
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
raise SystemError("PyThreadState_SetAsyncExc failed")
class flashMain(runcore.flashRun):
def __init__(self, parent):
runcore.flashRun.__init__(self, parent)
self.lastTime = None
self.isUartAllInOneActionTaskPending = False
self.isUsbAllInOneActionTaskPending = [False] * uidef.kMaxMfgBoards
def _startGaugeTimer( self ):
self.lastTime = time.time()
self.initGauge()
def _stopGaugeTimer( self ):
self.deinitGauge()
self.updateCostTime()
def callbackSetMcuDevice( self, event ):
self.setTargetSetupValue()
self.createMcuTarget()
self._setUartUsbPort()
def callbackSetConnectedBoards( self, event ):
self.setMcuBoards()
def callbackSwitchSerialPortIndex( self, event ):
self.setSerialPortIndex()
def _setUartUsbPort( self, deviceIndex=0 ):
usbIdList = self.getUsbid()
retryToDetectUsb = False
self.setPortSetupValue(deviceIndex, self.connectStage[deviceIndex], usbIdList, retryToDetectUsb )
def callbackSetUartPort( self, event ):
self._setUartUsbPort()
def callbackSetUsbhidPort( self, event ):
self._setUartUsbPort()
def callbackSetPortVid( self, event ):
self.updatePortSetupValue()
def callbackSetBaudPid( self, event ):
self.updatePortSetupValue()
def _retryToPingBootloader( self, bootType, deviceIndex=0 ):
pingStatus = False
pingCnt = kRetryPingTimes
while (not pingStatus) and pingCnt > 0:
if bootType == kBootloaderType_Rom:
self.writeDebugLog("Entering pingRom(), deviceIndex = " + str(deviceIndex) + ", usb path is " + self.usbDevicePath[deviceIndex]['rom'])
pingStatus = self.pingRom(deviceIndex)
elif bootType == kBootloaderType_Flashloader:
# This is mainly for RT1170 flashloader, but it is also ok for other RT devices
if self.isUartPortSelected:
time.sleep(3)
if self.usbDevicePath[deviceIndex]['flashloader'] != None:
self.connectToDevice(self.connectStage[deviceIndex], deviceIndex)
self.writeDebugLog("Entering pingFlashloader(), deviceIndex = " + str(deviceIndex) + ", usb path is " + self.usbDevicePath[deviceIndex]['flashloader'])
pingStatus = self.pingFlashloader(deviceIndex)
else:
pass
if pingStatus:
break
pingCnt = pingCnt - 1
time.sleep(2)
return pingStatus
def _doubleCheckBootModeError( self ):
if (self.mcuSeries == uidef.kMcuSeries_iMXRT10yy) or \
(self.mcuSeries == uidef.kMcuSeries_iMXRT11yy):
self.setInfoStatus(uilang.kMsgLanguageContentDict['connectError_doubleCheckBmod'][self.languageIndex])
elif (self.mcuSeries == uidef.kMcuSeries_iMXRTxxx):
self.setInfoStatus(uilang.kMsgLanguageContentDict['connectError_doubleCheckIsp'][self.languageIndex])
elif (self.mcuSeries == uidef.kMcuSeries_LPC):
self.setInfoStatus(uilang.kMsgLanguageContentDict['connectError_doubleCheckIspBoot'][self.languageIndex])
elif (self.mcuSeries == uidef.kMcuSeries_Kinetis):
self.setInfoStatus(uilang.kMsgLanguageContentDict['connectError_doubleCheckFopt'][self.languageIndex])
else:
pass
def _connectFailureHandler( self, deviceIndex=0 ):
self.connectStage[deviceIndex] = uidef.kConnectStage_Rom
self.updateConnectStatus('red')
usbIdList = self.getUsbid()
self.setPortSetupValue(deviceIndex, self.connectStage[deviceIndex], usbIdList, False )
self.setInfoStatus(uilang.kMsgLanguageContentDict['connectError_checkUsbCable'][self.languageIndex])
def _connectStateMachine( self, deviceIndex=0 ):
retryToDetectUsb = False
connectSteps = 0
if (self.mcuSeries == uidef.kMcuSeries_iMXRT10yy) or \
(self.mcuSeries == uidef.kMcuSeries_iMXRT11yy):
connectSteps = 3
if (self.mcuSeries == uidef.kMcuSeries_iMXRTxxx) or \
(self.mcuSeries == uidef.kMcuSeries_LPC) or \
(self.mcuSeries == uidef.kMcuSeries_Kinetis):
connectSteps = 2
else:
pass
isConnectionFailureOnce = False
while connectSteps:
if not self.updatePortSetupValue(deviceIndex, retryToDetectUsb):
self._connectFailureHandler(deviceIndex)
if not isConnectionFailureOnce:
isConnectionFailureOnce = True
continue
else:
return False
if self.connectStage[deviceIndex] == uidef.kConnectStage_Rom:
self.connectToDevice(self.connectStage[deviceIndex], deviceIndex)
if self._retryToPingBootloader(kBootloaderType_Rom, deviceIndex):
if (self.mcuSeries == uidef.kMcuSeries_iMXRT10yy) or \
(self.mcuSeries == uidef.kMcuSeries_iMXRT11yy):
self.getMcuDeviceHabStatus(deviceIndex)
if self.jumpToFlashloader(deviceIndex):
self.connectStage[deviceIndex] = uidef.kConnectStage_Flashloader
usbIdList = self.getUsbid()
self.setPortSetupValue(deviceIndex, self.connectStage[deviceIndex], usbIdList, True )
else:
self.updateConnectStatus('red')
self.setInfoStatus(uilang.kMsgLanguageContentDict['connectError_failToJumpToFl'][self.languageIndex])
return False
elif (self.mcuSeries == uidef.kMcuSeries_iMXRTxxx) or \
(self.mcuSeries == uidef.kMcuSeries_LPC) or \
(self.mcuSeries == uidef.kMcuSeries_Kinetis):
self.updateConnectStatus('green')
self.connectStage[deviceIndex] = uidef.kConnectStage_Ready
else:
pass
else:
self.updateConnectStatus('red')
self._doubleCheckBootModeError()
return False
elif self.connectStage[deviceIndex] == uidef.kConnectStage_Flashloader:
self.connectToDevice(self.connectStage[deviceIndex], deviceIndex)
if self._retryToPingBootloader(kBootloaderType_Flashloader, deviceIndex):
self.updateConnectStatus('green')
self.connectStage[deviceIndex] = uidef.kConnectStage_Ready
else:
self.setInfoStatus(uilang.kMsgLanguageContentDict['connectError_failToPingFl'][self.languageIndex])
self._connectFailureHandler(deviceIndex)
return False
elif self.connectStage[deviceIndex] == uidef.kConnectStage_Ready:
if connectSteps == 1:
self.setInfoStatus(uilang.kMsgLanguageContentDict['connectInfo_readyForDownload'][self.languageIndex])
return True
else:
if self._retryToPingBootloader(kBootloaderType_Flashloader, deviceIndex):
self.setInfoStatus(uilang.kMsgLanguageContentDict['connectInfo_readyForDownload'][self.languageIndex])
return True
else:
self.connectStage[deviceIndex] = uidef.kConnectStage_Rom
connectSteps += 1
else:
pass
connectSteps -= 1
def task_doUartAllInOneAction( self ):
while True:
if self.isUartAllInOneActionTaskPending:
self._doUartAllInOneAction()
self.isUartAllInOneActionTaskPending = False
self._stopGaugeTimer()
time.sleep(1)
def _doUartAllInOneAction( self ):
if len(self.sbAppFiles) == 0:
self.updateConnectStatus('red')
self.setInfoStatus(uilang.kMsgLanguageContentDict['downloadError_notValidImage'][self.languageIndex])
return
boards = len(self.uartComPort)
operations = 0
successes = 0
for board in range(boards):
if self.uartComPort[board] == None:
continue
operations += 1
if self._connectStateMachine(board):
for i in range(len(self.sbAppFiles)):
if self.flashSbImage(self.sbAppFiles[i], board):
if i == len(self.sbAppFiles) - 1:
successes += 1
self.updateConnectStatus('blue')
self.setInfoStatus(uilang.kMsgLanguageContentDict['downloadInfo_success'][self.languageIndex])
else:
self.updateConnectStatus('red')
break
self.resetMcuDevice(board)
self.connectStage[board] = uidef.kConnectStage_Rom
self._setUartUsbPort()
self.setDownloadOperationResults(operations, successes)
self.updateConnectStatus('black')
def _doUsbxAllInOneAction( self, deviceIndex=0 ):
while True:
if self.isUsbAllInOneActionTaskPending[deviceIndex]:
self._doUsbAutoAllInOneAction(deviceIndex)
self.isUsbAllInOneActionTaskPending[deviceIndex] = False
if (deviceIndex == 0) and (not self.isDymaticUsbDetection):
self._stopGaugeTimer()
else:
if ((deviceIndex == 0) and self.isDymaticUsbDetection) or \
(deviceIndex != 0):
try:
if self.usbDevicePath[deviceIndex]['rom'] != None:
self.writeDebugLog("Entering task_doUsbxAllInOneAction(), Set Pending flag " + str(deviceIndex) + ", usb path is " + self.usbDevicePath[deviceIndex]['rom'])
self.isUsbAllInOneActionTaskPending[deviceIndex] = True
global g_usbAutoDownloadResult_success
global g_usbAutoDownloadResult_total
self.updateSlotStatus(deviceIndex, 'green', g_usbAutoDownloadResult_success[deviceIndex], g_usbAutoDownloadResult_total[deviceIndex])
else:
pass
except:
pass
time.sleep(1)
def task_doUsb0AllInOneAction( self ):
self._doUsbxAllInOneAction(0)
def task_doUsb1AllInOneAction( self ):
self._doUsbxAllInOneAction(1)
def task_doUsb2AllInOneAction( self ):
self._doUsbxAllInOneAction(2)
def task_doUsb3AllInOneAction( self ):
self._doUsbxAllInOneAction(3)
def task_doUsb4AllInOneAction( self ):
self._doUsbxAllInOneAction(4)
def task_doUsb5AllInOneAction( self ):
self._doUsbxAllInOneAction(5)
def task_doUsb6AllInOneAction( self ):
self._doUsbxAllInOneAction(6)
def task_doUsb7AllInOneAction( self ):
self._doUsbxAllInOneAction(7)
def _doUsbAutoAllInOneAction( self, deviceIndex=0 ):
global g_usbAutoDownloadResult_success
global g_usbAutoDownloadResult_total
if len(self.sbAppFiles) == 0:
self.updateConnectStatus('red')
if not self.isDymaticUsbDetection:
self.setInfoStatus(uilang.kMsgLanguageContentDict['downloadError_notValidImage'][self.languageIndex])
return
successes = 0
g_usbAutoDownloadResult_total[deviceIndex] += 1
if self._connectStateMachine(deviceIndex):
for i in range(len(self.sbAppFiles)):
if self.flashSbImage(self.sbAppFiles[i], deviceIndex):
if i == len(self.sbAppFiles) - 1:
successes = 1
g_usbAutoDownloadResult_success[deviceIndex] += 1
self.updateSlotStatus(deviceIndex, 'blue', g_usbAutoDownloadResult_success[deviceIndex], g_usbAutoDownloadResult_total[deviceIndex])
self.updateConnectStatus('blue')
if not self.isDymaticUsbDetection:
self.setInfoStatus(uilang.kMsgLanguageContentDict['downloadInfo_success'][self.languageIndex])
else:
self.updateConnectStatus('red')
self.writeInfoLog("Slot " + str(deviceIndex) + " failure:" + str(g_usbAutoDownloadResult_total[deviceIndex]))
self.updateSlotStatus(deviceIndex, 'red', g_usbAutoDownloadResult_success[deviceIndex], g_usbAutoDownloadResult_total[deviceIndex])
break
if not self.isDymaticUsbDetection:
self.resetMcuDevice(deviceIndex)
time.sleep(2)
else:
self.writeInfoLog("Slot " + str(deviceIndex) + " failure: " + str(g_usbAutoDownloadResult_total[deviceIndex]))
self.updateSlotStatus(deviceIndex, 'red', g_usbAutoDownloadResult_success[deviceIndex], g_usbAutoDownloadResult_total[deviceIndex])
self.connectStage[deviceIndex] = uidef.kConnectStage_Rom
self._setUartUsbPort(deviceIndex)
self.isUsbhidConnected[deviceIndex] = False
if self.isDymaticUsbDetection:
self.usbDevicePath[deviceIndex]['rom'] = None
# Never clear 'flashloader' here, it will be used to help insert usb device
#self.usbDevicePath[deviceIndex]['flashloader'] = None
else:
self.updateConnectStatus('black')
self.setDownloadOperationResults(1, successes)
self.initUsbDevicePath()
# Back to set gray color for slot button
time.sleep(0.5)
self.updateSlotStatus(deviceIndex, 'gray', g_usbAutoDownloadResult_success[deviceIndex], g_usbAutoDownloadResult_total[deviceIndex])
def callbackAllInOneAction( self, event ):
if self.isUartPortSelected:
self.isUartAllInOneActionTaskPending = True
self._startGaugeTimer()
elif self.isUsbhidPortSelected and (not self.isDymaticUsbDetection):
self.isUsbAllInOneActionTaskPending[0] = True
self._startGaugeTimer()
else:
pass
def callbackChangedAppFile( self, event ):
self.getUserAppFilePath()
self.setCostTime(0)
self.setDownloadOperationResults(0)
self.updateConnectStatus('black')
def callbackChangedAppFolder( self, event ):
self.getUserAppFilePath()
if os.path.isfile(self.sbAppFilePath):
self.resetUserAppFolderPath()
self.setInfoStatus(uilang.kMsgLanguageContentDict['downloadError_clearImageFileFirst'][self.languageIndex])
else:
self.getUserAppFolderPath()
self.setCostTime(0)
self.setDownloadOperationResults(0)
self.updateConnectStatus('black')
def _stopTask( self, thread ):
_async_raise(thread.ident, SystemExit)
def _deinitToolToExit( self ):
self._stopTask(g_task_detectUsbhid)
self._stopTask(g_task_uartAllInOneAction)
self._stopTask(g_task_usbAllInOneAction[0])
self._stopTask(g_task_increaseGauge)
global g_main_win
g_main_win.Show(False)
try:
self.Destroy()
except:
pass
self.closeInfoLog()
self.closeDebugLog()
def callbackExit( self, event ):
self._deinitToolToExit()
def callbackClose( self, event ):
self._deinitToolToExit()
def callbackSetUsbDetectionAsDynamic( self, event ):
self.setUsbDetection()
def callbackSetUsbDetectionAsStatic( self, event ):
self.setUsbDetection()
def callbackSetLanguageAsEnglish( self, event ):
self.setLanguage()
def callbackSetLanguageAsChinese( self, event ):
self.setLanguage()
def callbackShowHomePage( self, event ):
msgText = ((uilang.kMsgLanguageContentDict['homePage_info'][self.languageIndex]))
wx.MessageBox(msgText, uilang.kMsgLanguageContentDict['homePage_title'][self.languageIndex], wx.OK | wx.ICON_INFORMATION)
def callbackShowAboutAuthor( self, event ):
msgText = ((uilang.kMsgLanguageContentDict['aboutAuthor_author'][self.languageIndex]) +
(uilang.kMsgLanguageContentDict['aboutAuthor_email1'][self.languageIndex]) +
(uilang.kMsgLanguageContentDict['aboutAuthor_email2'][self.languageIndex]) +
(uilang.kMsgLanguageContentDict['aboutAuthor_blog'][self.languageIndex]))
wx.MessageBox(msgText, uilang.kMsgLanguageContentDict['aboutAuthor_title'][self.languageIndex], wx.OK | wx.ICON_INFORMATION)
def callbackShowRevisionHistory( self, event ):
msgText = ((uilang.kMsgLanguageContentDict['revisionHistory_v1_0_0'][self.languageIndex]) +
(uilang.kMsgLanguageContentDict['revisionHistory_v2_0_0'][self.languageIndex]) +
(uilang.kMsgLanguageContentDict['revisionHistory_v3_0_0'][self.languageIndex]) +
(uilang.kMsgLanguageContentDict['revisionHistory_v3_1_0'][self.languageIndex]))
wx.MessageBox(msgText, uilang.kMsgLanguageContentDict['revisionHistory_title'][self.languageIndex], wx.OK | wx.ICON_INFORMATION)
if __name__ == '__main__':
app = wx.App()
g_main_win = flashMain(None)
g_main_win.SetTitle(u"NXP MCU Boot Flasher v3.1.0")
g_main_win.Show()
g_task_detectUsbhid = threading.Thread(target=g_main_win.task_doDetectUsbhid)
g_task_detectUsbhid.setDaemon(True)
g_task_detectUsbhid.start()
g_task_uartAllInOneAction = threading.Thread(target=g_main_win.task_doUartAllInOneAction)
g_task_uartAllInOneAction.setDaemon(True)
g_task_uartAllInOneAction.start()
g_task_usbAllInOneAction[0] = threading.Thread(target=g_main_win.task_doUsb0AllInOneAction)
g_task_usbAllInOneAction[0].setDaemon(True)
g_task_usbAllInOneAction[0].start()
g_task_usbAllInOneAction[1] = threading.Thread(target=g_main_win.task_doUsb1AllInOneAction)
g_task_usbAllInOneAction[1].setDaemon(True)
g_task_usbAllInOneAction[1].start()
g_task_usbAllInOneAction[2] = threading.Thread(target=g_main_win.task_doUsb2AllInOneAction)
g_task_usbAllInOneAction[2].setDaemon(True)
g_task_usbAllInOneAction[2].start()
g_task_usbAllInOneAction[3] = threading.Thread(target=g_main_win.task_doUsb3AllInOneAction)
g_task_usbAllInOneAction[3].setDaemon(True)
g_task_usbAllInOneAction[3].start()
g_task_usbAllInOneAction[4] = threading.Thread(target=g_main_win.task_doUsb4AllInOneAction)
g_task_usbAllInOneAction[4].setDaemon(True)
g_task_usbAllInOneAction[4].start()
g_task_usbAllInOneAction[5] = threading.Thread(target=g_main_win.task_doUsb5AllInOneAction)
g_task_usbAllInOneAction[5].setDaemon(True)
g_task_usbAllInOneAction[5].start()
g_task_usbAllInOneAction[6] = threading.Thread(target=g_main_win.task_doUsb6AllInOneAction)
g_task_usbAllInOneAction[6].setDaemon(True)
g_task_usbAllInOneAction[6].start()
g_task_usbAllInOneAction[7] = threading.Thread(target=g_main_win.task_doUsb7AllInOneAction)
g_task_usbAllInOneAction[7].setDaemon(True)
g_task_usbAllInOneAction[7].start()
g_task_increaseGauge = threading.Thread(target=g_main_win.task_doIncreaseGauge)
g_task_increaseGauge.setDaemon(True)
g_task_increaseGauge.start()
app.MainLoop()
|
pir.py | #! /usr/bin/env python3
import RPi.GPIO as GPIO
import time
import threading
import blinkt
import colorsys
import numpy as np
from sys import exit
GPIO.setmode(GPIO.BCM)
PIR_PIN = 21
GPIO.setup(PIR_PIN, GPIO.IN)
class Timer():
def __init__(self):
self.started = None
def start(self):
self.started = time.time()
def stop(self):
self.started = None
def elapsed(self):
if self.started:
return time.time() - self.started
return 0
timer = Timer()
motion_detected = False
threads_active = False
larson_on = False
pulse_on = False
def larson():
REDS = [0, 0, 0, 0, 0, 16, 64, 255, 64, 16, 0, 0, 0, 0, 0, 0]
start_time = time.time()
while threads_active:
if larson_on:
# Sine wave, spends a little longer at min/max
# delta = (time.time() - start_time) * 8
# offset = int(round(((math.sin(delta) + 1) / 2) * (blinkt.NUM_PIXELS - 1)))
# Triangle wave, a snappy ping-pong effect
delta = (time.time() - start_time) * 16
offset = int(abs((delta % len(REDS)) - blinkt.NUM_PIXELS))
for i in range(blinkt.NUM_PIXELS):
blinkt.set_pixel(i, REDS[offset + i], 0, 0)
blinkt.show()
time.sleep(0.1)
def pulse():
def make_gaussian(fwhm):
x = np.arange(0, blinkt.NUM_PIXELS, 1, float)
y = x[:, np.newaxis]
x0, y0 = 3.5, 3.5
fwhm = fwhm
gauss = np.exp(-4 * np.log(2) * ((x - x0) ** 2 + (y - y0) ** 2) / fwhm ** 2)
return gauss
while threads_active:
if pulse_on:
for z in list(range(1, 10)[::-1]) + list(range(1, 10)):
fwhm = 5.0 / z
gauss = make_gaussian(fwhm)
start = time.time()
y = 4
for x in range(blinkt.NUM_PIXELS):
h = 0.5
s = 1.0
v = gauss[x, y]
rgb = colorsys.hsv_to_rgb(h, s, v)
r, g, b = [int(255.0 * i) for i in rgb]
blinkt.set_pixel(x, r, g, b)
blinkt.show()
end = time.time()
t = end - start
if t < 0.04:
time.sleep(0.04 - t)
else:
time.sleep(0.1)
def motion(pir_pin):
global motion_detected
motion_detected = GPIO.input(pir_pin)
timer.start()
blinkt.set_clear_on_exit()
larson_thread = threading.Thread(target=larson)
pulse_thread = threading.Thread(target=pulse)
print("Blinkt motion sensor (CTRL+C to exit)")
try:
threads_active = True
larson_thread.start()
pulse_thread.start()
GPIO.add_event_detect(PIR_PIN, GPIO.BOTH, callback=motion)
while True:
if motion_detected:
# larson for first 10 seconds then pulse
if 0 < timer.elapsed() < 10:
larson_on = True
pulse_on = False
else:
larson_on = False
pulse_on = True
else:
# larson for 5 seconds after motion stops
if 0 < timer.elapsed() < 5:
larson_on = True
pulse_on = False
else:
if larson_on:
larson_on = False
pulse_on = False
time.sleep(0.2)
blinkt.clear()
blinkt.show()
time.sleep(1)
except KeyboardInterrupt:
print("\nQuit")
threads_active = False
larson_thread.join()
pulse_thread.join()
GPIO.cleanup()
|
controller.py | from numpy import true_divide
from model import Reminder
from view import ViewBase
import logging
import threading
import time
class Controller():
def __init__(self, reminder, view):
self.reminder_ = reminder
self.view_ = view
# Daemon thread that runs in backround.
self.threads = list()
self.poll = True
self.thread_wait = threading.Thread(target=self.run_every_x_seconds, args=(1, 2), daemon=True)
self.threads.append(self.thread_wait)
self.thread_wait.start()
def run_every_x_seconds(self, name, seconds):
while(1):
logging.info("Thread %s: starting", name)
time.sleep(seconds)
self.poll = True
logging.info("Thread %s: finishing", name)
def requestPoll(self):
#self.poller
pass
def showAll(self):
#gets list of all Person objects
people_in_db = self.reminder_.getAll()
#calls view
return self.view_.showAllView(people_in_db)
def input(self):
if(self.poll):
self.poll = False
return True
return False
def start(self):
self.view_.startView()
poll = self.input()
if poll:
return self.showAll()
else:
return self.view_.endView()
def updateView(self) ->bool:
"""
Intitiate view if model requests it
"""
if self.reminder_.requestPoll():
self.showAll()
if __name__ == "__main__":
from model import CalendarReminder
from view import GUIView
format = "%(asctime)s: %(message)s"
logging.basicConfig(format=format, level=logging.INFO,
datefmt="%H:%M:%S")
controller = Controller(reminder = CalendarReminder(), view = GUIView())
#running controller function
while(1):
controller.start() |
test_flush.py | import time
import pdb
import threading
import logging
from multiprocessing import Pool, Process
import pytest
from utils import *
dim = 128
segment_row_count = 5000
index_file_size = 10
collection_id = "test_flush"
DELETE_TIMEOUT = 60
nprobe = 1
tag = "1970-01-01"
top_k = 1
nb = 6000
tag = "partition_tag"
field_name = "float_vector"
entity = gen_entities(1)
entities = gen_entities(nb)
raw_vector, binary_entity = gen_binary_entities(1)
raw_vectors, binary_entities = gen_binary_entities(nb)
default_fields = gen_default_fields()
default_single_query = {
"bool": {
"must": [
{"vector": {field_name: {"topk": 10, "query": gen_vectors(1, dim),
"params": {"nprobe": 10}}}}
]
}
}
class TestFlushBase:
"""
******************************************************************
The following cases are used to test `flush` function
******************************************************************
"""
@pytest.fixture(
scope="function",
params=gen_simple_index()
)
def get_simple_index(self, request, connect):
if str(connect._cmd("mode")[1]) == "GPU":
if request.param["index_type"] not in ivf():
pytest.skip("Only support index_type: idmap/flat")
return request.param
@pytest.fixture(
scope="function",
params=gen_single_filter_fields()
)
def get_filter_field(self, request):
yield request.param
@pytest.fixture(
scope="function",
params=gen_single_vector_fields()
)
def get_vector_field(self, request):
yield request.param
def test_flush_collection_not_existed(self, connect, collection):
'''
target: test flush, params collection_name not existed
method: flush, with collection not existed
expected: error raised
'''
collection_new = gen_unique_str("test_flush_1")
with pytest.raises(Exception) as e:
connect.flush([collection_new])
def test_flush_empty_collection(self, connect, collection):
'''
method: flush collection with no vectors
expected: no error raised
'''
ids = connect.insert(collection, entities)
assert len(ids) == nb
status = connect.delete_entity_by_id(collection, ids)
assert status.OK()
res = connect.count_entities(collection)
assert 0 == res
# with pytest.raises(Exception) as e:
# connect.flush([collection])
# TODO
@pytest.mark.level(2)
def test_add_partition_flush(self, connect, id_collection):
'''
method: add entities into partition in collection, flush serveral times
expected: the length of ids and the collection row count
'''
# vector = gen_vector(nb, dim)
connect.create_partition(id_collection, tag)
# vectors = gen_vectors(nb, dim)
ids = [i for i in range(nb)]
ids = connect.insert(id_collection, entities, ids)
connect.flush([id_collection])
res_count = connect.count_entities(id_collection)
assert res_count == nb
ids = connect.insert(id_collection, entities, ids, partition_tag=tag)
assert len(ids) == nb
connect.flush([id_collection])
res_count = connect.count_entities(id_collection)
assert res_count == nb * 2
# TODO
@pytest.mark.level(2)
def test_add_partitions_flush(self, connect, id_collection):
'''
method: add entities into partitions in collection, flush one
expected: the length of ids and the collection row count
'''
# vectors = gen_vectors(nb, dim)
tag_new = gen_unique_str()
connect.create_partition(id_collection, tag)
connect.create_partition(id_collection, tag_new)
ids = [i for i in range(nb)]
ids = connect.insert(id_collection, entities, ids, partition_tag=tag)
connect.flush([id_collection])
ids = connect.insert(id_collection, entities, ids, partition_tag=tag_new)
connect.flush([id_collection])
res = connect.count_entities(id_collection)
assert res == 2 * nb
# TODO
@pytest.mark.level(2)
def test_add_collections_flush(self, connect, id_collection):
'''
method: add entities into collections, flush one
expected: the length of ids and the collection row count
'''
collection_new = gen_unique_str()
default_fields = gen_default_fields(False)
connect.create_collection(collection_new, default_fields)
connect.create_partition(id_collection, tag)
connect.create_partition(collection_new, tag)
# vectors = gen_vectors(nb, dim)
ids = [i for i in range(nb)]
ids = connect.insert(id_collection, entities, ids, partition_tag=tag)
ids = connect.insert(collection_new, entities, ids, partition_tag=tag)
connect.flush([id_collection])
connect.flush([collection_new])
res = connect.count_entities(id_collection)
assert res == nb
res = connect.count_entities(collection_new)
assert res == nb
# TODO
@pytest.mark.level(2)
def test_add_collections_fields_flush(self, connect, id_collection, get_filter_field, get_vector_field):
'''
method: create collection with different fields, and add entities into collections, flush one
expected: the length of ids and the collection row count
'''
nb_new = 5
filter_field = get_filter_field
vector_field = get_vector_field
collection_new = gen_unique_str("test_flush")
fields = {
"fields": [filter_field, vector_field],
"segment_row_count": segment_row_count,
"auto_id": False
}
connect.create_collection(collection_new, fields)
connect.create_partition(id_collection, tag)
connect.create_partition(collection_new, tag)
# vectors = gen_vectors(nb, dim)
entities_new = gen_entities_by_fields(fields["fields"], nb_new, dim)
ids = [i for i in range(nb)]
ids_new = [i for i in range(nb_new)]
ids = connect.insert(id_collection, entities, ids, partition_tag=tag)
ids = connect.insert(collection_new, entities_new, ids_new, partition_tag=tag)
connect.flush([id_collection])
connect.flush([collection_new])
res = connect.count_entities(id_collection)
assert res == nb
res = connect.count_entities(collection_new)
assert res == nb_new
@pytest.mark.skip(reason="search not support yet")
def test_add_flush_multiable_times(self, connect, collection):
'''
method: add entities, flush serveral times
expected: no error raised
'''
# vectors = gen_vectors(nb, dim)
ids = connect.insert(collection, entities)
for i in range(10):
connect.flush([collection])
res = connect.count_entities(collection)
assert res == len(ids)
# query_vecs = [vectors[0], vectors[1], vectors[-1]]
res = connect.search(collection, default_single_query)
logging.getLogger().debug(res)
assert res
# TODO
@pytest.mark.level(2)
# TODO: stable case
def test_add_flush_auto(self, connect, id_collection):
'''
method: add entities
expected: no error raised
'''
# vectors = gen_vectors(nb, dim)
ids = [i for i in range(nb)]
ids = connect.insert(id_collection, entities, ids)
timeout = 10
start_time = time.time()
while (time.time() - start_time < timeout):
time.sleep(1)
res = connect.count_entities(id_collection)
if res == nb:
break
if time.time() - start_time > timeout:
assert False
@pytest.fixture(
scope="function",
params=[
1,
100
],
)
def same_ids(self, request):
yield request.param
# TODO
@pytest.mark.level(2)
def test_add_flush_same_ids(self, connect, id_collection, same_ids):
'''
method: add entities, with same ids, count(same ids) < 15, > 15
expected: the length of ids and the collection row count
'''
# vectors = gen_vectors(nb, dim)
ids = [i for i in range(nb)]
for i, item in enumerate(ids):
if item <= same_ids:
ids[i] = 0
ids = connect.insert(id_collection, entities, ids)
connect.flush([id_collection])
res = connect.count_entities(id_collection)
assert res == nb
@pytest.mark.skip(reason="search not support yet")
def test_delete_flush_multiable_times(self, connect, collection):
'''
method: delete entities, flush serveral times
expected: no error raised
'''
# vectors = gen_vectors(nb, dim)
ids = connect.insert(collection, entities)
status = connect.delete_entity_by_id(collection, [ids[-1]])
assert status.OK()
for i in range(10):
connect.flush([collection])
# query_vecs = [vectors[0], vectors[1], vectors[-1]]
res = connect.search(collection, default_single_query)
logging.getLogger().debug(res)
assert res
# TODO: CI fail, LOCAL pass
def _test_collection_count_during_flush(self, connect, args):
'''
method: flush collection at background, call `count_entities`
expected: status ok
'''
collection = gen_unique_str("test_flush")
# param = {'collection_name': collection,
# 'dimension': dim,
# 'index_file_size': index_file_size,
# 'metric_type': MetricType.L2}
milvus = get_milvus(args["ip"], args["port"], handler=args["handler"])
milvus.create_collection(collection, default_fields)
# vectors = gen_vector(nb, dim)
ids = milvus.insert(collection, entities, ids=[i for i in range(nb)])
def flush(collection_name):
milvus = get_milvus(args["ip"], args["port"], handler=args["handler"])
status = milvus.delete_entity_by_id(collection_name, [i for i in range(nb)])
with pytest.raises(Exception) as e:
milvus.flush([collection_name])
p = Process(target=flush, args=(collection,))
p.start()
res = milvus.count_entities(collection)
assert res == nb
p.join()
res = milvus.count_entities(collection)
assert res == nb
logging.getLogger().info(res)
assert res == 0
class TestFlushAsync:
@pytest.fixture(scope="function", autouse=True)
def skip_http_check(self, args):
if args["handler"] == "HTTP":
pytest.skip("skip in http mode")
"""
******************************************************************
The following cases are used to test `flush` function
******************************************************************
"""
def check_status(self):
logging.getLogger().info("In callback check status")
def test_flush_empty_collection(self, connect, collection):
'''
method: flush collection with no vectors
expected: status ok
'''
future = connect.flush([collection], _async=True)
status = future.result()
def test_flush_async_long(self, connect, collection):
# vectors = gen_vectors(nb, dim)
ids = connect.insert(collection, entities)
future = connect.flush([collection], _async=True)
status = future.result()
# TODO:
def _test_flush_async(self, connect, collection):
nb = 100000
vectors = gen_vectors(nb, dim)
connect.insert(collection, entities)
logging.getLogger().info("before")
future = connect.flush([collection], _async=True, _callback=self.check_status)
logging.getLogger().info("after")
future.done()
status = future.result()
class TestCollectionNameInvalid(object):
"""
Test adding vectors with invalid collection names
"""
@pytest.fixture(
scope="function",
# params=gen_invalid_collection_names()
params=gen_invalid_strs()
)
def get_invalid_collection_name(self, request):
yield request.param
@pytest.mark.level(2)
def test_flush_with_invalid_collection_name(self, connect, get_invalid_collection_name):
collection_name = get_invalid_collection_name
if collection_name is None or not collection_name:
pytest.skip("while collection_name is None, then flush all collections")
with pytest.raises(Exception) as e:
connect.flush(collection_name)
|
code.py | # Released under the MIT License. See LICENSE for details.
#
"""Functionality for formatting, linting, etc. code."""
from __future__ import annotations
import os
import subprocess
import sys
from pathlib import Path
from typing import TYPE_CHECKING
from efrotools.filecache import FileCache
if TYPE_CHECKING:
from typing import Set, List, Dict, Any, Union, Optional
def formatcode(projroot: Path, full: bool) -> None:
"""Run clang-format on all of our source code (multithreaded)."""
import time
import concurrent.futures
from multiprocessing import cpu_count
from efrotools import get_files_hash
os.chdir(projroot)
cachepath = Path(projroot, 'config/.cache-formatcode')
if full and cachepath.exists():
cachepath.unlink()
cache = FileCache(cachepath)
cfconfig = Path(projroot, '.clang-format')
filenames = get_code_filenames(projroot)
confighash = get_files_hash([cfconfig])
cache.update(filenames, confighash)
dirtyfiles = cache.get_dirty_files()
def format_file(filename: str) -> Dict[str, Any]:
start_time = time.time()
# Note: seems os.system does not unlock the gil;
# make sure to use subprocess.
result = subprocess.call(['clang-format', '-i', filename])
if result != 0:
raise Exception(f'Formatting failed for {filename}')
duration = time.time() - start_time
print(f'Formatted {filename} in {duration:.2f} seconds.')
sys.stdout.flush()
return {'f': filename, 't': duration}
with concurrent.futures.ThreadPoolExecutor(
max_workers=cpu_count()) as executor:
# Converting this to a list will propagate any errors.
list(executor.map(format_file, dirtyfiles))
if dirtyfiles:
# Since we changed files, need to update hashes again.
cache.update(filenames, confighash)
cache.mark_clean(filenames)
cache.write()
print(f'Formatting is up to date for {len(filenames)} code files.',
flush=True)
def cpplint(projroot: Path, full: bool) -> None:
"""Run lint-checking on all code deemed lint-able."""
# pylint: disable=too-many-locals, too-many-statements
import tempfile
from concurrent.futures import ThreadPoolExecutor
from multiprocessing import cpu_count
from efrotools import getconfig, PYVER
from efro.terminal import Clr
from efro.error import CleanError
os.chdir(projroot)
filenames = get_code_filenames(projroot)
for fpath in filenames:
if ' ' in fpath:
raise Exception(f'Found space in path {fpath}; unexpected.')
# Check the config for a list of ones to ignore.
code_blacklist: List[str] = getconfig(projroot).get(
'cpplint_blacklist', [])
# Just pretend blacklisted ones don't exist.
filenames = [f for f in filenames if f not in code_blacklist]
filenames = [f for f in filenames if not f.endswith('.mm')]
cachepath = Path(projroot, 'config/.cache-lintcode')
if full and cachepath.exists():
cachepath.unlink()
cache = FileCache(cachepath)
# Clear out entries and hashes for files that have changed/etc.
cache.update(filenames, '')
dirtyfiles = cache.get_dirty_files()
if dirtyfiles:
print(f'{Clr.BLU}CppLint checking'
f' {len(dirtyfiles)} file(s)...{Clr.RST}')
# We want to do a few custom modifications to the cpplint module...
try:
import cpplint as cpplintmodule
except Exception as exc:
raise CleanError('Unable to import cpplint.') from exc
with open(cpplintmodule.__file__) as infile:
codelines = infile.read().splitlines()
cheadersline = codelines.index('_C_HEADERS = frozenset([')
# Extra headers we consider as valid C system headers.
c_headers = [
'malloc.h', 'tchar.h', 'jni.h', 'android/log.h', 'EGL/egl.h',
'libgen.h', 'linux/netlink.h', 'linux/rtnetlink.h', 'android/bitmap.h',
'android/log.h', 'uuid/uuid.h', 'cxxabi.h', 'direct.h', 'shellapi.h',
'rpc.h', 'io.h'
]
codelines.insert(cheadersline + 1, ''.join(f"'{h}'," for h in c_headers))
# Skip unapproved C++ headers check (it flags <mutex>, <thread>, etc.)
headercheckline = codelines.index(
" if include and include.group(1) in ('cfenv',")
codelines[headercheckline] = (
" if False and include and include.group(1) in ('cfenv',")
# Skip copyright line check (our public repo code is MIT licensed
# so not crucial to keep track of who wrote exactly what)
copyrightline = codelines.index(
' """Logs an error if no Copyright'
' message appears at the top of the file."""')
codelines[copyrightline] = ' return'
# Don't complain about unknown NOLINT categories.
# (we use them for clang-tidy)
unknownlintline = codelines.index(
' elif category not in _LEGACY_ERROR_CATEGORIES:')
codelines[unknownlintline] = ' elif False:'
def lint_file(filename: str) -> None:
result = subprocess.call(
[f'python{PYVER}', '-m', 'cpplint', '--root=src', filename],
env=env)
if result != 0:
raise CleanError(
f'{Clr.RED}Cpplint failed for {filename}.{Clr.RST}')
with tempfile.TemporaryDirectory() as tmpdir:
# Write our replacement module, make it discoverable, then run.
with open(tmpdir + '/cpplint.py', 'w') as outfile:
outfile.write('\n'.join(codelines))
env = os.environ.copy()
env['PYTHONPATH'] = tmpdir
with ThreadPoolExecutor(max_workers=cpu_count()) as executor:
# Converting this to a list will propagate any errors.
list(executor.map(lint_file, dirtyfiles))
if dirtyfiles:
cache.mark_clean(filenames)
cache.write()
print(
f'{Clr.GRN}CppLint: all {len(filenames)} files are passing.{Clr.RST}',
flush=True)
def get_code_filenames(projroot: Path) -> List[str]:
"""Return the list of files to lint-check or auto-formatting."""
from efrotools import getconfig
exts = ('.h', '.c', '.cc', '.cpp', '.cxx', '.m', '.mm')
places = getconfig(projroot).get('code_source_dirs', None)
if places is None:
raise RuntimeError('code_source_dirs not declared in config')
codefilenames = []
for place in places:
for root, _dirs, files in os.walk(place):
for fname in files:
if any(fname.endswith(ext) for ext in exts):
codefilenames.append(os.path.join(root, fname))
codefilenames.sort()
return codefilenames
def formatscripts(projroot: Path, full: bool) -> None:
"""Runs yapf on all our scripts (multithreaded)."""
import time
from concurrent.futures import ThreadPoolExecutor
from multiprocessing import cpu_count
from efrotools import get_files_hash, PYVER
os.chdir(projroot)
cachepath = Path(projroot, 'config/.cache-formatscripts')
if full and cachepath.exists():
cachepath.unlink()
cache = FileCache(cachepath)
yapfconfig = Path(projroot, '.style.yapf')
filenames = get_script_filenames(projroot)
confighash = get_files_hash([yapfconfig])
cache.update(filenames, confighash)
dirtyfiles = cache.get_dirty_files()
def format_file(filename: str) -> None:
start_time = time.time()
result = subprocess.call(
[f'python{PYVER}', '-m', 'yapf', '--in-place', filename])
if result != 0:
raise Exception(f'Formatting failed for {filename}')
duration = time.time() - start_time
print(f'Formatted {filename} in {duration:.2f} seconds.')
sys.stdout.flush()
with ThreadPoolExecutor(max_workers=cpu_count()) as executor:
# Convert the futures to a list to propagate any errors even
# though there are no return values we use.
list(executor.map(format_file, dirtyfiles))
if dirtyfiles:
# Since we changed files, need to update hashes again.
cache.update(filenames, confighash)
cache.mark_clean(filenames)
cache.write()
print(f'Formatting is up to date for {len(filenames)} script files.',
flush=True)
def _should_include_script(fnamefull: str) -> bool:
fname = os.path.basename(fnamefull)
if fname.endswith('.py'):
return True
# Look for 'binary' scripts with no extensions too.
if not fname.startswith('.') and '.' not in fname:
try:
with open(fnamefull) as infile:
line = infile.readline()
if '/usr/bin/env python' in line or '/usr/bin/python' in line:
return True
except UnicodeDecodeError:
# Actual binary files will probably kick back this error.
pass
return False
def get_script_filenames(projroot: Path) -> List[str]:
"""Return the Python filenames to lint-check or auto-format."""
from efrotools import getconfig
filenames = set()
places = getconfig(projroot).get('python_source_dirs', None)
if places is None:
raise RuntimeError('python_source_dirs not declared in config')
for place in places:
for root, _dirs, files in os.walk(place):
for fname in files:
fnamefull = os.path.join(root, fname)
# Skip symlinks (we conceivably operate on the original too)
if os.path.islink(fnamefull):
continue
if _should_include_script(fnamefull):
filenames.add(fnamefull)
return sorted(list(f for f in filenames if 'flycheck_' not in f))
def runpylint(projroot: Path, filenames: List[str]) -> None:
"""Run Pylint explicitly on files."""
pylintrc = Path(projroot, '.pylintrc')
if not os.path.isfile(pylintrc):
raise Exception('pylintrc not found where expected')
# Technically we could just run pylint standalone via command line here,
# but let's go ahead and run it inline so we're consistent with our cached
# full-project version.
_run_pylint(projroot,
pylintrc,
cache=None,
dirtyfiles=filenames,
allfiles=None)
def pylint(projroot: Path, full: bool, fast: bool) -> None:
"""Run Pylint on all scripts in our project (with smart dep tracking)."""
from efrotools import get_files_hash
from efro.terminal import Clr
pylintrc = Path(projroot, '.pylintrc')
if not os.path.isfile(pylintrc):
raise Exception('pylintrc not found where expected')
filenames = get_script_filenames(projroot)
if any(' ' in name for name in filenames):
raise Exception('found space in path; unexpected')
script_blacklist: List[str] = []
filenames = [f for f in filenames if f not in script_blacklist]
cachebasename = '.cache-lintscriptsfast' if fast else '.cache-lintscripts'
cachepath = Path(projroot, 'config', cachebasename)
if full and cachepath.exists():
cachepath.unlink()
cache = FileCache(cachepath)
# Clear out entries and hashes for files that have changed/etc.
cache.update(filenames, get_files_hash([pylintrc]))
# Do a recursive dependency check and mark all files who are
# either dirty or have a dependency that is dirty.
filestates: Dict[str, bool] = {}
for fname in filenames:
_dirty_dep_check(fname, filestates, cache, fast, 0)
dirtyfiles = [k for k, v in filestates.items() if v]
# Let's sort by modification time, so ones we're actively trying
# to fix get linted first and we see remaining errors faster.
dirtyfiles.sort(reverse=True, key=lambda f: os.stat(f).st_mtime)
if dirtyfiles:
print(
f'{Clr.BLU}Pylint checking {len(dirtyfiles)} file(s)...{Clr.RST}',
flush=True)
try:
_run_pylint(projroot, pylintrc, cache, dirtyfiles, filenames)
finally:
# No matter what happens, we still want to
# update our disk cache (since some lints may have passed).
cache.write()
print(f'{Clr.GRN}Pylint: all {len(filenames)} files are passing.{Clr.RST}',
flush=True)
cache.write()
def _dirty_dep_check(fname: str, filestates: Dict[str, bool], cache: FileCache,
fast: bool, recursion: int) -> bool:
"""Recursively check a file's deps and return whether it is dirty."""
# pylint: disable=too-many-branches
if not fast:
# Check for existing dirty state (only applies in non-fast where
# we recurse infinitely).
curstate = filestates.get(fname)
if curstate is not None:
return curstate
# Ok; there's no current state for this file.
# First lets immediately mark it as clean so if a dependency of ours
# queries it we won't loop infinitely. (If we're actually dirty that
# will be reflected properly once we're done).
if not fast:
filestates[fname] = False
# If this dependency has disappeared, consider that dirty.
if fname not in cache.entries:
dirty = True
else:
cacheentry = cache.entries[fname]
# See if we ourself are dirty
if 'hash' not in cacheentry:
dirty = True
else:
# Ok we're clean; now check our dependencies..
dirty = False
# Only increment recursion in fast mode, and
# skip dependencies if we're pass the recursion limit.
recursion2 = recursion
if fast:
# Our one exception is top level ba which basically aggregates.
if not fname.endswith('/ba/__init__.py'):
recursion2 += 1
if recursion2 <= 1:
deps = cacheentry.get('deps', [])
for dep in deps:
# If we have a dep that no longer exists, WE are dirty.
if not os.path.exists(dep):
dirty = True
break
if _dirty_dep_check(dep, filestates, cache, fast,
recursion2):
dirty = True
break
# Cache and return our dirty state..
# Note: for fast mode we limit to recursion==0 so we only write when
# the file itself is being directly visited.
if recursion == 0:
filestates[fname] = dirty
return dirty
def _run_pylint(projroot: Path, pylintrc: Union[Path, str],
cache: Optional[FileCache], dirtyfiles: List[str],
allfiles: Optional[List[str]]) -> Dict[str, Any]:
import time
from pylint import lint
from efro.error import CleanError
from efro.terminal import Clr
start_time = time.time()
args = ['--rcfile', str(pylintrc), '--output-format=colorized']
args += dirtyfiles
name = f'{len(dirtyfiles)} file(s)'
run = lint.Run(args, do_exit=False)
if cache is not None:
assert allfiles is not None
result = _apply_pylint_run_to_cache(projroot, run, dirtyfiles,
allfiles, cache)
if result != 0:
raise CleanError(f'Pylint failed for {result} file(s).')
# Sanity check: when the linter fails we should always be failing too.
# If not, it means we're probably missing something and incorrectly
# marking a failed file as clean.
if run.linter.msg_status != 0 and result == 0:
raise RuntimeError('Pylint linter returned non-zero result'
' but we did not; this is probably a bug.')
else:
if run.linter.msg_status != 0:
raise CleanError('Pylint failed.')
duration = time.time() - start_time
print(f'{Clr.GRN}Pylint passed for {name}'
f' in {duration:.1f} seconds.{Clr.RST}')
sys.stdout.flush()
return {'f': dirtyfiles, 't': duration}
def _apply_pylint_run_to_cache(projroot: Path, run: Any, dirtyfiles: List[str],
allfiles: List[str], cache: FileCache) -> int:
# pylint: disable=too-many-locals
# pylint: disable=too-many-branches
# pylint: disable=too-many-statements
from astroid import modutils
from efrotools import getconfig
from efro.error import CleanError
# First off, build a map of dirtyfiles to module names
# (and the corresponding reverse map).
paths_to_names: Dict[str, str] = {}
names_to_paths: Dict[str, str] = {}
for fname in allfiles:
try:
mpath = modutils.modpath_from_file(fname)
mpath = _filter_module_name('.'.join(mpath))
paths_to_names[fname] = mpath
except ImportError:
# This probably means its a tool or something not in our
# standard path. In this case just use its base name.
# (seems to be what pylint does)
dummyname = os.path.splitext(os.path.basename(fname))[0]
paths_to_names[fname] = dummyname
for key, val in paths_to_names.items():
names_to_paths[val] = key
# If there's any cyclic-import errors, just mark all deps as dirty;
# don't want to add the logic to figure out which ones the cycles cover
# since they all seems to appear as errors for the last file in the list.
cycles: int = run.linter.stats.get('by_msg', {}).get('cyclic-import', 0)
have_dep_cycles: bool = cycles > 0
if have_dep_cycles:
print(f'Found {cycles} cycle-errors; keeping all dirty files dirty.')
# Update dependencies for what we just ran.
# A run leaves us with a map of modules to a list of the modules that
# imports them. We want the opposite though: for each of our modules
# we want a list of the modules it imports.
reversedeps = {}
# Make sure these are all proper module names; no foo.bar.__init__ stuff.
for key, val in run.linter.stats['dependencies'].items():
sval = [_filter_module_name(m) for m in val]
reversedeps[_filter_module_name(key)] = sval
deps: Dict[str, Set[str]] = {}
untracked_deps = set()
for mname, mallimportedby in reversedeps.items():
for mimportedby in mallimportedby:
if mname in names_to_paths:
deps.setdefault(mimportedby, set()).add(mname)
else:
untracked_deps.add(mname)
ignored_untracked_deps: List[str] = getconfig(projroot).get(
'pylint_ignored_untracked_deps', [])
# Add a few that this package itself triggers.
ignored_untracked_deps += ['pylint.lint', 'astroid.modutils', 'astroid']
# Ignore some specific untracked deps; complain about any others.
untracked_deps = set(dep for dep in untracked_deps
if dep not in ignored_untracked_deps)
if untracked_deps:
raise CleanError(
f'Pylint found untracked dependencies: {untracked_deps}.'
' If these are external to your project, add them to'
' "pylint_ignored_untracked_deps" in the project config.')
# Finally add the dependency lists to our entries (operate on
# everything in the run; it may not be mentioned in deps).
no_deps_modules = set()
for fname in dirtyfiles:
fmod = paths_to_names[fname]
if fmod not in deps:
# Since this code is a bit flaky, lets always announce when we
# come up empty and keep a whitelist of expected values to ignore.
no_deps_modules.add(fmod)
depsval: List[str] = []
else:
# Our deps here are module names; store paths.
depsval = [names_to_paths[dep] for dep in deps[fmod]]
cache.entries[fname]['deps'] = depsval
# Let's print a list of modules with no detected deps so we can make sure
# this is behaving.
if no_deps_modules:
if bool(False):
print('NOTE: no dependencies found for:',
', '.join(no_deps_modules))
# Ok, now go through all dirtyfiles involved in this run.
# Mark them as either errored or clean depending on whether there's
# error info for them in the run stats.
# Once again need to convert any foo.bar.__init__ to foo.bar.
stats_by_module: Dict[str, Any] = {
_filter_module_name(key): val
for key, val in run.linter.stats['by_module'].items()
}
errcount = 0
for fname in dirtyfiles:
mname2 = paths_to_names.get(fname)
if mname2 is None:
raise Exception('unable to get module name for "' + fname + '"')
counts = stats_by_module.get(mname2)
# 'statement' count seems to be new and always non-zero; ignore it
if counts is not None:
counts = {c: v for c, v in counts.items() if c != 'statement'}
if (counts is not None and any(counts.values())) or have_dep_cycles:
# print('GOT FAIL FOR', fname, counts)
if 'hash' in cache.entries[fname]:
del cache.entries[fname]['hash']
errcount += 1
else:
# print('MARKING FILE CLEAN', mname2, fname)
cache.entries[fname]['hash'] = (cache.curhashes[fname])
return errcount
def _filter_module_name(mpath: str) -> str:
"""Filter weird module paths such as 'foo.bar.__init__' to 'foo.bar'."""
# Seems Pylint returns module paths with __init__ on the end in some cases
# and not in others. Could dig into it, but for now just filtering them
# out...
return mpath[:-9] if mpath.endswith('.__init__') else mpath
def runmypy(projroot: Path,
filenames: List[str],
full: bool = False,
check: bool = True) -> None:
"""Run MyPy on provided filenames."""
from efrotools import PYTHON_BIN
args = [
PYTHON_BIN, '-m', 'mypy', '--pretty', '--no-error-summary',
'--config-file',
str(Path(projroot, '.mypy.ini'))
] + filenames
if full:
args.insert(args.index('mypy') + 1, '--no-incremental')
subprocess.run(args, check=check)
def mypy(projroot: Path, full: bool) -> None:
"""Type check all of our scripts using mypy."""
import time
from efro.terminal import Clr
from efro.error import CleanError
filenames = get_script_filenames(projroot)
desc = '(full)' if full else '(incremental)'
print(f'{Clr.BLU}Running Mypy {desc}...{Clr.RST}', flush=True)
starttime = time.time()
try:
runmypy(projroot, filenames, full)
except Exception as exc:
raise CleanError('Mypy failed.') from exc
duration = time.time() - starttime
print(f'{Clr.GRN}Mypy passed in {duration:.1f} seconds.{Clr.RST}',
flush=True)
def dmypy(projroot: Path) -> None:
"""Type check all of our scripts using mypy in daemon mode."""
import time
from efro.terminal import Clr
from efro.error import CleanError
filenames = get_script_filenames(projroot)
# Special case; explicitly kill the daemon.
if '-stop' in sys.argv:
subprocess.run(['dmypy', 'stop'], check=False)
return
print('Running Mypy (daemon)...', flush=True)
starttime = time.time()
try:
args = [
'dmypy', 'run', '--timeout', '3600', '--', '--config-file',
'.mypy.ini', '--pretty'
] + filenames
subprocess.run(args, check=True)
except Exception as exc:
raise CleanError('Mypy daemon: fail.') from exc
duration = time.time() - starttime
print(f'{Clr.GRN}Mypy daemon passed in {duration:.1f} seconds.{Clr.RST}',
flush=True)
def _parse_idea_results(path: Path) -> int:
"""Print errors found in an idea inspection xml file.
Returns the number of errors found.
"""
import xml.etree.ElementTree as Et
error_count = 0
root = Et.parse(str(path)).getroot()
for child in root:
line: Optional[str] = None
description: Optional[str] = None
fname: Optional[str] = None
if child.tag == 'problem':
is_error = True
for pchild in child:
if pchild.tag == 'problem_class':
# We still report typos but we don't fail the
# check due to them (that just gets tedious).
if pchild.text == 'Typo':
is_error = False
if pchild.tag == 'line':
line = pchild.text
if pchild.tag == 'description':
description = pchild.text
if pchild.tag == 'file':
fname = pchild.text
if isinstance(fname, str):
fname = fname.replace('file://$PROJECT_DIR$/', '')
print(f'{fname}:{line}: {description}')
if is_error:
error_count += 1
return error_count
def _run_idea_inspections(projroot: Path,
scripts: List[str],
displayname: str,
inspect: Path,
verbose: bool,
inspectdir: Path = None) -> None:
"""Actually run idea inspections.
Throw an Exception if anything is found or goes wrong.
"""
# pylint: disable=too-many-locals
import tempfile
import time
import datetime
from efro.error import CleanError
from efro.terminal import Clr
start_time = time.time()
print(
f'{Clr.BLU}{displayname} checking'
f' {len(scripts)} file(s)...{Clr.RST}',
flush=True)
tmpdir = tempfile.TemporaryDirectory()
iprof = Path(projroot, '.idea/inspectionProfiles/Default.xml')
if not iprof.exists():
iprof = Path(projroot, '.idea/inspectionProfiles/Project_Default.xml')
if not iprof.exists():
raise Exception('No default inspection profile found.')
cmd = [str(inspect), str(projroot), str(iprof), tmpdir.name, '-v2']
if inspectdir is not None:
cmd += ['-d', str(inspectdir)]
running = True
def heartbeat() -> None:
"""Print the time occasionally to make the log more informative."""
while running:
time.sleep(60)
print('Heartbeat', datetime.datetime.now(), flush=True)
if verbose:
import threading
print(cmd, flush=True)
threading.Thread(target=heartbeat, daemon=True).start()
result = subprocess.run(cmd, capture_output=not verbose, check=False)
running = False
if result.returncode != 0:
# In verbose mode this stuff got printed already.
if not verbose:
stdout = (
result.stdout.decode() if isinstance( # type: ignore
result.stdout, bytes) else str(result.stdout))
stderr = (
result.stderr.decode() if isinstance( # type: ignore
result.stdout, bytes) else str(result.stdout))
print(f'{displayname} inspection failure stdout:\n{stdout}' +
f'{displayname} inspection failure stderr:\n{stderr}')
raise RuntimeError(f'{displayname} inspection failed.')
files = [f for f in os.listdir(tmpdir.name) if not f.startswith('.')]
total_errors = 0
if files:
for fname in files:
total_errors += _parse_idea_results(Path(tmpdir.name, fname))
if total_errors > 0:
raise CleanError(f'{Clr.SRED}{displayname} inspection'
f' found {total_errors} error(s).{Clr.RST}')
duration = time.time() - start_time
print(
f'{Clr.GRN}{displayname} passed for {len(scripts)} files'
f' in {duration:.1f} seconds.{Clr.RST}',
flush=True)
def _run_idea_inspections_cached(cachepath: Path,
filenames: List[str],
full: bool,
projroot: Path,
displayname: str,
inspect: Path,
verbose: bool,
inspectdir: Path = None) -> None:
# pylint: disable=too-many-locals
import hashlib
import json
from efro.terminal import Clr
md5 = hashlib.md5()
# Let's calc a single hash from the contents of all script files and only
# run checks when that changes. Sadly there's not much else optimization
# wise that we can easily do, but this will at least prevent re-checks when
# nothing at all has changed.
for filename in filenames:
with open(filename, 'rb') as infile:
md5.update(infile.read())
# Also hash a few .idea files so we re-run inspections when they change.
extra_hash_paths = [
Path(projroot, '.idea/inspectionProfiles/Default.xml'),
Path(projroot, '.idea/inspectionProfiles/Project_Default.xml'),
Path(projroot, '.idea/dictionaries/ericf.xml')
]
for epath in extra_hash_paths:
if os.path.exists(epath):
with open(epath, 'rb') as infile:
md5.update(infile.read())
current_hash = md5.hexdigest()
existing_hash: Optional[str]
try:
with open(cachepath) as infile2:
existing_hash = json.loads(infile2.read())['hash']
except Exception:
existing_hash = None
if full or current_hash != existing_hash:
_run_idea_inspections(projroot,
filenames,
displayname,
inspect=inspect,
verbose=verbose,
inspectdir=inspectdir)
with open(cachepath, 'w') as outfile:
outfile.write(json.dumps({'hash': current_hash}))
print(
f'{Clr.GRN}{displayname}: all {len(filenames)}'
f' files are passing.{Clr.RST}',
flush=True)
def pycharm(projroot: Path, full: bool, verbose: bool) -> None:
"""Run pycharm inspections on all our scripts."""
import time
# FIXME: Generalize this to work with at least linux, possibly windows.
cachepath = Path('config/.cache-pycharm')
filenames = get_script_filenames(projroot)
pycharmroot = Path('/Applications/PyCharm CE.app')
pycharmbin = Path(pycharmroot, 'Contents/MacOS/pycharm')
inspect = Path(pycharmroot, 'Contents/bin/inspect.sh')
# In full mode, clear out pycharm's caches first.
# It seems we need to spin up the GUI and give it a bit to
# re-cache system python for this to work...
# UPDATE: This really slows things down, so we now only do it in
# very specific cases where time isn't important.
# (such as our daily full-test-runs)
if full and os.environ.get('EFROTOOLS_FULL_PYCHARM_RECACHE') == '1':
print('Clearing PyCharm caches...', flush=True)
subprocess.run('rm -rf ~/Library/Caches/PyCharmCE*',
shell=True,
check=True)
print('Launching GUI PyCharm to rebuild caches...', flush=True)
process = subprocess.Popen(str(pycharmbin))
# Wait a bit and ask it nicely to die.
# We need to make sure it has enough time to do its cache updating
# thing even if the system is fully under load.
time.sleep(10 * 60)
# Seems killing it via applescript is more likely to leave it
# in a working state for offline inspections than TERM signal..
subprocess.run(
"osascript -e 'tell application \"PyCharm CE\" to quit'",
shell=True,
check=False)
# process.terminate()
print('Waiting for GUI PyCharm to quit...', flush=True)
process.wait()
_run_idea_inspections_cached(cachepath=cachepath,
filenames=filenames,
full=full,
projroot=projroot,
displayname='PyCharm',
inspect=inspect,
verbose=verbose)
def clioncode(projroot: Path, full: bool, verbose: bool) -> None:
"""Run clion inspections on all our code."""
import time
cachepath = Path('config/.cache-clioncode')
filenames = get_code_filenames(projroot)
clionroot = Path('/Applications/CLion.app')
clionbin = Path(clionroot, 'Contents/MacOS/clion')
inspect = Path(clionroot, 'Contents/bin/inspect.sh')
# At the moment offline clion inspections seem a bit flaky.
# They don't seem to run at all if we haven't opened the project
# in the GUI, and it seems recent changes can get ignored for that
# reason too.
# So for now let's try blowing away caches, launching the gui
# temporarily, and then kicking off inspections after that. Sigh.
print('Clearing CLion caches...', flush=True)
subprocess.run('rm -rf ~/Library/Caches/CLion*', shell=True, check=True)
# Note: I'm assuming this project needs to be open when the GUI
# comes up. Currently just have one project so can rely on auto-open
# but may need to get fancier later if that changes.
print('Launching GUI CLion to rebuild caches...', flush=True)
process = subprocess.Popen(str(clionbin))
# Wait a moment and ask it nicely to die.
waittime = 120
while waittime > 0:
print(f'Waiting for {waittime} more seconds.')
time.sleep(10)
waittime -= 10
# Seems killing it via applescript is more likely to leave it
# in a working state for offline inspections than TERM signal..
subprocess.run("osascript -e 'tell application \"CLion\" to quit'",
shell=True,
check=False)
# process.terminate()
print('Waiting for GUI CLion to quit...', flush=True)
process.wait(timeout=60)
print('Launching Offline CLion to run inspections...', flush=True)
_run_idea_inspections_cached(
cachepath=cachepath,
filenames=filenames,
full=full,
projroot=Path(projroot, 'ballisticacore-cmake'),
inspectdir=Path(projroot, 'ballisticacore-cmake/src/ballistica'),
displayname='CLion',
inspect=inspect,
verbose=verbose)
def androidstudiocode(projroot: Path, full: bool, verbose: bool) -> None:
"""Run Android Studio inspections on all our code."""
# import time
cachepath = Path('config/.cache-androidstudiocode')
filenames = get_code_filenames(projroot)
clionroot = Path('/Applications/Android Studio.app')
# clionbin = Path(clionroot, 'Contents/MacOS/studio')
inspect = Path(clionroot, 'Contents/bin/inspect.sh')
# At the moment offline clion inspections seem a bit flaky.
# They don't seem to run at all if we haven't opened the project
# in the GUI, and it seems recent changes can get ignored for that
# reason too.
# So for now let's try blowing away caches, launching the gui
# temporarily, and then kicking off inspections after that. Sigh.
# print('Clearing Android Studio caches...', flush=True)
# subprocess.run('rm -rf ~/Library/Caches/AndroidStudio*',
# shell=True,
# check=True)
# Note: I'm assuming this project needs to be open when the GUI
# comes up. Currently just have one project so can rely on auto-open
# but may need to get fancier later if that changes.
# print('Launching GUI CLion to rebuild caches...', flush=True)
# process = subprocess.Popen(str(clionbin))
# Wait a moment and ask it nicely to die.
# time.sleep(120)
# Seems killing it via applescript is more likely to leave it
# in a working state for offline inspections than TERM signal..
# subprocess.run(
# "osascript -e 'tell application \"Android Studio\" to quit'",
# shell=True)
# process.terminate()
# print('Waiting for GUI CLion to quit...', flush=True)
# process.wait(timeout=60)
print('Launching Offline Android Studio to run inspections...', flush=True)
_run_idea_inspections_cached(
cachepath=cachepath,
filenames=filenames,
full=full,
projroot=Path(projroot, 'ballisticacore-android'),
inspectdir=Path(
projroot,
'ballisticacore-android/BallisticaCore/src/main/cpp/src/ballistica'
),
# inspectdir=None,
displayname='Android Studio',
inspect=inspect,
verbose=verbose)
|
start_server.py | # Copyright (c) 2020, Ford Motor Company, Livio
# 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 must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following
# disclaimer in the documentation and/or other materials provided with the
# distribution.
# Neither the name of the the copyright holders nor the names of their
# contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import asyncio
import signal
import websockets
import json
import os
import requests
from zipfile import ZipFile
import subprocess
import uuid
import time
import sys
import socketserver
from http.server import SimpleHTTPRequestHandler
import threading
import argparse
class Flags():
"""Used to define global properties"""
FILE_SERVER_HOST = '127.0.0.1'
FILE_SERVER_PORT = 4000
FILE_SERVER_URI = 'http://127.0.0.1:4000'
class WebengineFileServer():
"""Used to handle routing file server requests for webengine apps.
Routes are added/removed via the add_app_mapping/remove_app_mapping functions
"""
def __init__(self, _host, _port, _uri=None):
self.HOST = _host
self.PORT = _port
self.URI = _uri if _uri is not None else 'http://%s:%s' % (self.HOST, self.PORT)
self.tcp_server = None
self.app_dir_mapping = {}
def start(self):
socketserver.TCPServer.allow_reuse_address = True
try:
self.tcp_server = socketserver.TCPServer((self.HOST, self.PORT), self.getRequestHandler(self.app_dir_mapping))
self.tcp_server.serve_forever()
self.stop()
except KeyboardInterrupt:
pass
except Exception as e:
print('Failed to open file server at port %s' % self.PORT)
print(e)
self.tcp_server = None
def stop(self, sig=None, frame=None):
if self.tcp_server is not None:
self.tcp_server.shutdown()
self.tcp_server.server_close()
def add_app_mapping(self, _secret_key, _app_dir):
self.app_dir_mapping[_secret_key] = _app_dir
def remove_app_mapping(self, _secret_key):
self.app_dir_mapping.pop(_secret_key)
@staticmethod
def getRequestHandler(app_dir_mapping):
class Handler(SimpleHTTPRequestHandler):
def end_headers(self):
self.send_header('Access-Control-Allow-Origin', '*')
super().end_headers()
def do_GET(self):
path_parts = self.path.split('/')
key = path_parts[1]
file_path = '/'.join(path_parts[2:])
# Check if the secret key is valid
if key not in app_dir_mapping:
super().send_error(403, "Using invalid key %s" % key)
return
# Get path relative to current working directory
app_dir_path = app_dir_mapping[key].lstrip(os.path.commonpath([app_dir_mapping[key], os.getcwd()]))
# Check if requested path is a directory
if os.path.isdir(os.path.join(os.getcwd(), app_dir_path, file_path)):
super().send_error(403, "Cannot list directories")
return
self.path = '/%s/%s' % (app_dir_path, file_path)
super().do_GET()
return Handler
class WSServer():
"""Used to create a Websocket Connection with the HMI.
Has a SampleRPCService class to handle incoming and outgoing messages.
"""
def __init__(self, _host, _port, _service_class=None):
self.HOST = _host
self.PORT = _port
self.service_class = _service_class if _service_class != None else WSServer.SampleRPCService
async def serve(self, _stop_func):
async with websockets.serve(self.on_connect, self.HOST, self.PORT):
await _stop_func
def start_server(self):
loop = asyncio.get_event_loop()
# The stop condition is set when receiving SIGTERM or SIGINT.
stop = loop.create_future()
loop.add_signal_handler(signal.SIGTERM, stop.set_result, None)
loop.add_signal_handler(signal.SIGINT, stop.set_result, None)
# Run the server until the stop condition is met.
loop.run_until_complete(self.serve(stop))
async def on_connect(self, _websocket, _path):
print('\033[1;2mClient %s connected\033[0m' % str(_websocket.remote_address))
rpc_service = self.service_class(_websocket, _path)
async for message in _websocket:
await rpc_service.on_receive(message)
class SampleRPCService():
def __init__(self, _websocket, _path):
print('\033[1;2mCreated RPC service\033[0m')
self.websocket = _websocket
self.path = _path
async def on_receive(self, _msg):
print('\033[1;2mMessage received: %s\033[0m' % _msg)
class RPCService(WSServer.SampleRPCService):
"""Used to handle receiving RPC requests and send RPC responses.
An implementation of the SampleRPCService class. RPC requests are handled in the `handle_*` functions.
"""
webengine_manager = None
def __init__(self, _websocket, _path):
super().__init__(_websocket, _path)
if RPCService.webengine_manager is None:
RPCService.webengine_manager = WebEngineManager()
self.rpc_mapping = {
"GetPTSFileContent": self.handle_get_pts_file_content,
"SavePTUToFile": self.handle_save_ptu_to_file,
"InstallApp": RPCService.webengine_manager.handle_install_app,
"GetInstalledApps": RPCService.webengine_manager.handle_get_installed_apps,
"UninstallApp": RPCService.webengine_manager.handle_uninstall_app,
}
async def send(self, _msg):
print('\033[1;2m***Sending message: %s\033[0m' % _msg)
await self.websocket.send(_msg)
async def send_error(self, _error_msg):
err = self.gen_error_msg(_error_msg)
print(json.dumps(err))
await self.send(json.dumps(err))
async def on_receive(self, _msg):
print('\033[1;2m***Message received: %s\033[0m' % _msg)
request_message = None
try:
request_message = json.loads(_msg)
except ValueError as err:
await self.send_error('Invalid JSON received: %s' % err)
return
if 'method' not in request_message:
await self.send_error('Received message does not contain manadatory field \'method\'')
return
if 'params' not in request_message:
await self.send_error('Received message does not contain manadatory field \'params\'')
return
response_message = self.handle_request(request_message['method'], request_message['params'])
response_message['method'] = request_message['method']
if response_message != None:
await self.send(json.dumps(response_message))
def handle_request(self, _method_name, _params):
# print('***Handling RPC request: {"method": %s, "params": %s}' % (_method, _params))
if _method_name not in self.rpc_mapping:
return self.gen_error_msg('Method handler for %s was not found! Message ignored' % _method_name)
return self.rpc_mapping[_method_name](_method_name, _params)
def handle_get_pts_file_content(self, _method_name, _params):
if 'fileName' not in _params:
return self.gen_error_msg('Missing mandatory param \'fileName\'')
file_name = _params["fileName"]
file_content = None
with open(file_name, 'r') as json_file:
file_content = json.load(json_file)
return {
"success": True,
"params":{
"content": json.dumps(file_content)
}
}
def handle_save_ptu_to_file(self, _method_name, _params):
if 'fileName' not in _params:
return self.gen_error_msg('Missing mandatory param \'fileName\'')
if 'content' not in _params:
return self.gen_error_msg('Missing mandatory param \'content\'')
file_name = _params["fileName"]
content = json.loads(_params["content"])
# Validate file path
def isFileNameValid(_file_name):
path = os.path.abspath(os.path.normpath(_file_name))
if os.path.commonpath([path, os.getcwd()]) != os.getcwd(): # Trying to save outside the working directory
return False
return True
if not isFileNameValid(file_name):
return self.gen_error_msg('Invalid file name: %s. Cannot save PTU' % file_name)
try:
json_file = open(file_name, 'w')
json.dump(content, json_file)
except:
return self.gen_error_msg('Failed to save PTU file %s' % file_name)
return {
"success": True
}
@staticmethod
def gen_error_msg(_error_msg):
return {'success': False, 'info': _error_msg}
class WebEngineManager():
"""Used to specifically handle WebEngine RPCs.
All the `handle_*` functions parse the RPC requests and the non `handle_*` functions implement
the actual webengine operations(downloading the app zip, creating directories, etc.).
"""
def __init__(self):
self.storage_folder = os.path.join(os.getcwd(), 'webengine')
if not os.path.isdir(self.storage_folder):
print('\033[1mCreating apps storage folder\033[0m')
os.mkdir(self.storage_folder)
self.webengine_apps = {}
self.file_server = WebengineFileServer(Flags.FILE_SERVER_HOST, Flags.FILE_SERVER_PORT, Flags.FILE_SERVER_URI)
thd = threading.Thread(target=self.file_server.start)
thd.start()
signal.signal(signal.SIGINT, self.file_server.stop)
def handle_install_app(self, _method_name, _params):
if 'policyAppID' not in _params:
return RPCService.gen_error_msg('Missing manadatory param \'policyAppID\'')
if 'packageUrl' not in _params:
return RPCService.gen_error_msg('Missing manadatory param \'packageUrl\'')
resp = self.install_app(_params['policyAppID'], _params['packageUrl'])
return resp
def install_app(self, _app_id, _package_url):
# Create app directory
print('\033[1mCreating folder for app %s\033[0m' % _app_id)
app_storage_folder = os.path.join(self.storage_folder, _app_id)
if os.path.isdir(app_storage_folder):
print('\033[1;31mFolder already exists. returning\033[0m')
return RPCService.gen_error_msg('App with id %s is already installed' % _app_id)
os.mkdir(app_storage_folder)
# Download app zip
print('\033[1mDownloading zip\033[0m')
r = requests.get(_package_url)
if r.status_code != 200:
return RPCService.gen_error_msg('Failed to download app from %s. Response result code %s' % (_package_url, r.status_code) )
app_zip_path = os.path.join(app_storage_folder, 'app.zip')
with open(app_zip_path, 'wb') as fptr:
fptr.write(r.content)
# Unzip app.zip file
print('\033[1mUnzipping file\033[0m')
try:
zip_ref = ZipFile(app_zip_path, 'r')
zip_ref.extractall(path=app_storage_folder)
os.remove(app_zip_path)
except:
return RPCService.gen_error_msg('Failed to unzip app')
# Start file server
print('\033[1mAdding app to File Server\033[0m')
file_server_info = self.add_app_to_file_server(app_storage_folder)
self.webengine_apps[_app_id] = {
"policyAppID": _app_id,
"appURL": file_server_info['url'],
"appKey": file_server_info['key']
}
return {
"success": True,
"params": {
"appUrl": file_server_info['url']
}
}
def add_app_to_file_server(self, _app_storage_folder):
secret_key = str(uuid.uuid4())
print('\033[2mSecret key is %s\033[0m' % (secret_key))
self.file_server.add_app_mapping(secret_key, _app_storage_folder)
return {
"key": secret_key,
"url": '%s/%s/' % (self.file_server.URI, secret_key)
}
def handle_get_installed_apps(self, _method_name, _params):
resp = self.get_installed_apps()
return resp
def get_installed_apps(self):
apps_info = []
app_dirs = [d for d in os.listdir(self.storage_folder) if os.path.isdir(os.path.join(self.storage_folder, d))]
for app_id in app_dirs:
if app_id not in self.webengine_apps:
print('\033[1mAdding app %s to file server\033[0m' % app_id)
app_storage_folder = os.path.join(self.storage_folder, app_id)
file_server_info = self.add_app_to_file_server(app_storage_folder)
self.webengine_apps[app_id] = {
"policyAppID": app_id,
"appURL": file_server_info['url'],
"appKey": file_server_info['key']
}
apps_info.append({
"policyAppID": app_id,
"appUrl": self.webengine_apps[app_id]['appURL']
})
return {
"success": True,
"params":{
"apps": apps_info
}
}
def handle_uninstall_app(self, _method_name, _params):
if 'policyAppID' not in _params:
return RPCService.gen_error_msg('Missing manadatory param \'policyAppID\'')
resp = self.uninstall_app(_params['policyAppID'])
return resp
def uninstall_app(self, _app_id):
app_storage_folder = os.path.join(self.storage_folder, _app_id)
if not os.path.isdir(app_storage_folder):
print('\033[1;31mApp %s is not installed\033[0m' % _app_id)
return RPCService.gen_error_msg('App \'%s\' is not installed' % _app_id)
if _app_id in self.webengine_apps:
self.file_server.remove_app_mapping(self.webengine_apps[_app_id]['appKey'])
removed_app = self.webengine_apps.pop(_app_id)
print('\033[1mRemoving webengine app %s\033[0m' % str(removed_app))
print('\033[1mRemoving app storage folder\033[0m')
subprocess.call(['rm', '-rf', app_storage_folder])
return {
"success": True,
"params":{
"policyAppID": _app_id
}
}
def main():
parser = argparse.ArgumentParser(description="Handle backend operations for the hmi")
parser.add_argument('--host', type=str, required=True, help="Backend server hostname")
parser.add_argument('--port', type=int, required=True, help="Backend server port number")
parser.add_argument('--fs-port', type=int, default=4000, help="File server port number")
parser.add_argument('--fs-uri', type=str, help="File server's URI (to be sent back to the client hmi)")
args = parser.parse_args()
Flags.FILE_SERVER_HOST = args.host
Flags.FILE_SERVER_PORT = args.fs_port
Flags.FILE_SERVER_URI = args.fs_uri if args.fs_uri else 'http://%s:%s' % (Flags.FILE_SERVER_HOST, Flags.FILE_SERVER_PORT)
backend_server = WSServer(args.host, args.port, RPCService)
print('Starting server')
backend_server.start_server()
print('Stopping server')
if __name__ == '__main__':
main()
|
test_utils_test.py | import asyncio
import pathlib
import socket
import threading
from contextlib import contextmanager
from time import sleep
import pytest
from tornado import gen
from distributed import Client, Nanny, Scheduler, Worker, config, default_client
from distributed.core import rpc
from distributed.metrics import time
from distributed.utils import get_ip
from distributed.utils_test import (
cluster,
gen_cluster,
gen_test,
inc,
new_config,
tls_only_security,
wait_for_port,
)
def test_bare_cluster(loop):
with cluster(nworkers=10) as (s, _):
pass
def test_cluster(loop):
with cluster() as (s, [a, b]):
with rpc(s["address"]) as s:
ident = loop.run_sync(s.identity)
assert ident["type"] == "Scheduler"
assert len(ident["workers"]) == 2
@gen_cluster(client=True)
async def test_gen_cluster(c, s, a, b):
assert isinstance(c, Client)
assert isinstance(s, Scheduler)
for w in [a, b]:
assert isinstance(w, Worker)
assert s.nthreads == {w.address: w.nthreads for w in [a, b]}
assert await c.submit(lambda: 123) == 123
@gen_cluster(client=True)
async def test_gen_cluster_pytest_fixture(c, s, a, b, tmp_path):
assert isinstance(tmp_path, pathlib.Path)
assert isinstance(c, Client)
assert isinstance(s, Scheduler)
for w in [a, b]:
assert isinstance(w, Worker)
@pytest.mark.parametrize("foo", [True])
@gen_cluster(client=True)
async def test_gen_cluster_parametrized(c, s, a, b, foo):
assert foo is True
assert isinstance(c, Client)
assert isinstance(s, Scheduler)
for w in [a, b]:
assert isinstance(w, Worker)
@pytest.mark.parametrize("foo", [True])
@pytest.mark.parametrize("bar", ["a", "b"])
@gen_cluster(client=True)
async def test_gen_cluster_multi_parametrized(c, s, a, b, foo, bar):
assert foo is True
assert bar in ("a", "b")
assert isinstance(c, Client)
assert isinstance(s, Scheduler)
for w in [a, b]:
assert isinstance(w, Worker)
@pytest.mark.parametrize("foo", [True])
@gen_cluster(client=True)
async def test_gen_cluster_parametrized_variadic_workers(c, s, *workers, foo):
assert foo is True
assert isinstance(c, Client)
assert isinstance(s, Scheduler)
for w in workers:
assert isinstance(w, Worker)
@gen_cluster(
client=True,
Worker=Nanny,
config={"distributed.comm.timeouts.connect": "1s", "new.config.value": "foo"},
)
async def test_gen_cluster_set_config_nanny(c, s, a, b):
def assert_config():
import dask
assert dask.config.get("distributed.comm.timeouts.connect") == "1s"
assert dask.config.get("new.config.value") == "foo"
return dask.config
await c.run(assert_config)
await c.run_on_scheduler(assert_config)
@gen_cluster(client=True)
def test_gen_cluster_legacy_implicit(c, s, a, b):
assert isinstance(c, Client)
assert isinstance(s, Scheduler)
for w in [a, b]:
assert isinstance(w, Worker)
assert s.nthreads == {w.address: w.nthreads for w in [a, b]}
assert (yield c.submit(lambda: 123)) == 123
@gen_cluster(client=True)
@gen.coroutine
def test_gen_cluster_legacy_explicit(c, s, a, b):
assert isinstance(c, Client)
assert isinstance(s, Scheduler)
for w in [a, b]:
assert isinstance(w, Worker)
assert s.nthreads == {w.address: w.nthreads for w in [a, b]}
assert (yield c.submit(lambda: 123)) == 123
@pytest.mark.skip(reason="This hangs on travis")
def test_gen_cluster_cleans_up_client(loop):
import dask.context
assert not dask.config.get("get", None)
@gen_cluster(client=True)
async def f(c, s, a, b):
assert dask.config.get("get", None)
await c.submit(inc, 1)
f()
assert not dask.config.get("get", None)
@gen_cluster(client=False)
async def test_gen_cluster_without_client(s, a, b):
assert isinstance(s, Scheduler)
for w in [a, b]:
assert isinstance(w, Worker)
assert s.nthreads == {w.address: w.nthreads for w in [a, b]}
async with Client(s.address, asynchronous=True) as c:
future = c.submit(lambda x: x + 1, 1)
result = await future
assert result == 2
@gen_cluster(
client=True,
scheduler="tls://127.0.0.1",
nthreads=[("tls://127.0.0.1", 1), ("tls://127.0.0.1", 2)],
security=tls_only_security(),
)
async def test_gen_cluster_tls(e, s, a, b):
assert isinstance(e, Client)
assert isinstance(s, Scheduler)
assert s.address.startswith("tls://")
for w in [a, b]:
assert isinstance(w, Worker)
assert w.address.startswith("tls://")
assert s.nthreads == {w.address: w.nthreads for w in [a, b]}
@gen_test()
async def test_gen_test():
await asyncio.sleep(0.01)
@gen_test()
def test_gen_test_legacy_implicit():
yield asyncio.sleep(0.01)
@gen_test()
@gen.coroutine
def test_gen_test_legacy_explicit():
yield asyncio.sleep(0.01)
@contextmanager
def _listen(delay=0):
serv = socket.socket()
serv.bind(("127.0.0.1", 0))
e = threading.Event()
def do_listen():
e.set()
sleep(delay)
serv.listen(5)
ret = serv.accept()
if ret is not None:
cli, _ = ret
cli.close()
serv.close()
t = threading.Thread(target=do_listen)
t.daemon = True
t.start()
try:
e.wait()
sleep(0.01)
yield serv
finally:
t.join(5.0)
def test_wait_for_port():
t1 = time()
with pytest.raises(RuntimeError):
wait_for_port((get_ip(), 9999), 0.5)
t2 = time()
assert t2 - t1 >= 0.5
with _listen(0) as s1:
t1 = time()
wait_for_port(s1.getsockname())
t2 = time()
assert t2 - t1 <= 1.0
with _listen(1) as s1:
t1 = time()
wait_for_port(s1.getsockname())
t2 = time()
assert t2 - t1 <= 2.0
def test_new_config():
c = config.copy()
with new_config({"xyzzy": 5}):
config["xyzzy"] == 5
assert config == c
assert "xyzzy" not in config
def test_lingering_client():
@gen_cluster()
async def f(s, a, b):
await Client(s.address, asynchronous=True)
f()
with pytest.raises(ValueError):
default_client()
def test_lingering_client_2(loop):
with cluster() as (s, [a, b]):
client = Client(s["address"], loop=loop)
def test_tls_cluster(tls_client):
tls_client.submit(lambda x: x + 1, 10).result() == 11
assert tls_client.security
@pytest.mark.asyncio
async def test_tls_scheduler(security, cleanup):
async with Scheduler(security=security, host="localhost") as s:
assert s.address.startswith("tls")
|
test_threading.py | """
Tests for the threading module.
"""
import test.support
from test.support import threading_helper
from test.support import verbose, cpython_only
from test.support.import_helper import import_module
from test.support.script_helper import assert_python_ok, assert_python_failure
import random
import sys
import _thread
import threading
import time
import unittest
import weakref
import os
import subprocess
import signal
import textwrap
from unittest import mock
from test import lock_tests
from test import support
# Between fork() and exec(), only async-safe functions are allowed (issues
# #12316 and #11870), and fork() from a worker thread is known to trigger
# problems with some operating systems (issue #3863): skip problematic tests
# on platforms known to behave badly.
platforms_to_skip = ('netbsd5', 'hp-ux11')
def restore_default_excepthook(testcase):
testcase.addCleanup(setattr, threading, 'excepthook', threading.excepthook)
threading.excepthook = threading.__excepthook__
# A trivial mutable counter.
class Counter(object):
def __init__(self):
self.value = 0
def inc(self):
self.value += 1
def dec(self):
self.value -= 1
def get(self):
return self.value
class TestThread(threading.Thread):
def __init__(self, name, testcase, sema, mutex, nrunning):
threading.Thread.__init__(self, name=name)
self.testcase = testcase
self.sema = sema
self.mutex = mutex
self.nrunning = nrunning
def run(self):
delay = random.random() / 10000.0
if verbose:
print('task %s will run for %.1f usec' %
(self.name, delay * 1e6))
with self.sema:
with self.mutex:
self.nrunning.inc()
if verbose:
print(self.nrunning.get(), 'tasks are running')
self.testcase.assertLessEqual(self.nrunning.get(), 3)
time.sleep(delay)
if verbose:
print('task', self.name, 'done')
with self.mutex:
self.nrunning.dec()
self.testcase.assertGreaterEqual(self.nrunning.get(), 0)
if verbose:
print('%s is finished. %d tasks are running' %
(self.name, self.nrunning.get()))
class BaseTestCase(unittest.TestCase):
def setUp(self):
self._threads = threading_helper.threading_setup()
def tearDown(self):
threading_helper.threading_cleanup(*self._threads)
test.support.reap_children()
class ThreadTests(BaseTestCase):
@cpython_only
def test_name(self):
def func(): pass
thread = threading.Thread(name="myname1")
self.assertEqual(thread.name, "myname1")
# Convert int name to str
thread = threading.Thread(name=123)
self.assertEqual(thread.name, "123")
# target name is ignored if name is specified
thread = threading.Thread(target=func, name="myname2")
self.assertEqual(thread.name, "myname2")
with mock.patch.object(threading, '_counter', return_value=2):
thread = threading.Thread(name="")
self.assertEqual(thread.name, "Thread-2")
with mock.patch.object(threading, '_counter', return_value=3):
thread = threading.Thread()
self.assertEqual(thread.name, "Thread-3")
with mock.patch.object(threading, '_counter', return_value=5):
thread = threading.Thread(target=func)
self.assertEqual(thread.name, "Thread-5 (func)")
@cpython_only
def test_disallow_instantiation(self):
# Ensure that the type disallows instantiation (bpo-43916)
lock = threading.Lock()
tp = type(lock)
self.assertRaises(TypeError, tp)
# Create a bunch of threads, let each do some work, wait until all are
# done.
def test_various_ops(self):
# This takes about n/3 seconds to run (about n/3 clumps of tasks,
# times about 1 second per clump).
NUMTASKS = 10
# no more than 3 of the 10 can run at once
sema = threading.BoundedSemaphore(value=3)
mutex = threading.RLock()
numrunning = Counter()
threads = []
for i in range(NUMTASKS):
t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
threads.append(t)
self.assertIsNone(t.ident)
self.assertRegex(repr(t), r'^<TestThread\(.*, initial\)>$')
t.start()
if hasattr(threading, 'get_native_id'):
native_ids = set(t.native_id for t in threads) | {threading.get_native_id()}
self.assertNotIn(None, native_ids)
self.assertEqual(len(native_ids), NUMTASKS + 1)
if verbose:
print('waiting for all tasks to complete')
for t in threads:
t.join()
self.assertFalse(t.is_alive())
self.assertNotEqual(t.ident, 0)
self.assertIsNotNone(t.ident)
self.assertRegex(repr(t), r'^<TestThread\(.*, stopped -?\d+\)>$')
if verbose:
print('all tasks done')
self.assertEqual(numrunning.get(), 0)
def test_ident_of_no_threading_threads(self):
# The ident still must work for the main thread and dummy threads.
self.assertIsNotNone(threading.current_thread().ident)
def f():
ident.append(threading.current_thread().ident)
done.set()
done = threading.Event()
ident = []
with threading_helper.wait_threads_exit():
tid = _thread.start_new_thread(f, ())
done.wait()
self.assertEqual(ident[0], tid)
# Kill the "immortal" _DummyThread
del threading._active[ident[0]]
# run with a small(ish) thread stack size (256 KiB)
def test_various_ops_small_stack(self):
if verbose:
print('with 256 KiB thread stack size...')
try:
threading.stack_size(262144)
except _thread.error:
raise unittest.SkipTest(
'platform does not support changing thread stack size')
self.test_various_ops()
threading.stack_size(0)
# run with a large thread stack size (1 MiB)
def test_various_ops_large_stack(self):
if verbose:
print('with 1 MiB thread stack size...')
try:
threading.stack_size(0x100000)
except _thread.error:
raise unittest.SkipTest(
'platform does not support changing thread stack size')
self.test_various_ops()
threading.stack_size(0)
def test_foreign_thread(self):
# Check that a "foreign" thread can use the threading module.
def f(mutex):
# Calling current_thread() forces an entry for the foreign
# thread to get made in the threading._active map.
threading.current_thread()
mutex.release()
mutex = threading.Lock()
mutex.acquire()
with threading_helper.wait_threads_exit():
tid = _thread.start_new_thread(f, (mutex,))
# Wait for the thread to finish.
mutex.acquire()
self.assertIn(tid, threading._active)
self.assertIsInstance(threading._active[tid], threading._DummyThread)
#Issue 29376
self.assertTrue(threading._active[tid].is_alive())
self.assertRegex(repr(threading._active[tid]), '_DummyThread')
del threading._active[tid]
# PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
# exposed at the Python level. This test relies on ctypes to get at it.
def test_PyThreadState_SetAsyncExc(self):
ctypes = import_module("ctypes")
set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
set_async_exc.argtypes = (ctypes.c_ulong, ctypes.py_object)
class AsyncExc(Exception):
pass
exception = ctypes.py_object(AsyncExc)
# First check it works when setting the exception from the same thread.
tid = threading.get_ident()
self.assertIsInstance(tid, int)
self.assertGreater(tid, 0)
try:
result = set_async_exc(tid, exception)
# The exception is async, so we might have to keep the VM busy until
# it notices.
while True:
pass
except AsyncExc:
pass
else:
# This code is unreachable but it reflects the intent. If we wanted
# to be smarter the above loop wouldn't be infinite.
self.fail("AsyncExc not raised")
try:
self.assertEqual(result, 1) # one thread state modified
except UnboundLocalError:
# The exception was raised too quickly for us to get the result.
pass
# `worker_started` is set by the thread when it's inside a try/except
# block waiting to catch the asynchronously set AsyncExc exception.
# `worker_saw_exception` is set by the thread upon catching that
# exception.
worker_started = threading.Event()
worker_saw_exception = threading.Event()
class Worker(threading.Thread):
def run(self):
self.id = threading.get_ident()
self.finished = False
try:
while True:
worker_started.set()
time.sleep(0.1)
except AsyncExc:
self.finished = True
worker_saw_exception.set()
t = Worker()
t.daemon = True # so if this fails, we don't hang Python at shutdown
t.start()
if verbose:
print(" started worker thread")
# Try a thread id that doesn't make sense.
if verbose:
print(" trying nonsensical thread id")
result = set_async_exc(-1, exception)
self.assertEqual(result, 0) # no thread states modified
# Now raise an exception in the worker thread.
if verbose:
print(" waiting for worker thread to get started")
ret = worker_started.wait()
self.assertTrue(ret)
if verbose:
print(" verifying worker hasn't exited")
self.assertFalse(t.finished)
if verbose:
print(" attempting to raise asynch exception in worker")
result = set_async_exc(t.id, exception)
self.assertEqual(result, 1) # one thread state modified
if verbose:
print(" waiting for worker to say it caught the exception")
worker_saw_exception.wait(timeout=support.SHORT_TIMEOUT)
self.assertTrue(t.finished)
if verbose:
print(" all OK -- joining worker")
if t.finished:
t.join()
# else the thread is still running, and we have no way to kill it
def test_limbo_cleanup(self):
# Issue 7481: Failure to start thread should cleanup the limbo map.
def fail_new_thread(*args):
raise threading.ThreadError()
_start_new_thread = threading._start_new_thread
threading._start_new_thread = fail_new_thread
try:
t = threading.Thread(target=lambda: None)
self.assertRaises(threading.ThreadError, t.start)
self.assertFalse(
t in threading._limbo,
"Failed to cleanup _limbo map on failure of Thread.start().")
finally:
threading._start_new_thread = _start_new_thread
def test_finalize_running_thread(self):
# Issue 1402: the PyGILState_Ensure / _Release functions may be called
# very late on python exit: on deallocation of a running thread for
# example.
import_module("ctypes")
rc, out, err = assert_python_failure("-c", """if 1:
import ctypes, sys, time, _thread
# This lock is used as a simple event variable.
ready = _thread.allocate_lock()
ready.acquire()
# Module globals are cleared before __del__ is run
# So we save the functions in class dict
class C:
ensure = ctypes.pythonapi.PyGILState_Ensure
release = ctypes.pythonapi.PyGILState_Release
def __del__(self):
state = self.ensure()
self.release(state)
def waitingThread():
x = C()
ready.release()
time.sleep(100)
_thread.start_new_thread(waitingThread, ())
ready.acquire() # Be sure the other thread is waiting.
sys.exit(42)
""")
self.assertEqual(rc, 42)
def test_finalize_with_trace(self):
# Issue1733757
# Avoid a deadlock when sys.settrace steps into threading._shutdown
assert_python_ok("-c", """if 1:
import sys, threading
# A deadlock-killer, to prevent the
# testsuite to hang forever
def killer():
import os, time
time.sleep(2)
print('program blocked; aborting')
os._exit(2)
t = threading.Thread(target=killer)
t.daemon = True
t.start()
# This is the trace function
def func(frame, event, arg):
threading.current_thread()
return func
sys.settrace(func)
""")
def test_join_nondaemon_on_shutdown(self):
# Issue 1722344
# Raising SystemExit skipped threading._shutdown
rc, out, err = assert_python_ok("-c", """if 1:
import threading
from time import sleep
def child():
sleep(1)
# As a non-daemon thread we SHOULD wake up and nothing
# should be torn down yet
print("Woke up, sleep function is:", sleep)
threading.Thread(target=child).start()
raise SystemExit
""")
self.assertEqual(out.strip(),
b"Woke up, sleep function is: <built-in function sleep>")
self.assertEqual(err, b"")
def test_enumerate_after_join(self):
# Try hard to trigger #1703448: a thread is still returned in
# threading.enumerate() after it has been join()ed.
enum = threading.enumerate
old_interval = sys.getswitchinterval()
try:
for i in range(1, 100):
sys.setswitchinterval(i * 0.0002)
t = threading.Thread(target=lambda: None)
t.start()
t.join()
l = enum()
self.assertNotIn(t, l,
"#1703448 triggered after %d trials: %s" % (i, l))
finally:
sys.setswitchinterval(old_interval)
def test_no_refcycle_through_target(self):
class RunSelfFunction(object):
def __init__(self, should_raise):
# The links in this refcycle from Thread back to self
# should be cleaned up when the thread completes.
self.should_raise = should_raise
self.thread = threading.Thread(target=self._run,
args=(self,),
kwargs={'yet_another':self})
self.thread.start()
def _run(self, other_ref, yet_another):
if self.should_raise:
raise SystemExit
restore_default_excepthook(self)
cyclic_object = RunSelfFunction(should_raise=False)
weak_cyclic_object = weakref.ref(cyclic_object)
cyclic_object.thread.join()
del cyclic_object
self.assertIsNone(weak_cyclic_object(),
msg=('%d references still around' %
sys.getrefcount(weak_cyclic_object())))
raising_cyclic_object = RunSelfFunction(should_raise=True)
weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
raising_cyclic_object.thread.join()
del raising_cyclic_object
self.assertIsNone(weak_raising_cyclic_object(),
msg=('%d references still around' %
sys.getrefcount(weak_raising_cyclic_object())))
def test_old_threading_api(self):
# Just a quick sanity check to make sure the old method names are
# still present
t = threading.Thread()
with self.assertWarnsRegex(DeprecationWarning,
r'get the daemon attribute'):
t.isDaemon()
with self.assertWarnsRegex(DeprecationWarning,
r'set the daemon attribute'):
t.setDaemon(True)
with self.assertWarnsRegex(DeprecationWarning,
r'get the name attribute'):
t.getName()
with self.assertWarnsRegex(DeprecationWarning,
r'set the name attribute'):
t.setName("name")
e = threading.Event()
with self.assertWarnsRegex(DeprecationWarning, 'use is_set()'):
e.isSet()
cond = threading.Condition()
cond.acquire()
with self.assertWarnsRegex(DeprecationWarning, 'use notify_all()'):
cond.notifyAll()
with self.assertWarnsRegex(DeprecationWarning, 'use active_count()'):
threading.activeCount()
with self.assertWarnsRegex(DeprecationWarning, 'use current_thread()'):
threading.currentThread()
def test_repr_daemon(self):
t = threading.Thread()
self.assertNotIn('daemon', repr(t))
t.daemon = True
self.assertIn('daemon', repr(t))
def test_daemon_param(self):
t = threading.Thread()
self.assertFalse(t.daemon)
t = threading.Thread(daemon=False)
self.assertFalse(t.daemon)
t = threading.Thread(daemon=True)
self.assertTrue(t.daemon)
@unittest.skipUnless(hasattr(os, 'fork'), 'needs os.fork()')
def test_fork_at_exit(self):
# bpo-42350: Calling os.fork() after threading._shutdown() must
# not log an error.
code = textwrap.dedent("""
import atexit
import os
import sys
from test.support import wait_process
# Import the threading module to register its "at fork" callback
import threading
def exit_handler():
pid = os.fork()
if not pid:
print("child process ok", file=sys.stderr, flush=True)
# child process
else:
wait_process(pid, exitcode=0)
# exit_handler() will be called after threading._shutdown()
atexit.register(exit_handler)
""")
_, out, err = assert_python_ok("-c", code)
self.assertEqual(out, b'')
self.assertEqual(err.rstrip(), b'child process ok')
@unittest.skipUnless(hasattr(os, 'fork'), 'test needs fork()')
def test_dummy_thread_after_fork(self):
# Issue #14308: a dummy thread in the active list doesn't mess up
# the after-fork mechanism.
code = """if 1:
import _thread, threading, os, time
def background_thread(evt):
# Creates and registers the _DummyThread instance
threading.current_thread()
evt.set()
time.sleep(10)
evt = threading.Event()
_thread.start_new_thread(background_thread, (evt,))
evt.wait()
assert threading.active_count() == 2, threading.active_count()
if os.fork() == 0:
assert threading.active_count() == 1, threading.active_count()
os._exit(0)
else:
os.wait()
"""
_, out, err = assert_python_ok("-c", code)
self.assertEqual(out, b'')
self.assertEqual(err, b'')
@unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
def test_is_alive_after_fork(self):
# Try hard to trigger #18418: is_alive() could sometimes be True on
# threads that vanished after a fork.
old_interval = sys.getswitchinterval()
self.addCleanup(sys.setswitchinterval, old_interval)
# Make the bug more likely to manifest.
test.support.setswitchinterval(1e-6)
for i in range(20):
t = threading.Thread(target=lambda: None)
t.start()
pid = os.fork()
if pid == 0:
os._exit(11 if t.is_alive() else 10)
else:
t.join()
support.wait_process(pid, exitcode=10)
def test_main_thread(self):
main = threading.main_thread()
self.assertEqual(main.name, 'MainThread')
self.assertEqual(main.ident, threading.current_thread().ident)
self.assertEqual(main.ident, threading.get_ident())
def f():
self.assertNotEqual(threading.main_thread().ident,
threading.current_thread().ident)
th = threading.Thread(target=f)
th.start()
th.join()
@unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
@unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
def test_main_thread_after_fork(self):
code = """if 1:
import os, threading
from test import support
pid = os.fork()
if pid == 0:
main = threading.main_thread()
print(main.name)
print(main.ident == threading.current_thread().ident)
print(main.ident == threading.get_ident())
else:
support.wait_process(pid, exitcode=0)
"""
_, out, err = assert_python_ok("-c", code)
data = out.decode().replace('\r', '')
self.assertEqual(err, b"")
self.assertEqual(data, "MainThread\nTrue\nTrue\n")
@unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
@unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
@unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
def test_main_thread_after_fork_from_nonmain_thread(self):
code = """if 1:
import os, threading, sys
from test import support
def func():
pid = os.fork()
if pid == 0:
main = threading.main_thread()
print(main.name)
print(main.ident == threading.current_thread().ident)
print(main.ident == threading.get_ident())
# stdout is fully buffered because not a tty,
# we have to flush before exit.
sys.stdout.flush()
else:
support.wait_process(pid, exitcode=0)
th = threading.Thread(target=func)
th.start()
th.join()
"""
_, out, err = assert_python_ok("-c", code)
data = out.decode().replace('\r', '')
self.assertEqual(err, b"")
self.assertEqual(data, "Thread-1 (func)\nTrue\nTrue\n")
def test_main_thread_during_shutdown(self):
# bpo-31516: current_thread() should still point to the main thread
# at shutdown
code = """if 1:
import gc, threading
main_thread = threading.current_thread()
assert main_thread is threading.main_thread() # sanity check
class RefCycle:
def __init__(self):
self.cycle = self
def __del__(self):
print("GC:",
threading.current_thread() is main_thread,
threading.main_thread() is main_thread,
threading.enumerate() == [main_thread])
RefCycle()
gc.collect() # sanity check
x = RefCycle()
"""
_, out, err = assert_python_ok("-c", code)
data = out.decode()
self.assertEqual(err, b"")
self.assertEqual(data.splitlines(),
["GC: True True True"] * 2)
def test_finalization_shutdown(self):
# bpo-36402: Py_Finalize() calls threading._shutdown() which must wait
# until Python thread states of all non-daemon threads get deleted.
#
# Test similar to SubinterpThreadingTests.test_threads_join_2(), but
# test the finalization of the main interpreter.
code = """if 1:
import os
import threading
import time
import random
def random_sleep():
seconds = random.random() * 0.010
time.sleep(seconds)
class Sleeper:
def __del__(self):
random_sleep()
tls = threading.local()
def f():
# Sleep a bit so that the thread is still running when
# Py_Finalize() is called.
random_sleep()
tls.x = Sleeper()
random_sleep()
threading.Thread(target=f).start()
random_sleep()
"""
rc, out, err = assert_python_ok("-c", code)
self.assertEqual(err, b"")
def test_tstate_lock(self):
# Test an implementation detail of Thread objects.
started = _thread.allocate_lock()
finish = _thread.allocate_lock()
started.acquire()
finish.acquire()
def f():
started.release()
finish.acquire()
time.sleep(0.01)
# The tstate lock is None until the thread is started
t = threading.Thread(target=f)
self.assertIs(t._tstate_lock, None)
t.start()
started.acquire()
self.assertTrue(t.is_alive())
# The tstate lock can't be acquired when the thread is running
# (or suspended).
tstate_lock = t._tstate_lock
self.assertFalse(tstate_lock.acquire(timeout=0), False)
finish.release()
# When the thread ends, the state_lock can be successfully
# acquired.
self.assertTrue(tstate_lock.acquire(timeout=support.SHORT_TIMEOUT), False)
# But is_alive() is still True: we hold _tstate_lock now, which
# prevents is_alive() from knowing the thread's end-of-life C code
# is done.
self.assertTrue(t.is_alive())
# Let is_alive() find out the C code is done.
tstate_lock.release()
self.assertFalse(t.is_alive())
# And verify the thread disposed of _tstate_lock.
self.assertIsNone(t._tstate_lock)
t.join()
def test_repr_stopped(self):
# Verify that "stopped" shows up in repr(Thread) appropriately.
started = _thread.allocate_lock()
finish = _thread.allocate_lock()
started.acquire()
finish.acquire()
def f():
started.release()
finish.acquire()
t = threading.Thread(target=f)
t.start()
started.acquire()
self.assertIn("started", repr(t))
finish.release()
# "stopped" should appear in the repr in a reasonable amount of time.
# Implementation detail: as of this writing, that's trivially true
# if .join() is called, and almost trivially true if .is_alive() is
# called. The detail we're testing here is that "stopped" shows up
# "all on its own".
LOOKING_FOR = "stopped"
for i in range(500):
if LOOKING_FOR in repr(t):
break
time.sleep(0.01)
self.assertIn(LOOKING_FOR, repr(t)) # we waited at least 5 seconds
t.join()
def test_BoundedSemaphore_limit(self):
# BoundedSemaphore should raise ValueError if released too often.
for limit in range(1, 10):
bs = threading.BoundedSemaphore(limit)
threads = [threading.Thread(target=bs.acquire)
for _ in range(limit)]
for t in threads:
t.start()
for t in threads:
t.join()
threads = [threading.Thread(target=bs.release)
for _ in range(limit)]
for t in threads:
t.start()
for t in threads:
t.join()
self.assertRaises(ValueError, bs.release)
@cpython_only
def test_frame_tstate_tracing(self):
# Issue #14432: Crash when a generator is created in a C thread that is
# destroyed while the generator is still used. The issue was that a
# generator contains a frame, and the frame kept a reference to the
# Python state of the destroyed C thread. The crash occurs when a trace
# function is setup.
def noop_trace(frame, event, arg):
# no operation
return noop_trace
def generator():
while 1:
yield "generator"
def callback():
if callback.gen is None:
callback.gen = generator()
return next(callback.gen)
callback.gen = None
old_trace = sys.gettrace()
sys.settrace(noop_trace)
try:
# Install a trace function
threading.settrace(noop_trace)
# Create a generator in a C thread which exits after the call
import _testcapi
_testcapi.call_in_temporary_c_thread(callback)
# Call the generator in a different Python thread, check that the
# generator didn't keep a reference to the destroyed thread state
for test in range(3):
# The trace function is still called here
callback()
finally:
sys.settrace(old_trace)
def test_gettrace(self):
def noop_trace(frame, event, arg):
# no operation
return noop_trace
old_trace = threading.gettrace()
try:
threading.settrace(noop_trace)
trace_func = threading.gettrace()
self.assertEqual(noop_trace,trace_func)
finally:
threading.settrace(old_trace)
def test_getprofile(self):
def fn(*args): pass
old_profile = threading.getprofile()
try:
threading.setprofile(fn)
self.assertEqual(fn, threading.getprofile())
finally:
threading.setprofile(old_profile)
@cpython_only
def test_shutdown_locks(self):
for daemon in (False, True):
with self.subTest(daemon=daemon):
event = threading.Event()
thread = threading.Thread(target=event.wait, daemon=daemon)
# Thread.start() must add lock to _shutdown_locks,
# but only for non-daemon thread
thread.start()
tstate_lock = thread._tstate_lock
if not daemon:
self.assertIn(tstate_lock, threading._shutdown_locks)
else:
self.assertNotIn(tstate_lock, threading._shutdown_locks)
# unblock the thread and join it
event.set()
thread.join()
# Thread._stop() must remove tstate_lock from _shutdown_locks.
# Daemon threads must never add it to _shutdown_locks.
self.assertNotIn(tstate_lock, threading._shutdown_locks)
def test_locals_at_exit(self):
# bpo-19466: thread locals must not be deleted before destructors
# are called
rc, out, err = assert_python_ok("-c", """if 1:
import threading
class Atexit:
def __del__(self):
print("thread_dict.atexit = %r" % thread_dict.atexit)
thread_dict = threading.local()
thread_dict.atexit = "value"
atexit = Atexit()
""")
self.assertEqual(out.rstrip(), b"thread_dict.atexit = 'value'")
def test_boolean_target(self):
# bpo-41149: A thread that had a boolean value of False would not
# run, regardless of whether it was callable. The correct behaviour
# is for a thread to do nothing if its target is None, and to call
# the target otherwise.
class BooleanTarget(object):
def __init__(self):
self.ran = False
def __bool__(self):
return False
def __call__(self):
self.ran = True
target = BooleanTarget()
thread = threading.Thread(target=target)
thread.start()
thread.join()
self.assertTrue(target.ran)
class ThreadJoinOnShutdown(BaseTestCase):
def _run_and_join(self, script):
script = """if 1:
import sys, os, time, threading
# a thread, which waits for the main program to terminate
def joiningfunc(mainthread):
mainthread.join()
print('end of thread')
# stdout is fully buffered because not a tty, we have to flush
# before exit.
sys.stdout.flush()
\n""" + script
rc, out, err = assert_python_ok("-c", script)
data = out.decode().replace('\r', '')
self.assertEqual(data, "end of main\nend of thread\n")
def test_1_join_on_shutdown(self):
# The usual case: on exit, wait for a non-daemon thread
script = """if 1:
import os
t = threading.Thread(target=joiningfunc,
args=(threading.current_thread(),))
t.start()
time.sleep(0.1)
print('end of main')
"""
self._run_and_join(script)
@unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
@unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
def test_2_join_in_forked_process(self):
# Like the test above, but from a forked interpreter
script = """if 1:
from test import support
childpid = os.fork()
if childpid != 0:
# parent process
support.wait_process(childpid, exitcode=0)
sys.exit(0)
# child process
t = threading.Thread(target=joiningfunc,
args=(threading.current_thread(),))
t.start()
print('end of main')
"""
self._run_and_join(script)
@unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
@unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
def test_3_join_in_forked_from_thread(self):
# Like the test above, but fork() was called from a worker thread
# In the forked process, the main Thread object must be marked as stopped.
script = """if 1:
from test import support
main_thread = threading.current_thread()
def worker():
childpid = os.fork()
if childpid != 0:
# parent process
support.wait_process(childpid, exitcode=0)
sys.exit(0)
# child process
t = threading.Thread(target=joiningfunc,
args=(main_thread,))
print('end of main')
t.start()
t.join() # Should not block: main_thread is already stopped
w = threading.Thread(target=worker)
w.start()
"""
self._run_and_join(script)
@unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
def test_4_daemon_threads(self):
# Check that a daemon thread cannot crash the interpreter on shutdown
# by manipulating internal structures that are being disposed of in
# the main thread.
script = """if True:
import os
import random
import sys
import time
import threading
thread_has_run = set()
def random_io():
'''Loop for a while sleeping random tiny amounts and doing some I/O.'''
while True:
with open(os.__file__, 'rb') as in_f:
stuff = in_f.read(200)
with open(os.devnull, 'wb') as null_f:
null_f.write(stuff)
time.sleep(random.random() / 1995)
thread_has_run.add(threading.current_thread())
def main():
count = 0
for _ in range(40):
new_thread = threading.Thread(target=random_io)
new_thread.daemon = True
new_thread.start()
count += 1
while len(thread_has_run) < count:
time.sleep(0.001)
# Trigger process shutdown
sys.exit(0)
main()
"""
rc, out, err = assert_python_ok('-c', script)
self.assertFalse(err)
@unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
@unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
def test_reinit_tls_after_fork(self):
# Issue #13817: fork() would deadlock in a multithreaded program with
# the ad-hoc TLS implementation.
def do_fork_and_wait():
# just fork a child process and wait it
pid = os.fork()
if pid > 0:
support.wait_process(pid, exitcode=50)
else:
os._exit(50)
# start a bunch of threads that will fork() child processes
threads = []
for i in range(16):
t = threading.Thread(target=do_fork_and_wait)
threads.append(t)
t.start()
for t in threads:
t.join()
@unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
def test_clear_threads_states_after_fork(self):
# Issue #17094: check that threads states are cleared after fork()
# start a bunch of threads
threads = []
for i in range(16):
t = threading.Thread(target=lambda : time.sleep(0.3))
threads.append(t)
t.start()
pid = os.fork()
if pid == 0:
# check that threads states have been cleared
if len(sys._current_frames()) == 1:
os._exit(51)
else:
os._exit(52)
else:
support.wait_process(pid, exitcode=51)
for t in threads:
t.join()
class SubinterpThreadingTests(BaseTestCase):
def pipe(self):
r, w = os.pipe()
self.addCleanup(os.close, r)
self.addCleanup(os.close, w)
if hasattr(os, 'set_blocking'):
os.set_blocking(r, False)
return (r, w)
def test_threads_join(self):
# Non-daemon threads should be joined at subinterpreter shutdown
# (issue #18808)
r, w = self.pipe()
code = textwrap.dedent(r"""
import os
import random
import threading
import time
def random_sleep():
seconds = random.random() * 0.010
time.sleep(seconds)
def f():
# Sleep a bit so that the thread is still running when
# Py_EndInterpreter is called.
random_sleep()
os.write(%d, b"x")
threading.Thread(target=f).start()
random_sleep()
""" % (w,))
ret = test.support.run_in_subinterp(code)
self.assertEqual(ret, 0)
# The thread was joined properly.
self.assertEqual(os.read(r, 1), b"x")
def test_threads_join_2(self):
# Same as above, but a delay gets introduced after the thread's
# Python code returned but before the thread state is deleted.
# To achieve this, we register a thread-local object which sleeps
# a bit when deallocated.
r, w = self.pipe()
code = textwrap.dedent(r"""
import os
import random
import threading
import time
def random_sleep():
seconds = random.random() * 0.010
time.sleep(seconds)
class Sleeper:
def __del__(self):
random_sleep()
tls = threading.local()
def f():
# Sleep a bit so that the thread is still running when
# Py_EndInterpreter is called.
random_sleep()
tls.x = Sleeper()
os.write(%d, b"x")
threading.Thread(target=f).start()
random_sleep()
""" % (w,))
ret = test.support.run_in_subinterp(code)
self.assertEqual(ret, 0)
# The thread was joined properly.
self.assertEqual(os.read(r, 1), b"x")
@cpython_only
def test_daemon_threads_fatal_error(self):
subinterp_code = f"""if 1:
import os
import threading
import time
def f():
# Make sure the daemon thread is still running when
# Py_EndInterpreter is called.
time.sleep({test.support.SHORT_TIMEOUT})
threading.Thread(target=f, daemon=True).start()
"""
script = r"""if 1:
import _testcapi
_testcapi.run_in_subinterp(%r)
""" % (subinterp_code,)
with test.support.SuppressCrashReport():
rc, out, err = assert_python_failure("-c", script)
self.assertIn("Fatal Python error: Py_EndInterpreter: "
"not the last thread", err.decode())
class ThreadingExceptionTests(BaseTestCase):
# A RuntimeError should be raised if Thread.start() is called
# multiple times.
def test_start_thread_again(self):
thread = threading.Thread()
thread.start()
self.assertRaises(RuntimeError, thread.start)
thread.join()
def test_joining_current_thread(self):
current_thread = threading.current_thread()
self.assertRaises(RuntimeError, current_thread.join);
def test_joining_inactive_thread(self):
thread = threading.Thread()
self.assertRaises(RuntimeError, thread.join)
def test_daemonize_active_thread(self):
thread = threading.Thread()
thread.start()
self.assertRaises(RuntimeError, setattr, thread, "daemon", True)
thread.join()
def test_releasing_unacquired_lock(self):
lock = threading.Lock()
self.assertRaises(RuntimeError, lock.release)
def test_recursion_limit(self):
# Issue 9670
# test that excessive recursion within a non-main thread causes
# an exception rather than crashing the interpreter on platforms
# like Mac OS X or FreeBSD which have small default stack sizes
# for threads
script = """if True:
import threading
def recurse():
return recurse()
def outer():
try:
recurse()
except RecursionError:
pass
w = threading.Thread(target=outer)
w.start()
w.join()
print('end of main thread')
"""
expected_output = "end of main thread\n"
p = subprocess.Popen([sys.executable, "-c", script],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
data = stdout.decode().replace('\r', '')
self.assertEqual(p.returncode, 0, "Unexpected error: " + stderr.decode())
self.assertEqual(data, expected_output)
def test_print_exception(self):
script = r"""if True:
import threading
import time
running = False
def run():
global running
running = True
while running:
time.sleep(0.01)
1/0
t = threading.Thread(target=run)
t.start()
while not running:
time.sleep(0.01)
running = False
t.join()
"""
rc, out, err = assert_python_ok("-c", script)
self.assertEqual(out, b'')
err = err.decode()
self.assertIn("Exception in thread", err)
self.assertIn("Traceback (most recent call last):", err)
self.assertIn("ZeroDivisionError", err)
self.assertNotIn("Unhandled exception", err)
def test_print_exception_stderr_is_none_1(self):
script = r"""if True:
import sys
import threading
import time
running = False
def run():
global running
running = True
while running:
time.sleep(0.01)
1/0
t = threading.Thread(target=run)
t.start()
while not running:
time.sleep(0.01)
sys.stderr = None
running = False
t.join()
"""
rc, out, err = assert_python_ok("-c", script)
self.assertEqual(out, b'')
err = err.decode()
self.assertIn("Exception in thread", err)
self.assertIn("Traceback (most recent call last):", err)
self.assertIn("ZeroDivisionError", err)
self.assertNotIn("Unhandled exception", err)
def test_print_exception_stderr_is_none_2(self):
script = r"""if True:
import sys
import threading
import time
running = False
def run():
global running
running = True
while running:
time.sleep(0.01)
1/0
sys.stderr = None
t = threading.Thread(target=run)
t.start()
while not running:
time.sleep(0.01)
running = False
t.join()
"""
rc, out, err = assert_python_ok("-c", script)
self.assertEqual(out, b'')
self.assertNotIn("Unhandled exception", err.decode())
def test_bare_raise_in_brand_new_thread(self):
def bare_raise():
raise
class Issue27558(threading.Thread):
exc = None
def run(self):
try:
bare_raise()
except Exception as exc:
self.exc = exc
thread = Issue27558()
thread.start()
thread.join()
self.assertIsNotNone(thread.exc)
self.assertIsInstance(thread.exc, RuntimeError)
# explicitly break the reference cycle to not leak a dangling thread
thread.exc = None
class ThreadRunFail(threading.Thread):
def run(self):
raise ValueError("run failed")
class ExceptHookTests(BaseTestCase):
def setUp(self):
restore_default_excepthook(self)
super().setUp()
def test_excepthook(self):
with support.captured_output("stderr") as stderr:
thread = ThreadRunFail(name="excepthook thread")
thread.start()
thread.join()
stderr = stderr.getvalue().strip()
self.assertIn(f'Exception in thread {thread.name}:\n', stderr)
self.assertIn('Traceback (most recent call last):\n', stderr)
self.assertIn(' raise ValueError("run failed")', stderr)
self.assertIn('ValueError: run failed', stderr)
@support.cpython_only
def test_excepthook_thread_None(self):
# threading.excepthook called with thread=None: log the thread
# identifier in this case.
with support.captured_output("stderr") as stderr:
try:
raise ValueError("bug")
except Exception as exc:
args = threading.ExceptHookArgs([*sys.exc_info(), None])
try:
threading.excepthook(args)
finally:
# Explicitly break a reference cycle
args = None
stderr = stderr.getvalue().strip()
self.assertIn(f'Exception in thread {threading.get_ident()}:\n', stderr)
self.assertIn('Traceback (most recent call last):\n', stderr)
self.assertIn(' raise ValueError("bug")', stderr)
self.assertIn('ValueError: bug', stderr)
def test_system_exit(self):
class ThreadExit(threading.Thread):
def run(self):
sys.exit(1)
# threading.excepthook() silently ignores SystemExit
with support.captured_output("stderr") as stderr:
thread = ThreadExit()
thread.start()
thread.join()
self.assertEqual(stderr.getvalue(), '')
def test_custom_excepthook(self):
args = None
def hook(hook_args):
nonlocal args
args = hook_args
try:
with support.swap_attr(threading, 'excepthook', hook):
thread = ThreadRunFail()
thread.start()
thread.join()
self.assertEqual(args.exc_type, ValueError)
self.assertEqual(str(args.exc_value), 'run failed')
self.assertEqual(args.exc_traceback, args.exc_value.__traceback__)
self.assertIs(args.thread, thread)
finally:
# Break reference cycle
args = None
def test_custom_excepthook_fail(self):
def threading_hook(args):
raise ValueError("threading_hook failed")
err_str = None
def sys_hook(exc_type, exc_value, exc_traceback):
nonlocal err_str
err_str = str(exc_value)
with support.swap_attr(threading, 'excepthook', threading_hook), \
support.swap_attr(sys, 'excepthook', sys_hook), \
support.captured_output('stderr') as stderr:
thread = ThreadRunFail()
thread.start()
thread.join()
self.assertEqual(stderr.getvalue(),
'Exception in threading.excepthook:\n')
self.assertEqual(err_str, 'threading_hook failed')
def test_original_excepthook(self):
def run_thread():
with support.captured_output("stderr") as output:
thread = ThreadRunFail(name="excepthook thread")
thread.start()
thread.join()
return output.getvalue()
def threading_hook(args):
print("Running a thread failed", file=sys.stderr)
default_output = run_thread()
with support.swap_attr(threading, 'excepthook', threading_hook):
custom_hook_output = run_thread()
threading.excepthook = threading.__excepthook__
recovered_output = run_thread()
self.assertEqual(default_output, recovered_output)
self.assertNotEqual(default_output, custom_hook_output)
self.assertEqual(custom_hook_output, "Running a thread failed\n")
class TimerTests(BaseTestCase):
def setUp(self):
BaseTestCase.setUp(self)
self.callback_args = []
self.callback_event = threading.Event()
def test_init_immutable_default_args(self):
# Issue 17435: constructor defaults were mutable objects, they could be
# mutated via the object attributes and affect other Timer objects.
timer1 = threading.Timer(0.01, self._callback_spy)
timer1.start()
self.callback_event.wait()
timer1.args.append("blah")
timer1.kwargs["foo"] = "bar"
self.callback_event.clear()
timer2 = threading.Timer(0.01, self._callback_spy)
timer2.start()
self.callback_event.wait()
self.assertEqual(len(self.callback_args), 2)
self.assertEqual(self.callback_args, [((), {}), ((), {})])
timer1.join()
timer2.join()
def _callback_spy(self, *args, **kwargs):
self.callback_args.append((args[:], kwargs.copy()))
self.callback_event.set()
class LockTests(lock_tests.LockTests):
locktype = staticmethod(threading.Lock)
class PyRLockTests(lock_tests.RLockTests):
locktype = staticmethod(threading._PyRLock)
@unittest.skipIf(threading._CRLock is None, 'RLock not implemented in C')
class CRLockTests(lock_tests.RLockTests):
locktype = staticmethod(threading._CRLock)
class EventTests(lock_tests.EventTests):
eventtype = staticmethod(threading.Event)
class ConditionAsRLockTests(lock_tests.RLockTests):
# Condition uses an RLock by default and exports its API.
locktype = staticmethod(threading.Condition)
class ConditionTests(lock_tests.ConditionTests):
condtype = staticmethod(threading.Condition)
class SemaphoreTests(lock_tests.SemaphoreTests):
semtype = staticmethod(threading.Semaphore)
class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
semtype = staticmethod(threading.BoundedSemaphore)
class BarrierTests(lock_tests.BarrierTests):
barriertype = staticmethod(threading.Barrier)
class MiscTestCase(unittest.TestCase):
def test__all__(self):
restore_default_excepthook(self)
extra = {"ThreadError"}
not_exported = {'currentThread', 'activeCount'}
support.check__all__(self, threading, ('threading', '_thread'),
extra=extra, not_exported=not_exported)
class InterruptMainTests(unittest.TestCase):
def check_interrupt_main_with_signal_handler(self, signum):
def handler(signum, frame):
1/0
old_handler = signal.signal(signum, handler)
self.addCleanup(signal.signal, signum, old_handler)
with self.assertRaises(ZeroDivisionError):
_thread.interrupt_main()
def check_interrupt_main_noerror(self, signum):
handler = signal.getsignal(signum)
try:
# No exception should arise.
signal.signal(signum, signal.SIG_IGN)
_thread.interrupt_main(signum)
signal.signal(signum, signal.SIG_DFL)
_thread.interrupt_main(signum)
finally:
# Restore original handler
signal.signal(signum, handler)
def test_interrupt_main_subthread(self):
# Calling start_new_thread with a function that executes interrupt_main
# should raise KeyboardInterrupt upon completion.
def call_interrupt():
_thread.interrupt_main()
t = threading.Thread(target=call_interrupt)
with self.assertRaises(KeyboardInterrupt):
t.start()
t.join()
t.join()
def test_interrupt_main_mainthread(self):
# Make sure that if interrupt_main is called in main thread that
# KeyboardInterrupt is raised instantly.
with self.assertRaises(KeyboardInterrupt):
_thread.interrupt_main()
def test_interrupt_main_with_signal_handler(self):
self.check_interrupt_main_with_signal_handler(signal.SIGINT)
self.check_interrupt_main_with_signal_handler(signal.SIGTERM)
def test_interrupt_main_noerror(self):
self.check_interrupt_main_noerror(signal.SIGINT)
self.check_interrupt_main_noerror(signal.SIGTERM)
def test_interrupt_main_invalid_signal(self):
self.assertRaises(ValueError, _thread.interrupt_main, -1)
self.assertRaises(ValueError, _thread.interrupt_main, signal.NSIG)
self.assertRaises(ValueError, _thread.interrupt_main, 1000000)
class AtexitTests(unittest.TestCase):
def test_atexit_output(self):
rc, out, err = assert_python_ok("-c", """if True:
import threading
def run_last():
print('parrot')
threading._register_atexit(run_last)
""")
self.assertFalse(err)
self.assertEqual(out.strip(), b'parrot')
def test_atexit_called_once(self):
rc, out, err = assert_python_ok("-c", """if True:
import threading
from unittest.mock import Mock
mock = Mock()
threading._register_atexit(mock)
mock.assert_not_called()
# force early shutdown to ensure it was called once
threading._shutdown()
mock.assert_called_once()
""")
self.assertFalse(err)
def test_atexit_after_shutdown(self):
# The only way to do this is by registering an atexit within
# an atexit, which is intended to raise an exception.
rc, out, err = assert_python_ok("-c", """if True:
import threading
def func():
pass
def run_last():
threading._register_atexit(func)
threading._register_atexit(run_last)
""")
self.assertTrue(err)
self.assertIn("RuntimeError: can't register atexit after shutdown",
err.decode())
if __name__ == "__main__":
unittest.main()
|
test_dota_ms.py | # -*- coding:utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import os
import sys
import tensorflow as tf
import cv2
import numpy as np
import math
from tqdm import tqdm
import argparse
from multiprocessing import Queue, Process
sys.path.append("../")
from data.io.image_preprocess import short_side_resize_for_inference_data
from libs.networks import build_whole_network
from help_utils import tools
from libs.label_name_dict.label_dict import *
from libs.box_utils import draw_box_in_img
from libs.box_utils.coordinate_convert import forward_convert, backward_convert
from libs.box_utils import nms_rotate
from libs.box_utils.rotate_polygon_nms import rotate_gpu_nms
def worker(gpu_id, images, det_net, args, result_queue):
os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu_id)
img_plac = tf.placeholder(dtype=tf.uint8, shape=[None, None, 3]) # is RGB. not BGR
img_batch = tf.cast(img_plac, tf.float32)
img_batch = short_side_resize_for_inference_data(img_tensor=img_batch,
target_shortside_len=cfgs.IMG_SHORT_SIDE_LEN,
length_limitation=cfgs.IMG_MAX_LENGTH,
is_resize=not args.multi_scale)
if cfgs.NET_NAME in ['resnet152_v1d', 'resnet101_v1d', 'resnet50_v1d']:
img_batch = (img_batch / 255 - tf.constant(cfgs.PIXEL_MEAN_)) / tf.constant(cfgs.PIXEL_STD)
else:
img_batch = img_batch - tf.constant(cfgs.PIXEL_MEAN)
img_batch = tf.expand_dims(img_batch, axis=0)
detection_boxes, detection_scores, detection_category = det_net.build_whole_detection_network(
input_img_batch=img_batch,
gtboxes_batch=None,
gtboxes_r_batch=None,
gpu_id=0)
init_op = tf.group(
tf.global_variables_initializer(),
tf.local_variables_initializer()
)
restorer, restore_ckpt = det_net.get_restorer()
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
with tf.Session(config=config) as sess:
sess.run(init_op)
if not restorer is None:
restorer.restore(sess, restore_ckpt)
print('restore model %d ...' % gpu_id)
for img_path in images:
# if 'P0016' not in img_path:
# continue
img = cv2.imread(img_path)
box_res_rotate = []
label_res_rotate = []
score_res_rotate = []
imgH = img.shape[0]
imgW = img.shape[1]
img_short_side_len_list = cfgs.IMG_SHORT_SIDE_LEN if args.multi_scale else [cfgs.IMG_SHORT_SIDE_LEN]
if imgH < args.h_len:
temp = np.zeros([args.h_len, imgW, 3], np.float32)
temp[0:imgH, :, :] = img
img = temp
imgH = args.h_len
if imgW < args.w_len:
temp = np.zeros([imgH, args.w_len, 3], np.float32)
temp[:, 0:imgW, :] = img
img = temp
imgW = args.w_len
for hh in range(0, imgH, args.h_len - args.h_overlap):
if imgH - hh - 1 < args.h_len:
hh_ = imgH - args.h_len
else:
hh_ = hh
for ww in range(0, imgW, args.w_len - args.w_overlap):
if imgW - ww - 1 < args.w_len:
ww_ = imgW - args.w_len
else:
ww_ = ww
src_img = img[hh_:(hh_ + args.h_len), ww_:(ww_ + args.w_len), :]
for short_size in img_short_side_len_list:
max_len = cfgs.IMG_MAX_LENGTH
if args.h_len < args.w_len:
new_h, new_w = short_size, min(int(short_size * float(args.w_len) / args.h_len), max_len)
else:
new_h, new_w = min(int(short_size * float(args.h_len) / args.w_len), max_len), short_size
img_resize = cv2.resize(src_img, (new_w, new_h))
resized_img, det_boxes_r_, det_scores_r_, det_category_r_ = \
sess.run(
[img_batch, detection_boxes, detection_scores, detection_category],
feed_dict={img_plac: img_resize[:, :, ::-1]}
)
resized_h, resized_w = resized_img.shape[1], resized_img.shape[2]
src_h, src_w = src_img.shape[0], src_img.shape[1]
if len(det_boxes_r_) > 0:
det_boxes_r_ = forward_convert(det_boxes_r_, False)
det_boxes_r_[:, 0::2] *= (src_w / resized_w)
det_boxes_r_[:, 1::2] *= (src_h / resized_h)
det_boxes_r_ = backward_convert(det_boxes_r_, False)
for ii in range(len(det_boxes_r_)):
box_rotate = det_boxes_r_[ii]
box_rotate[0] = box_rotate[0] + ww_
box_rotate[1] = box_rotate[1] + hh_
box_res_rotate.append(box_rotate)
label_res_rotate.append(det_category_r_[ii])
score_res_rotate.append(det_scores_r_[ii])
box_res_rotate = np.array(box_res_rotate)
label_res_rotate = np.array(label_res_rotate)
score_res_rotate = np.array(score_res_rotate)
filter_indices = score_res_rotate >= 0.05
score_res_rotate = score_res_rotate[filter_indices]
box_res_rotate = box_res_rotate[filter_indices]
label_res_rotate = label_res_rotate[filter_indices]
box_res_rotate_ = []
label_res_rotate_ = []
score_res_rotate_ = []
threshold = {'roundabout': 0.1, 'tennis-court': 0.3, 'swimming-pool': 0.1, 'storage-tank': 0.1,
'soccer-ball-field': 0.3, 'small-vehicle': 0.05, 'ship': 0.05, 'plane': 0.3,
'large-vehicle': 0.05, 'helicopter': 0.2, 'harbor': 0.0001, 'ground-track-field': 0.3,
'bridge': 0.0001, 'basketball-court': 0.3, 'baseball-diamond': 0.3, 'container-crane': 0.3}
for sub_class in range(1, cfgs.CLASS_NUM + 1):
index = np.where(label_res_rotate == sub_class)[0]
if len(index) == 0:
continue
tmp_boxes_r = box_res_rotate[index]
tmp_label_r = label_res_rotate[index]
tmp_score_r = score_res_rotate[index]
tmp_boxes_r = np.array(tmp_boxes_r)
tmp = np.zeros([tmp_boxes_r.shape[0], tmp_boxes_r.shape[1] + 1])
tmp[:, 0:-1] = tmp_boxes_r
tmp[:, -1] = np.array(tmp_score_r)
try:
inx = nms_rotate.nms_rotate_cpu(boxes=np.array(tmp_boxes_r),
scores=np.array(tmp_score_r),
iou_threshold=threshold[LABEL_NAME_MAP[sub_class]],
max_output_size=500)
except:
# Note: the IoU of two same rectangles is 0, which is calculated by rotate_gpu_nms
jitter = np.zeros([tmp_boxes_r.shape[0], tmp_boxes_r.shape[1] + 1])
jitter[:, 0] += np.random.rand(tmp_boxes_r.shape[0], ) / 1000
inx = rotate_gpu_nms(np.array(tmp, np.float32) + np.array(jitter, np.float32),
float(threshold[LABEL_NAME_MAP[sub_class]]), 0)
box_res_rotate_.extend(np.array(tmp_boxes_r)[inx])
score_res_rotate_.extend(np.array(tmp_score_r)[inx])
label_res_rotate_.extend(np.array(tmp_label_r)[inx])
result_dict = {'boxes': np.array(box_res_rotate_), 'scores': np.array(score_res_rotate_),
'labels': np.array(label_res_rotate_), 'image_id': img_path}
result_queue.put_nowait(result_dict)
def test_dota(det_net, real_test_img_list, args, txt_name):
save_path = os.path.join('./test_dota', cfgs.VERSION)
nr_records = len(real_test_img_list)
pbar = tqdm(total=nr_records)
gpu_num = len(args.gpus.strip().split(','))
nr_image = math.ceil(nr_records / gpu_num)
result_queue = Queue(500)
procs = []
for i, gpu_id in enumerate(args.gpus.strip().split(',')):
start = i * nr_image
end = min(start + nr_image, nr_records)
split_records = real_test_img_list[start:end]
proc = Process(target=worker, args=(int(gpu_id), split_records, det_net, args, result_queue))
print('process:%d, start:%d, end:%d' % (i, start, end))
proc.start()
procs.append(proc)
for i in range(nr_records):
res = result_queue.get()
if args.show_box:
nake_name = res['image_id'].split('/')[-1]
tools.mkdir(os.path.join(save_path, 'dota_img_vis'))
draw_path = os.path.join(save_path, 'dota_img_vis', nake_name)
draw_img = np.array(cv2.imread(res['image_id']), np.float32)
detected_indices = res['scores'] >= cfgs.SHOW_SCORE_THRSHOLD
detected_scores = res['scores'][detected_indices]
detected_boxes = res['boxes'][detected_indices]
detected_categories = res['labels'][detected_indices]
final_detections = draw_box_in_img.draw_boxes_with_label_and_scores(draw_img,
boxes=detected_boxes,
labels=detected_categories,
scores=detected_scores,
method=1,
in_graph=False)
cv2.imwrite(draw_path, final_detections)
else:
CLASS_DOTA = NAME_LABEL_MAP.keys()
write_handle = {}
tools.mkdir(os.path.join(save_path, 'dota_res'))
for sub_class in CLASS_DOTA:
if sub_class == 'back_ground':
continue
write_handle[sub_class] = open(os.path.join(save_path, 'dota_res', 'Task1_%s.txt' % sub_class), 'a+')
rboxes = forward_convert(res['boxes'], with_label=False)
for i, rbox in enumerate(rboxes):
command = '%s %.3f %.1f %.1f %.1f %.1f %.1f %.1f %.1f %.1f\n' % (res['image_id'].split('/')[-1].split('.')[0],
res['scores'][i],
rbox[0], rbox[1], rbox[2], rbox[3],
rbox[4], rbox[5], rbox[6], rbox[7],)
write_handle[LABEL_NAME_MAP[res['labels'][i]]].write(command)
for sub_class in CLASS_DOTA:
if sub_class == 'back_ground':
continue
write_handle[sub_class].close()
fw = open(txt_name, 'a+')
fw.write('{}\n'.format(res['image_id'].split('/')[-1]))
fw.close()
pbar.set_description("Test image %s" % res['image_id'].split('/')[-1])
pbar.update(1)
for p in procs:
p.join()
def eval(num_imgs, args):
txt_name = '{}.txt'.format(cfgs.VERSION)
if not args.show_box:
if not os.path.exists(txt_name):
fw = open(txt_name, 'w')
fw.close()
fr = open(txt_name, 'r')
img_filter = fr.readlines()
print('****************************'*3)
print('Already tested imgs:', img_filter)
print('****************************'*3)
fr.close()
test_imgname_list = [os.path.join(args.test_dir, img_name) for img_name in os.listdir(args.test_dir)
if img_name.endswith(('.jpg', '.png', '.jpeg', '.tif', '.tiff')) and
(img_name + '\n' not in img_filter)]
else:
test_imgname_list = [os.path.join(args.test_dir, img_name) for img_name in os.listdir(args.test_dir)
if img_name.endswith(('.jpg', '.png', '.jpeg', '.tif', '.tiff'))]
assert len(test_imgname_list) != 0, 'test_dir has no imgs there.' \
' Note that, we only support img format of (.jpg, .png, and .tiff) '
if num_imgs == np.inf:
real_test_img_list = test_imgname_list
else:
real_test_img_list = test_imgname_list[: num_imgs]
fpn = build_whole_network.DetectionNetwork(
base_network_name=cfgs.NET_NAME,
is_training=False)
test_dota(det_net=fpn, real_test_img_list=real_test_img_list, args=args, txt_name=txt_name)
if not args.show_box:
os.remove(txt_name)
def parse_args():
parser = argparse.ArgumentParser('evaluate the result.')
parser.add_argument('--test_dir', dest='test_dir',
help='evaluate imgs dir ',
default='/data/dataset/DOTA/test/images/', type=str)
parser.add_argument('--gpus', dest='gpus',
help='gpu id',
default='0,1,2,3,4,5,6,7', type=str)
parser.add_argument('--eval_num', dest='eval_num',
help='the num of eval imgs',
default=np.inf, type=int)
parser.add_argument('--show_box', '-s', default=False,
action='store_true')
parser.add_argument('--multi_scale', '-ms', default=False,
action='store_true')
parser.add_argument('--h_len', dest='h_len',
help='image height',
default=800, type=int)
parser.add_argument('--w_len', dest='w_len',
help='image width',
default=800, type=int)
parser.add_argument('--h_overlap', dest='h_overlap',
help='height overlap',
default=200, type=int)
parser.add_argument('--w_overlap', dest='w_overlap',
help='width overlap',
default=200, type=int)
args = parser.parse_args()
return args
if __name__ == '__main__':
args = parse_args()
print(20*"--")
print(args)
print(20*"--")
eval(args.eval_num,
args=args)
|
kademlia_v05.py | """An upgrade of the previous to provide support for a naive broadcast message type."""
from __future__ import annotations
import socket
from collections import defaultdict
from copy import deepcopy
from concurrent.futures import Future
from datetime import datetime, timezone
from functools import partial
from itertools import chain
from logging import getLogger
from os import urandom
from sched import scheduler
from traceback import format_exc
from threading import Thread
from time import sleep, time
from typing import Any, DefaultDict, Dict, Iterator, List, Optional, Set, Tuple, Union
try:
from queue import SimpleQueue # added in 3.7
except ImportError:
from queue import Queue as SimpleQueue # type: ignore
from umsgpack import packb, unpackb
from .protocol.v05 import (distance, preferred_compression, AckMessage, Address, AddressType, BroadcastMessage,
ChannelInfo, CompressType, GlobalPeerInfo, GoodbyeMessage, HelloMessage, IdentifyMessage,
Message, NetworkConfiguration, FindKeyMessage, FindNodeMessage, PeerInfo, StoreKeyMessage)
# TODO: what happens if someone has a local address as the first item in addresses? do you send a message to them,
# not see an exception, and just think they're not listening? There needs to be some mechanism to handle this.
# Maybe I should send to all of them and have it so that nodes use the one they last heard on
# Alternately, I could have a timeout mechanism so that if in some timeout period it didn't hear back it tries the next
# address in the list. This list could be shuffled either randomly or by preference or not at all.
# TODO: better broadcast algorithm
# TODO: support multiple routing tables so nodes can listen on two or more networks
# this would allow you to help maintain the bootstrap network while joining your own, for instance.
# might be reasonable to make "channels" in my incoming messages to determine which network it's for
# Maybe we do a thing where the things in FindNode are a mapping of NetworkConfiguration to GlobalNodeInfo,
# then nodes can use it to fill all of their routing tables in fewer messages.
# should clock sync include all listening networks or be specific to a channel? yes
# Make sure to note in protocol docs that nodes without multi-channel support should be possible
# outline the four example combinations and how they would work of (mono, multi) x (threaded, event loop)
# this is in progress:
# - [x] Add channel to message
# - [x] Add to GlobalPeerInfo somehow
# - [x] Remove single ID from GlobalPeerInfo
# - [x] Add storage[channel]
# - [x] Add channel to send APIs
# - [x] Add multiple ID support
# - [x] Add multiple routing table support
# - [x] Add bootstrap network support
# - [ ] Allow for nodes to have different channel numbers for the same network
# TODO: Add pruning of nodes with high miss counts
# TODO: Actually spawn instances on the servers I listed
# TODO: Add multicast messages support
# progress
# - [ ] Add target field to Messages
# - [ ] Add support for standard routed messages
# If you have seen this message before, disregard it
# If your ID is target, process without assuming the address is correct
# If it isn't, find the alpha closest nodes to target and send to them
# If the target is in said list, send only to target
# - [ ] Add support for multicast with the following algorithm
# Sender calculates closest alpha nodes to each target and notes which are associated with which
# Treat as if it was a routed message for each target, except that the responses should contain lists of peers
# When forwarding, join messages together where possible. For instance, if 1000101..., is closest to targets A
# b, then send targets as [a, b]
# note that both this and the above are terrible algorithms that shouldn't stay around for too long
# produces |targets| * alpha ^ log_{2^b}(n) messages in the worst case, which is potentially very high
# Overall Progress:
# - [x] An object model and serialization standard that can be used easily in most languages
# - [x] A simple high-level API (along with a fine-grained one)
# - [x] log(n) distributed hash table get/sets
# - [x] Support for disabling DHT support network-wide
# - [ ] Support for "edge nodes" which do not store DHT data except as a cache
# - [x] log(n) broadcast delivery time
# - [ ] log(n) routed message delivery
# - [ ] Support for multicast routed messages
# - [ ] Support for in-protocol group messages
# - [x] Transparent (to the developer) compression
# - [ ] transparent (to the user) encryption
# - [ ] Support for multiple transport protocols (TCP, UDP, etc.)
# - [ ] Support for "virtual transports" (using other nodes as a bridge)
# - [x] A well-defined standard configuration space
# - [x] Support for extension subprotocols and implementation-specific configurations
bootstrap_info = NetworkConfiguration(channel=-1, k=6, b=4, h_name="SHA256")
bootstrap_seeds = (
(0, ('euclid.nmu.edu', 44565)),
(0, ('williac.nmu.edu', 44565)),
(0, ('acai.host.gabeappleton.me', 44565)),
(0, ('bato.host.gabeappleton.me', 44565)),
)
def time_func() -> int:
"""Return milliseconds since UTC epoch."""
return int(datetime.now(tz=timezone.utc).timestamp() * 1000)
class RoutingTable:
__slots__ = {
'logger': 'A handle to the logging module',
'config': 'A reference to your network configuration',
'ref_id': 'The node you are routing for',
'distance': 'A partial function which pre-fills your node id in the standard distance function',
'table': 'The main routing table divided into h subgroups of 2^b - 1 buckets. Each bucket is a '
'mapping from id to sock index, addr pairs',
'member_info': 'This mapping of id to PeerInfo objects keeps much richer data for each peer for easier access',
'delay': 'The number of seconds you should next wait before looking for new nodes. Reset every time a node is '
'added or removed, doubles every time you look for them.'
}
def __init__(self, ref_id: bytes, config: NetworkConfiguration):
self.logger = getLogger(f'KademliaNode[id={ref_id.hex()}].routing_table')
self.config = config
self.ref_id = ref_id
self.distance = partial(distance, ref_id)
self.table: Tuple[Tuple[Dict[bytes, Tuple[int, Tuple[Any, ...]]], ...], ...] = \
tuple(tuple({} for _ in range(1 << config.b)) for _ in range(config.h * 8 // config.b + 1))
self.member_info: Dict[bytes, PeerInfo] = {}
self.delay = 60
def add(self, name: bytes, addr: Tuple[Any, ...], sock: int) -> bool:
"""Add a node to your routing table, initially containing only the minimum viable information.
To add more info, directly modify the PeerInfo object in routing_table.member_info.
"""
if name == self.ref_id:
self.logger.info("Tried to add myself to my routing table")
return False
elif name in self.member_info:
self.logger.info("Tried to add a node that's already in the table for some reason")
return False
dist = self.distance(name)
if self.config.b == 1:
row = self.table[dist.bit_length() - 1][0]
else:
# TODO: verify the math here. I might have an error somewhere in here.
group = self.table[(dist.bit_length() - 1) // self.config.b]
row = group[(dist - 1) % (1 << self.config.b)]
if len(row) < self.config.k:
self.logger.info("Added %s to our routing table", name.hex())
row[name] = (sock, addr)
self.member_info[name] = PeerInfo(name, addr, sock, self.ref_id)
self.logger.debug("A node was added, so I'm resetting the delay to next look for peers")
self.delay = 60
return True
self.logger.info("Would add %s to our routing table, but that bucket is full", name.hex())
return False
def remove(self, name: bytes) -> None:
"""Remove a node from your routing table, if it is present."""
if name in self:
self.logger.info("Removing %s from our routing table", name.hex())
dist = self.distance(name)
if self.config.b == 1:
row = self.table[dist.bit_length() - 1][0]
else:
# TODO: verify the math here. I might have an error somewhere in here.
group = self.table[(dist.bit_length() - 1) // self.config.b]
row = group[(dist - 1) % (1 << self.config.b)]
del row[name]
del self.member_info[name]
self.logger.debug("A node was removed, so I'm resetting the delay to next look for peers")
self.delay = 60
else:
self.logger.info("Would remove %s from our routing table, but they aren't there", name.hex())
def __contains__(self, addr: Union[bytes, Address, Tuple[Any, ...]]) -> bool:
"""Look up if a name, address, or tuple-formatted address is in your routing table."""
if isinstance(addr, bytes):
return addr in self.member_info
if isinstance(addr, tuple):
return (addr in (peer.local.addr for peer in self.member_info.values()))
return addr in chain.from_iterable(peer.public.addresses for peer in self.member_info.values())
def __iter__(self) -> Iterator[PeerInfo]:
"""Iterate through the routing table."""
yield from self.member_info.values()
def register_refresh(self) -> None:
"""Increase the delay between next looking for nodes."""
self.logger.debug("A refresh event was triggered, so I'm doubling the delay to next look for peers")
self.delay *= 2
def by_address(self, addr: Union[Address, Tuple[Any, ...]]) -> Optional[PeerInfo]:
"""Look up a node in your routing table by their address."""
if isinstance(addr, tuple):
for peer in self.member_info.values():
if addr == peer.local.addr:
return peer
for address in peer.public.addresses:
if address.args == addr:
return peer
for peer in self.member_info.values():
if addr in peer.public.addresses:
return peer
return None
def nearest(self, target: bytes, amount: Optional[int] = None) -> Dict[int, PeerInfo]:
"""Return up to the nearest k nodes to some target."""
if amount is None:
amount = self.config.k
dist = self.distance(target)
try:
if self.config.b == 1:
row = self.table[dist.bit_length() - 1][0]
else:
# TODO: verify the math here. I might have an error somewhere in here.
group = self.table[(dist.bit_length() - 1) // self.config.b]
row = group[(dist - 1) % (1 << self.config.b)]
if len(row) >= amount:
ret: Dict[int, PeerInfo] = {}
for name in sorted(row, key=lambda x: distance(x, target))[:amount]:
ret[distance(target, name)] = self.member_info[name]
return ret
except IndexError:
self.logger.exception("Hey, I hit that known bug again!")
ret = {
distance(target, x.public.channels[self.config.channel].id): x for x in self
if self.config.channel in x.public.channels
}
if len(ret) > self.config.k:
new_ret: Dict[int, PeerInfo] = {}
while len(new_ret) < amount:
k = min(ret)
new_ret[k] = ret.pop(k)
ret = new_ret
return ret
class KademliaNode:
__slots__ = {
'logger': 'A handle to the logging module',
'routing_table': 'A handle to your routing table',
'preferred_compression': 'The list of compression methods this node is able to use, in order of preference',
'socks': 'The list of listening sockets for this node',
'storage': 'The table which holds the keys you are responsible for holding, with entries clearing inversely '
'proportional to the square of its distance from you',
'awaiting_ack': 'The list of messages waiting for an ACK',
'timeouts': 'The list of timeout events to clear messages that would be waiting for ACKs',
'daemons': 'The list of currently running daemons for this node (should be num_sockets + 2)',
'addresses': 'The list of MessagePack-encodable addresses you are listening on',
'seen_broadcasts': 'A set of sender, idx pairs of recently seen broadcast messages, used to filter the naive '
'broadcast algorithm',
'message_queue': 'The queue of newly received messages for processing by the reactor thread',
'schedule': 'The queue of upcoming events for the heartbeat thread to execute, largely pings and looking for '
'new nodes',
'_local_time': 'The local HLC timestamp of this node',
'errors': 'The formatted error and tracebacks of problems this node has encountered in its daemons',
'self_info': 'The GlobalPeerInfo object describing this node',
'groups': 'A mapping of group names you are a member of to the list of members',
}
def __init__(self, port: int):
self.errors: List[str] = []
self._local_time: Tuple[int, int] = (time_func(), 0)
self.logger = getLogger(f'KademliaNode[id={id(self)}]')
self.logger.debug("My preferred compression methods are %r", preferred_compression)
self.preferred_compression = preferred_compression
self.schedule = scheduler()
self.socks = [socket.socket(socket.AF_INET, socket.SOCK_DGRAM),
socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)]
self.socks[1].setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, True)
self.routing_table: Dict[int, RoutingTable] = {}
self.awaiting_ack: Dict[Tuple[int, int], Message] = {}
self.message_queue: SimpleQueue[Tuple[Message, Tuple[Any, ...], socket.socket]] = SimpleQueue()
self.storage: DefaultDict[int, Dict[bytes, Any]] = defaultdict(dict)
self.timeouts: DefaultDict[int, Dict[Union[bytes, Tuple[bytes]], Any]] = defaultdict(dict)
self.groups: DefaultDict[int, DefaultDict[str, List[bytes]]] = defaultdict(lambda: defaultdict(list))
self.daemons: List[Thread] = []
self.addresses: List[Address] = []
self.seen_broadcasts: Set[Tuple[bytes, Tuple[int, int]]] = set()
self.self_info = GlobalPeerInfo(
addresses=self.addresses,
compression=preferred_compression
)
for sock, addr, family, rand_addr in zip(
self.socks,
('0.0.0.0', '::'),
(socket.AF_INET, socket.AF_INET6),
('8.8.8.8', '2606:4700:4700::1111')
):
self.logger.debug("Setting up a listening address on %r", addr)
daemon = Thread(target=self.listen_loop, args=(sock, ), daemon=True)
sock.bind((addr, port))
daemon.start()
self.daemons.append(daemon)
s = socket.socket(family, socket.SOCK_DGRAM)
s.connect((rand_addr, 1))
local_ip_address = s.getsockname()[0]
s.close()
self.logger.debug("Discovered the actual listening address is %r", local_ip_address)
self.addresses.append(Address(
AddressType.UDPv4 if family == socket.AF_INET else AddressType.UDPv6,
local_ip_address,
port
))
action_daemon = Thread(target=self.reactor, daemon=True)
action_daemon.start()
self.daemons.append(action_daemon)
heartbeat_daemon = Thread(target=self.heartbeat, daemon=True)
heartbeat_daemon.start()
self.daemons.append(heartbeat_daemon)
def tick(self) -> Tuple[int, int]:
"""Advance the local network clock, returning the new timestamp.
Note, this returns a Hybrid Logical Clock timestamp, not an integer. To use this like physical time, just grab
the front value and divide by 1000 to get seconds.
"""
new_t = time_func()
if self._local_time[0] < new_t:
self._local_time = (new_t, 0)
else:
self._local_time = (self._local_time[0], self._local_time[1] + 1)
return self._local_time
def refresh(self, channel: int):
"""Search for new peers and clear ones which are largely unresponsive."""
self.logger.debug("Refreshing lower-than-k buckets")
self.routing_table[channel].register_refresh()
for bit_length, bucket_group in enumerate(self.routing_table[channel].table):
channel_info = self.self_info.channels[channel]
dist = bit_length * (self.self_info.channels[channel].subnet.b - 1)
for prefix, bucket in enumerate(bucket_group, start=1):
subnet = channel_info.subnet
xored = (int.from_bytes(channel_info.id, 'big') ^ ((prefix << dist))).to_bytes(subnet.h, 'big')
if len(bucket) < subnet.k and subnet.k.bit_length() <= dist * subnet.b:
self.send_all(FindNodeMessage(target=xored))
self.schedule.enter(self.routing_table[channel].delay, 0, self.refresh, argument=(channel, ))
def listen_loop(self, sock: socket.socket):
"""Listen for incoming messages on a separate thread."""
self.logger.info("Listen loop started for %r", sock)
while True:
try:
data, addr = sock.recvfrom(4096)
message = unpackb(data)
self.message_queue.put((message, addr, sock))
except Exception:
self.errors.append(format_exc())
self.logger.exception("Ran into an error in the listener loop for %r", sock)
def reactor(self):
"""React to incoming messages on a separate thread."""
self.logger.info("Reactor loop started")
while True:
try:
message, addr, sock = self.message_queue.get()
channel = message.channel
# update local time
physical = max((self._local_time[0], message.nonce[0], time_func()))
if physical in (self._local_time[0], message.nonce[0]):
logical = max((self._local_time, message.nonce))[0] + 1
else:
logical = 0
self._local_time = (physical, logical)
# react to the message
if channel not in self.self_info.channels:
self.logger.info("I got a message on closed channel %i", channel)
self._send(sock, addr, AckMessage(status=0xff, channel=channel))
continue
message.react(self, addr, sock)
# check if we need to introduce ourselves
if message.sender not in self.routing_table[channel]:
if isinstance(message, BroadcastMessage):
if message.sender != self.self_info.channels[channel].id:
self._send(sock, addr, FindNodeMessage(target=message.sender, channel=channel))
else:
if self.routing_table[channel].add(message.sender, addr, self.socks.index(sock)):
self._send_hello(sock, addr, channel)
for key in self.storage[channel]:
target = self.self_info.channels[channel].subnet.h_func(key).digest()
nearest = self.routing_table[channel].nearest(target)
if message.sender in (peer.public.name for peer in nearest.values()):
self._send(
sock, addr, StoreKeyMessage(
target=target,
key=key,
value=self.storage[channel][key],
channel=channel
)
)
except Exception:
self.errors.append(format_exc())
self.logger.exception("Ran into an error in the rector loop")
def heartbeat(self):
"""Run through scheduled events in a separate thread."""
self.logger.info("Heartbeat loop started")
while True:
try:
cutoff = self.schedule.timefunc()
self.schedule.run()
for event in self.schedule.queue:
if event.time < cutoff:
self.schedule.cancel(event)
except Exception:
self.errors.append(format_exc())
self.logger.exception("Encountered an error in the heartbeat loop")
sleep(0.01)
def is_active(self, channel: int, blocking: bool = False, timeout: float = float('nan')) -> bool:
"""Return a bool indicating if a channel is active or not.
Optionally, block until it is active or the timeout expires. An active channel is defined as one that is both
registered and has active connections to other nodes.
"""
if channel not in self.routing_table:
return False
if blocking:
timeout += time()
while not self.routing_table[channel].member_info and timeout > time():
sleep(0.01)
return bool(self.routing_table[channel].member_info)
def register_channel(
self,
name: str,
description: str,
subnet: NetworkConfiguration,
proprietary: Optional[Dict[str, Any]] = None
) -> None:
"""Register a multiplex channel on this node."""
if subnet.channel in self.self_info.channels:
self.logger.error("Someone tried to register channel %r, but it's taken!", subnet.channel)
raise ValueError("That channel is already assigned, try again.")
id_ = urandom(subnet.h) # TODO: replace this with something deterministic
self.self_info.channels[subnet.channel] = ChannelInfo(name, description, id_, subnet, proprietary)
self.routing_table[subnet.channel] = RoutingTable(id_, subnet)
self.schedule.enter(self.routing_table[subnet.channel].delay, 0, self.refresh, argument=(subnet.channel, ))
def bootstrap(self, channel_id: int, blocking: bool = False, timeout: float = float('inf')) -> bool:
"""Attempt to bootstrap a connection to your desired channel.
Note that you must register the channel first. It is highly recommended that you keep a connection to the
bootstrap network afterwards, as otherwise it will likely have very few nodes or your addition to the list of
potential peers will expire.
Note
----
Regardless of blocking/timeout, this function may block for up to one second.
"""
start = time()
if bootstrap_info not in self.self_info.channels.values():
self.register_channel(
name="Boostrapper",
description="A global network for Retrion peerfinding",
subnet=bootstrap_info
)
for sock, addr in bootstrap_seeds:
try:
self.connect(sock, addr, bootstrap_info.channel)
except Exception:
self.logger.exception("Could not connect to %r", addr)
if not self.is_active(bootstrap_info.channel, blocking=True, timeout=max(timeout, 1)):
raise RuntimeError("Could not connect to the bootstrap network in a reasonable timeframe. Try again?")
self.refresh(bootstrap_info.channel)
channel = self.self_info.channels[channel_id]
channel_info = (channel.name, channel.subnet.channel, channel.subnet.k, channel.subnet.h_name,
channel.subnet.dht_disabled)
key = packb(channel_info)
peers = self.get(key, channel=bootstrap_info.channel)
def bootstrapper(promise):
if promise.cancelled() or promise.result() is None:
self.logger.info("There don't seem to be any nodes on the network")
result: List[GlobalPeerInfo] = []
else:
result = promise.result()
# below is basically a copy/paste of FindNodeMessage.react()
for info in result:
for channel, channel_info in info.channels.items():
if not channel_info.subnet.supported or channel not in self.self_info.channels:
continue
my_channel_info = self.self_info.channels[channel]
if channel_info.subnet.equivalent(my_channel_info.subnet):
name = channel_info.id
if name != self.self_info.channels[channel].id and name not in self.routing_table[channel]:
for address in info.addresses:
try:
if self.routing_table[channel].add(name, address.args, address.addr_type):
self.connect(
address.addr_type,
address.args,
channel_id
)
self.routing_table[channel].member_info[name].public = info
break
except Exception:
self.errors.append(format_exc())
self.logger.exception("I was unable to send a message to %r", address)
result = (self.self_info, *result)
self.set(key, result, channel=bootstrap_info.channel)
peers.add_done_callback(bootstrapper)
timeout -= time() - start
return self.is_active(channel_id, blocking, timeout)
def connect(self, sock: int, addr: Tuple[Any, ...], channel: int):
"""Send an IDENTIFY message to your peer to kick off the connection process."""
self._send(self.socks[sock], addr, IdentifyMessage(channel=channel))
def close(self, channel: Optional[int] = None, *more: int):
"""Turn off one, multiple, or all of your channels."""
if channel is None:
self.close(*self.self_info.channels)
return
if more != ():
self.close(*more)
del self.self_info.channels[channel]
for key, value in self.storage[channel].items():
self.set(key, value, channel)
self.send_all(GoodbyeMessage(channel=channel))
del self.routing_table[channel]
def _send(
self,
sock: socket.socket,
addr: Tuple[Any, ...],
message: Message,
channel: Optional[int] = None,
peer: Optional[PeerInfo] = None
):
if channel is not None:
message.channel = channel
else:
channel = message.channel
message.sender = self.self_info.channels[channel].id
message = message.with_time(self.tick())
if peer is None:
peer = self.routing_table[channel].by_address(addr)
if peer:
message.compress = peer.local.compression
else:
message.compress = CompressType.PLAIN
# ACKs don't want an ACK
# IDENTIFY doesn't want an ACK, it wants a HELLO
# It's impractical to ACK a BROADCAST, just assume they got it
if not isinstance(message, (AckMessage, IdentifyMessage, BroadcastMessage)):
self.awaiting_ack[message.nonce] = message
def stale():
"""If a message wasn't ACK'd, mark a miss."""
if message.nonce in self.awaiting_ack:
del self.awaiting_ack[message.nonce]
peer = self.routing_table[channel].by_address(addr)
if peer:
peer.local.misses += 1
self.schedule.enter(60, 100, stale)
sock.sendto(packb(message), addr)
def _send_hello(self, sock: socket.socket, addr: Tuple[Any, ...], channel: int):
self._send(sock, addr, HelloMessage(kwargs=self.self_info, channel=channel))
def send_all(self, message: Message, channel: Optional[int] = None) -> int:
"""Send a message to every node in your routing table, returning the sum of how many were successful."""
if channel is not None:
message.channel = channel
else:
channel = message.channel
successful = 0
for name in tuple(self.routing_table[channel].member_info):
successful += self.send(name, message)
return successful
def send(self, name: bytes, message: Message, channel: Optional[int] = None) -> bool:
"""Send a message to a particular node, returning True if successful, False if not.
Raises
------
RuntimeError: If you don't know how to reach a particular node, this function will issue FIND_NODE messages
"""
if channel is not None:
message.channel = channel
else:
channel = message.channel
if name not in self.routing_table[channel]:
if name == self.self_info.channels[channel].id:
return False
alpha = self.self_info.channels[channel].subnet.alpha
for peer in self.routing_table[channel].nearest(name, alpha).values():
self.send(peer.public.channels[channel].id, FindNodeMessage(target=name, channel=channel))
raise RuntimeError("You don't have them in your contacts yet. Try again later.")
peer_info = self.routing_table[channel].member_info[name].local
self._send(self.socks[peer_info.sock], peer_info.addr, message)
return True
def send_to(
self,
message: Message,
target: bytes,
*extra_targets: bytes,
group_name: Optional[str] = None,
channel: Optional[int] = None
):
if channel is not None:
message.channel = channel
else:
channel = message.channel
if group_name:
return self.send_to(message, target, *extra_targets, *self.groups[channel][group_name])
if not extra_targets:
return self.send(target, message)
raise NotImplementedError()
def get(self, key: bytes, channel: int = 0, use_local_storage: bool = True) -> 'Future[Any]':
"""Fetch a value from the distributed hash table.
Raises
------
- PermissionError: If DHT features are disabled on the requested channel
"""
subnet = self.self_info.channels[channel].subnet
if subnet.dht_disabled:
raise PermissionError("DHT features are disabled on this channel.")
target = subnet.h_func(key).digest()
ret = Future() # type: ignore
if use_local_storage and key in self.storage[channel]:
ret.set_result(deepcopy(self.storage[channel][key]))
return ret
nearest = self.routing_table[channel].nearest(target, subnet.alpha)
if not nearest or (use_local_storage and max(nearest) > distance(self.self_info.channels[channel].id, target)):
ret.set_result(None)
return ret
msg = FindKeyMessage(target=target, key=key, channel=channel)
msg.async_res = ret
for peer in nearest.values():
self._send(self.socks[peer.local.sock], peer.local.addr, msg)
return ret
def set(self, key: bytes, value: Any, channel: int = 0):
"""Set a value in the distributed hash table.
Raises
------
- PermissionError: If DHT features are disabled on the requested channel
"""
subnet = self.self_info.channels[channel].subnet
if subnet.dht_disabled:
raise PermissionError("DHT features are disabled on this channel.")
target = subnet.h_func(key).digest()
dist = distance(self.self_info.channels[channel].id, target)
msg = StoreKeyMessage(target=target, key=key, value=value, channel=channel)
self.storage[channel][key] = deepcopy(value)
msg._schedule_val_expire(self, dist, originator=True)
for peer in self.routing_table[channel].nearest(target).values():
self._send(self.socks[peer.local.sock], peer.local.addr, msg)
|
test_local_apigw_service.py | from unittest import TestCase
import threading
import os
import shutil
import json
import time
import requests
import random
from mock import Mock
from samcli.local.apigw.local_apigw_service import Route, LocalApigwService
from tests.functional.function_code import nodejs_lambda, API_GATEWAY_ECHO_EVENT, API_GATEWAY_BAD_PROXY_RESPONSE, API_GATEWAY_ECHO_BASE64_EVENT, API_GATEWAY_CONTENT_TYPE_LOWER
from samcli.commands.local.lib import provider
from samcli.local.lambdafn.runtime import LambdaRuntime
from samcli.commands.local.lib.local_lambda import LocalLambdaRunner
from samcli.local.docker.manager import ContainerManager
from samcli.local.layers.layer_downloader import LayerDownloader
from samcli.local.docker.lambda_image import LambdaImage
class TestService_InvalidResponses(TestCase):
@classmethod
def setUpClass(cls):
cls.code_abs_path = nodejs_lambda(API_GATEWAY_BAD_PROXY_RESPONSE)
# Let's convert this absolute path to relative path. Let the parent be the CWD, and codeuri be the folder
cls.cwd = os.path.dirname(cls.code_abs_path)
cls.code_uri = os.path.relpath(cls.code_abs_path, cls.cwd) # Get relative path with respect to CWD
cls.function_name = "name"
cls.function = provider.Function(name=cls.function_name, runtime="nodejs4.3", memory=256, timeout=5,
handler="index.handler", codeuri=cls.code_uri, environment=None,
rolearn=None, layers=[])
cls.mock_function_provider = Mock()
cls.mock_function_provider.get.return_value = cls.function
list_of_routes = [Route(['POST', 'GET'], cls.function_name, '/something'),
Route(['GET'], cls.function_name, '/'),
Route(['GET', 'PUT'], cls.function_name, '/something/{event}'),
]
cls.service, cls.port, cls.url, cls.scheme = make_service(list_of_routes, cls.mock_function_provider, cls.cwd)
cls.service.create()
t = threading.Thread(name='thread', target=cls.service.run, args=())
t.setDaemon(True)
t.start()
time.sleep(1)
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.code_abs_path)
def test_non_proxy_response(self):
expected = {"message": "Internal server error"}
response = requests.get(self.url)
actual = response.json()
self.assertEquals(actual, expected)
self.assertEquals(response.status_code, 502)
self.assertEquals(response.headers.get('Content-Type'), "application/json")
class TestService_ContentType(TestCase):
@classmethod
def setUpClass(cls):
cls.code_abs_path = nodejs_lambda(API_GATEWAY_CONTENT_TYPE_LOWER)
# Let's convert this absolute path to relative path. Let the parent be the CWD, and codeuri be the folder
cls.cwd = os.path.dirname(cls.code_abs_path)
cls.code_uri = os.path.relpath(cls.code_abs_path, cls.cwd) # Get relative path with respect to CWD
cls.function_name = "name"
cls.function = provider.Function(name=cls.function_name, runtime="nodejs4.3", memory=256, timeout=5,
handler="index.handler", codeuri=cls.code_uri, environment=None,
rolearn=None, layers=[])
cls.base64_response_function = provider.Function(name=cls.function_name, runtime="nodejs4.3", memory=256, timeout=5,
handler="index.handler", codeuri=cls.code_uri, environment=None,
rolearn=None, layers=[])
cls.mock_function_provider = Mock()
cls.mock_function_provider.get.return_value = cls.function
list_of_routes = [
Route(['GET'], cls.function_name, '/'),
]
cls.service, cls.port, cls.url, cls.scheme = make_service(list_of_routes, cls.mock_function_provider, cls.cwd)
cls.service.create()
t = threading.Thread(name='thread', target=cls.service.run, args=())
t.setDaemon(True)
t.start()
time.sleep(1)
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.code_abs_path)
def setUp(self):
# Print full diff when comparing large dictionaries
self.maxDiff = None
def test_calling_service_root(self):
expected = "hello"
response = requests.get(self.url)
actual = response.json()
self.assertEquals(actual, expected)
self.assertEquals(response.status_code, 200)
self.assertEquals(response.headers.get('content-type'), "text/plain")
class TestService_EventSerialization(TestCase):
@classmethod
def setUpClass(cls):
cls.code_abs_path = nodejs_lambda(API_GATEWAY_ECHO_EVENT)
# Let's convert this absolute path to relative path. Let the parent be the CWD, and codeuri be the folder
cls.cwd = os.path.dirname(cls.code_abs_path)
cls.code_uri = os.path.relpath(cls.code_abs_path, cls.cwd) # Get relative path with respect to CWD
cls.function_name = "name"
cls.function = provider.Function(name=cls.function_name, runtime="nodejs4.3", memory=256, timeout=5,
handler="index.handler", codeuri=cls.code_uri, environment=None,
rolearn=None, layers=[])
cls.base64_response_function = provider.Function(name=cls.function_name, runtime="nodejs4.3", memory=256, timeout=5,
handler="index.handler", codeuri=cls.code_uri, environment=None,
rolearn=None, layers=[])
cls.mock_function_provider = Mock()
cls.mock_function_provider.get.return_value = cls.function
list_of_routes = [Route(['POST', 'GET'], cls.function_name, '/something'),
Route(['GET'], cls.function_name, '/'),
Route(['GET', 'PUT'], cls.function_name, '/something/{event}'),
Route(['GET'], cls.function_name, '/proxypath/{proxy+}'),
Route(['GET'], cls.function_name, '/resourceproxypath/{resource+}')
]
cls.service, cls.port, cls.url, cls.scheme = make_service(list_of_routes, cls.mock_function_provider, cls.cwd)
cls.service.create()
t = threading.Thread(name='thread', target=cls.service.run, args=())
t.setDaemon(True)
t.start()
time.sleep(1)
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.code_abs_path)
def setUp(self):
# Print full diff when comparing large dictionaries
self.maxDiff = None
def test_calling_service_root(self):
expected = make_service_response(self.port,
scheme=self.scheme,
method="GET",
resourcePath="/",
resolvedResourcePath="/",
pathParameters=None,
body=None,
queryParams=None,
headers=None)
response = requests.get(self.url)
actual = response.json()
self.assertEquals(actual, expected)
self.assertEquals(response.status_code, 200)
self.assertEquals(response.headers.get('Content-Type'), "application/json")
def test_calling_service_with_nonexistent_endpoint(self):
expected = {"message": "Missing Authentication Token"}
response = requests.get(self.url + "/nothere")
actual = response.json()
self.assertEquals(actual, expected)
self.assertEquals(response.status_code, 403)
self.assertEquals(response.headers.get('Content-Type'), "application/json")
def test_calling_service_with_valid_path_invalid_method(self):
expected = {"message": "Missing Authentication Token"}
response = requests.put(self.url)
actual = response.json()
self.assertEquals(actual, expected)
self.assertEquals(response.status_code, 403)
self.assertEquals(response.headers.get('Content-Type'), "application/json")
def test_calling_service_with_data_on_path(self):
path = "/something"
body = {"json": "data"}
expected = make_service_response(self.port,
scheme=self.scheme,
method="POST",
resourcePath=path,
resolvedResourcePath=path,
pathParameters=None,
body=json.dumps(body),
queryParams=None,
headers={"Content-Length": "16",
"Content-Type": "application/json"})
response = requests.post(self.url + path, json=body)
actual = response.json()
self.assertEquals(actual, expected)
self.assertEquals(response.status_code, 200)
self.assertEquals(response.headers.get('Content-Type'), "application/json")
def test_calling_service_with_form_data_on_path(self):
path = "/something"
body = {"key1": "value1"}
expected = make_service_response(self.port,
scheme=self.scheme,
method="POST",
resourcePath=path,
resolvedResourcePath=path,
pathParameters=None,
body='key1=value1',
queryParams=None,
headers={"Content-Length": "11",
"Content-Type": "application/x-www-form-urlencoded"})
response = requests.post(self.url + path, data=body)
actual = response.json()
self.assertEquals(actual, expected)
self.assertEquals(response.status_code, 200)
self.assertEquals(response.headers.get('Content-Type'), "application/json")
def test_calling_service_with_path_params(self):
path = '/something/event1'
expected = make_service_response(self.port,
scheme=self.scheme,
method="GET",
resourcePath="/something/{event}",
resolvedResourcePath=path,
pathParameters={"event": "event1"},
body=None,
queryParams=None,
headers=None)
response = requests.get(self.url + path)
actual = response.json()
self.assertEquals(actual, expected)
self.assertEquals(response.status_code, 200)
self.assertEquals(response.headers.get('Content-Type'), "application/json")
def test_calling_proxy_path(self):
path = '/proxypath/thisisproxypath/thatshouldbecaught'
expected = make_service_response(self.port,
scheme=self.scheme,
method="GET",
resourcePath="/proxypath/{proxy+}",
resolvedResourcePath=path,
pathParameters={"proxy": "thisisproxypath/thatshouldbecaught"},
body=None,
queryParams=None,
headers=None)
response = requests.get(self.url + path)
actual = response.json()
self.assertEquals(actual, expected)
self.assertEquals(response.status_code, 200)
self.assertEquals(response.headers.get('Content-Type'), "application/json")
def test_calling_proxy_path_that_has_name_resource(self):
path = '/resourceproxypath/resourcepath/thatshouldbecaught'
expected = make_service_response(self.port,
scheme=self.scheme,
method="GET",
resourcePath="/resourceproxypath/{resource+}",
resolvedResourcePath=path,
pathParameters={"resource": "resourcepath/thatshouldbecaught"},
body=None,
queryParams=None,
headers=None)
response = requests.get(self.url + path)
actual = response.json()
self.assertEquals(actual, expected)
self.assertEquals(response.status_code, 200)
self.assertEquals(response.headers.get('Content-Type'), "application/json")
def test_calling_service_with_body_and_query_and_headers(self):
path = "/something/event1"
body = {"json": "data"}
headers = {"X-Test": "TestValue"}
expected = make_service_response(self.port,
scheme=self.scheme,
method="PUT",
resourcePath="/something/{event}",
resolvedResourcePath=path,
pathParameters={"event": "event1"},
body=json.dumps(body),
queryParams={"key": "value"},
headers={"X-Test": "TestValue", "Content-Length": "16",
"Content-Type": "application/json"})
response = requests.put(self.url + path,
json=body,
params={"key": "value"},
headers=headers)
actual = response.json()
self.assertEquals(actual, expected)
self.assertEquals(response.status_code, 200)
self.assertEquals(response.headers.get('Content-Type'), "application/json")
class TestService_ProxyAtBasePath(TestCase):
@classmethod
def setUpClass(cls):
cls.code_abs_path = nodejs_lambda(API_GATEWAY_ECHO_EVENT)
# Let's convert this absolute path to relative path. Let the parent be the CWD, and codeuri be the folder
cls.cwd = os.path.dirname(cls.code_abs_path)
cls.code_uri = os.path.relpath(cls.code_abs_path, cls.cwd) # Get relative path with respect to CWD
cls.function_name = "name"
cls.function = provider.Function(name=cls.function_name, runtime="nodejs4.3", memory=256, timeout=5,
handler="index.handler", codeuri=cls.code_uri, environment=None,
rolearn=None, layers=[])
cls.mock_function_provider = Mock()
cls.mock_function_provider.get.return_value = cls.function
list_of_routes = [
Route(['GET'], cls.function_name, '/{proxy+}')
]
cls.service, cls.port, cls.url, cls.scheme = make_service(list_of_routes, cls.mock_function_provider, cls.cwd)
cls.service.create()
t = threading.Thread(name='thread', target=cls.service.run, args=())
t.setDaemon(True)
t.start()
time.sleep(1)
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.code_abs_path)
def setUp(self):
# Print full diff when comparing large dictionaries
self.maxDiff = None
def test_calling_proxy_path(self):
path = '/proxypath/thisisproxypath/thatshouldbecaught'
expected = make_service_response(self.port,
scheme=self.scheme,
method="GET",
resourcePath="/{proxy+}",
resolvedResourcePath=path,
pathParameters={"proxy": "proxypath/thisisproxypath/thatshouldbecaught"},
body=None,
queryParams=None,
headers=None)
response = requests.get(self.url + path)
actual = response.json()
self.assertEquals(actual, expected)
self.assertEquals(response.status_code, 200)
self.assertEquals(response.headers.get('Content-Type'), "application/json")
class TestService_Binary(TestCase):
@classmethod
def setUpClass(cls):
cls.code_abs_path = nodejs_lambda(API_GATEWAY_ECHO_BASE64_EVENT)
# Let's convert this absolute path to relative path. Let the parent be the CWD, and codeuri be the folder
cls.cwd = os.path.dirname(cls.code_abs_path)
cls.code_uri = os.path.relpath(cls.code_abs_path, cls.cwd) # Get relative path with respect to CWD
cls.function_name = "name"
cls.function = provider.Function(name=cls.function_name, runtime="nodejs4.3", memory=256, timeout=5,
handler="index.echoimagehandler", codeuri=cls.code_uri, environment=None,
rolearn=None, layers=[])
cls.mock_function_provider = Mock()
cls.mock_function_provider.get.return_value = cls.function
list_of_routes = [
Route(['GET'], cls.function_name, '/getimagegifbinarydata', binary_types=['image/gif']),
Route(['GET'], cls.function_name, '/getanygifbinarydata', binary_types=['*/*']),
Route(['POST'], cls.function_name, '/postbinarygif', binary_types=['image/gif'])
]
cls.service, cls.port, cls.url, cls.scheme = make_service(list_of_routes, cls.mock_function_provider, cls.cwd)
cls.service.create()
t = threading.Thread(name='thread', target=cls.service.run, args=())
t.setDaemon(True)
t.start()
time.sleep(1)
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.code_abs_path)
def setUp(self):
# Print full diff when comparing large dictionaries
self.maxDiff = None
def test_echo_with_defined_binary_types(self):
path = '/getimagegifbinarydata'
response = requests.get(self.url + path)
actual = response.content
self.assertEquals(actual, b'GIF89a=\x00D\x00\xf7\xa8\x00\x9a,3\xff\xc0\xc0\xef\xc0\xc0uXg\xfc\xf9\xf7\x993\x00\xff\xec\xec\xff\xa0\xa0\xe5\xcc\xbf\xcf\x9f\x87\x0f\xef\xef\x7f\x7f\x7f\xef\x0f\x0f\xdf\x1f\x1f\xff&&_\x9f\x9f\xffYY\xbf??5\xa5\xc2\xff\xff\xff\xac\x16\x19\xb2&\x00\xf8\x13\x10\xc2& \xdf`PP\x84\x9b\xf8\x03\x00\xb5\x0b\x0c\xdf\x0f\x00>\x9a\xb5\x87BM\x7f`P\xd2\xa5\x8f\xcc\x19\x00\xa5,\x00\xec\xd9\xcf\xe5\x0c\x00\xeb\t\x00\xff\xd9\xd9\xc7\x0c\x0c\x0f\x0f\x0f\xffyy~MZ\xfb\t\x08\xe5M@\xfb__\xff33\xcf\x90x\xf2\xe5\xdf\xc3\x06\x06\xbf\t\x08\xff\xb3\xb3\xd9\xb2\x9f\xff\x06\x06\xac)\x00\xff\xc6\xc6\x0c\t\x08\xf9\xf2\xef\xc9s`\xb8#\x00\x9f/\x00\xff__\xff\x8c\x8c\xc5\x1c\x00\xdf33\xffpp\xcf\x19\x19\xc0\x13\x10\xbf\x90x\xf7YY\xff\xf6\xf6\xe7??\xd7&&\xefLL2& \xdf\xbf\xaf\xbf\xbf\xbf???\xc5M@cn\x81_\x00\x00___\xcb00\xd8\x13\x00YC8\x80\x80\x80\xf3RRsVH\xc490\x10\x10\x10\x917@\xf2\x06\x00\xcf@@\xca\x86pooo\xa3!&\xc1\x1d\x18\xcf//\x1f\x1f\x1f\xdf\x00\x00\xd2\x16\x00\xcb\x90x\xbf\x1f\x00\x19\x13\x10\xf3\xd0\xd0\xe399&\x1d\x18Yy\x8e\x8f\x8f\x8f\xff\xa9\xa9\xcb\x13\x13\xbf00SF@\xb6& >\x1d\x18\xfb\xdd\xdd@@@\x99\x93\x90\xff\xbc\xbc\x7fPP\xaf\xaf\xaf\xc6VHzsp\x93& \xb7pp\xb3\x86ptPP|pp\xafOO\xd0\xd0\xd0\xef\xef\xefL90\xbc\xa9\xa0o0(\xeb\xb0\xb0\xff\xe0\xe0\xff\xd0\xd0\x870(K0(\xc9|h\x9f__lct\xebFF\xcf\xcf\xcf\xe0\xe0\xe0b& \xff },(@0(\xa9\x93\x88\xa6|h\x1f\xdf\xdf\xd5\xac\x97\xe2\xc5\xb7\xc7`POOO\x9cyhppp\xff\x80\x80\xff\x96\x96\xd7``\xcc\x99\x7f,\xb0\xcf\xbf\x00\x00\x00\x00\x00\x00\xff\xff\xff\x00\x00\xffff\xff\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00!\xf9\x04\x01\x00\x00\xa8\x00,\x00\x00\x00\x00=\x00D\x00\x00\x08\xff\x00Q\t\x1cH\xb0\xa0\xc1\x83\x08\x13*\\\xc8\xb0\xa1\xc0\x1b\x07\x0c8\x9cHq\xa1\x89\x14\xa72F\xac\xc8\xb1\xa2\t\x1f\x19Cj\x94\xd8\xb1$B\x03\x07D\xaa\x1ci\xb2%*#3V\xcad\xe9\xb2\xa2\x9d 3s\x9e\xdaX\x93!"\x8c:\x83\xf2\xeci\xf0c\xd0\xa3!\x87\x12E\x89\xb4iR\x92.a:\x9d\xfa\xb4\xe5\x0c\x9cT\xb3\xee\x84:\xf1\x06P\xad`\x95*4\n\xb6l\xd5\x84\x06>\x99]\x1b\xb2\xc5\x9c\x83F\xda\xb0\x9d{\xe4\x84\x00\x83W\xe7\xaeM\xe2f\xd4\xa8\xbb\x03\xbd\xea5kE\x88_\xbf\x80\x0fy\x1a\\\xb6\x08\x92\xc3\x87\x01\x070\xe5\x00\x02\xe3\xa9-\x80\xc4\x80\x1cY\xe0dS\x94-_\x0ezd3\xe7\xce\xa8>\x83\x0e=Zf\x92\x13\xa7Gm\x18 \xe1\xaf\xe7\xd5\xb8+\xb7\xceX8\xf6(\xda\xa2D\xd9N\x8d\xbb\xb8n\xc6\x8e}\x8f\xfa\x12<\xf8\xf0\xcf\x11\x1a\x14\x07}|mf\xdf\x00\x9elP\xd1\\\xb8dSaJ\x95\xffz }zu\xadiLs\xa6\xb0&8\x80\x01\xdd\x9f\x9b\x8a ^<\xf9\xe9\xac\xa9:\x82\x1d{\x83\x84\xe6\xef\xc5\xf7\x1d}\xf5\xd9W\x9eq\xa2\x1d\x95\x84a\xb1\xa9\xb0\x01\x00\xdd\x05\xd8\x9c|\x04\x16X\x8a\x02\x0b0\x80\x9f\x0b=\xe8\x94\\l\x1et \n\x00\x10\x02\x08\xdf\x84\x03ZX \x86\x1a\x16W\x03\x87+]\xe7[\x06\x00\x96\xe8\xde\x89\xce\xa5\xa8\xe2\x8a\x19N\xf7b\x87\x19\xa5\x17\x1b\x05\xa3P\x10\xa1\x8d#\xe2X\x9b\x8e;\xf2\xd8"n/\xd6\xd5\xdf\x13\xa2x\x80$\x89\x11\x9e\xd8\x81\x16\x146\xb9#\x8b\xd3\xf9\xe6\xc1\x7f\xa2\x0cp\xe5\x99\x12\xa8\x80\xdad\x15zi!\x98\xab\xf9Ff\x99gvG$g\xdf1\xa0\x80\x9bM\xc2\t\x19\x00\x19p\xd9\x9d\x99G6\xd7Hl\xdf\x99\xc2\xc8\x9e|~\t\x88)~Q@c\x99\xa3\x0cZg\x06\x00\xf8\x96\xa8)\x0c,\xc0h\xa3\x05^\x02\xe9(\x93Rji\x84\xcb)\'\x1fn\x9d~\nj)\xa3\x0e\xffZis\x84\x06\xd7\x81\xaak\xae\xc6\x01\x07\xa0\xb5\xfa*\xac~\xc9z\xaa\x04\x03l\x80+b\xb7\x81V@\x01$\xac\xd6\xe9\xab\xb1\xd2:kpj\x0ep\xe7\xb1\xab\x9aRA\x01!\x14\xd7\xc0\x03\x8dF\x1b\xdc\x00\xd3\x8ar-\xb6\xc8\x12\x07Z\t\x15\xf0:\xdd\xb7n\x8ak\xaa(\x1ddz\xac\x14\x86\x80\x92+~\xf8\xc1\xbb\xa3\xbc\xe4\xae\xe1\x01\xbaR\xfcAG\'\\\xa4\xab\x1a\xbf\xef\x82k\xa1\xbc\x03\xa3\xeb\xd7\x1d\xa4T\xcc\x87\xc2\xc5qP\x02\xc3\xab\xf9+\x9e\xb8OH\xec\xd7\x1bYTL\x8a\x1f~\xa1\x91\xecj"\xd8\xc01n\xfe\x8e\xdaA\x06\xe7\xa2;\t)Q\xb0AJ\x15\\\xa8\xbc2h!\x14\xe0\xee\xcb\xa05\x10\xc6\xa8"s&\x07\n\x13L\xb0sA\x0b\x9b\xa2\x81\x08"h\xf02\x0f\x15\xe0\x964g2\xa8\xd1D\xd3\xa4\xe8\x01\xf5t\x1c\x14`\xc6\xcb\xcbN\x11\xe7\xd6\x87]@\xca\xd7\x8f\x90\xf2\x01\x08#\x10t\x80$\xc5\x99\xc1-\xc7?\x14\xff@\xc6\xdal\x8f\xe2\x04)b0\xb1\t)}\x84\x12J&\x04\x05\x02\xc5\x18\xb8\xd9P\xc0\x0f\x1c\x93`5h\x81_\xb0H(j\x98\xacD( \xc0`P\xc5\x8f\x83\xa6\xc1\xb6;l1\x9d\x06\x1bk\x9d4\x18:(\x1e\n\x15&sR\xb7A9\xc0Q\xf1 \x18X\x00Z\xdf<\x84\xa0:h$H^\x1cgC\\\xa0\xdc\x10\x9a\xc8\xae8\x11gdQ\x07\x01\x07!\x10\n\x11W| {\xef\xa6\x90\xb0m\x01"T B\x01<\xa8\xed\xba_X|pE\x1e\xa7\xc9\xe0D\x19\xce\xcb\xbe\x04\xf5\x08\x11\x80@\x02\xf1+\xce}\t!\xecP\xc1\x0ed\xb8\xdc\xf9\x86\xa0\x88\x8aQA\x06\x90\xc1\x02\xfc\xf2G\x83\x1c4\xc4~\xf8\xcb\x1f\xf7^v\x98D\x98\x0c\x07\xca\x1b\xc5\x05\xba\x90\xbfP`Bt\x14\x81`\x07\'\xc8/\xbf\xc8@\toC\x01)\x9c\x00\xbb\x0e\xd2\xcd$"\x94\xa0\xef\xf0\xe3\x978\xe0l\x02^ \x05\x07\xf3\x97\x00\x04\xd0\xaf%1t\xde\x0b|X\xb0\x820\x8db\x0f\xa4`\xc2\x04\x16@\x8a\x0e\xce\x8f(\x02\t\xa2\xec\x86X\xc4\xb5\x15"\x898\xc4A\xfc\x1a\x08\xc5\x82HQqT\xc4\xdc("A\n<\x08\x02\x05\x94\x90\x1d\r@\xd8E\x83|1\x14T\xbc\x80\x0e>@\n\x14\x88An\xa0\xbb]\x1b\x13\xf2F\xd9Y\xc2dg\xe8\xe1\x1e\x1d\xd2\xc7P\xa0\x10\x07\x84\xf8\xe1 \x1fx\xbf\xfc\x11\xa1\x12\x90XdG\x82\xb8FI\x02q\t/\xb4\xa4&[\x12\x10\x00;') # NOQA
self.assertEquals(response.status_code, 200)
self.assertEquals(response.headers.get('Content-Type'), "image/gif")
def test_echo_with_any_binary_types(self):
path = '/getanygifbinarydata'
response = requests.get(self.url + path)
actual = response.content
self.assertEquals(actual, b'GIF89a=\x00D\x00\xf7\xa8\x00\x9a,3\xff\xc0\xc0\xef\xc0\xc0uXg\xfc\xf9\xf7\x993\x00\xff\xec\xec\xff\xa0\xa0\xe5\xcc\xbf\xcf\x9f\x87\x0f\xef\xef\x7f\x7f\x7f\xef\x0f\x0f\xdf\x1f\x1f\xff&&_\x9f\x9f\xffYY\xbf??5\xa5\xc2\xff\xff\xff\xac\x16\x19\xb2&\x00\xf8\x13\x10\xc2& \xdf`PP\x84\x9b\xf8\x03\x00\xb5\x0b\x0c\xdf\x0f\x00>\x9a\xb5\x87BM\x7f`P\xd2\xa5\x8f\xcc\x19\x00\xa5,\x00\xec\xd9\xcf\xe5\x0c\x00\xeb\t\x00\xff\xd9\xd9\xc7\x0c\x0c\x0f\x0f\x0f\xffyy~MZ\xfb\t\x08\xe5M@\xfb__\xff33\xcf\x90x\xf2\xe5\xdf\xc3\x06\x06\xbf\t\x08\xff\xb3\xb3\xd9\xb2\x9f\xff\x06\x06\xac)\x00\xff\xc6\xc6\x0c\t\x08\xf9\xf2\xef\xc9s`\xb8#\x00\x9f/\x00\xff__\xff\x8c\x8c\xc5\x1c\x00\xdf33\xffpp\xcf\x19\x19\xc0\x13\x10\xbf\x90x\xf7YY\xff\xf6\xf6\xe7??\xd7&&\xefLL2& \xdf\xbf\xaf\xbf\xbf\xbf???\xc5M@cn\x81_\x00\x00___\xcb00\xd8\x13\x00YC8\x80\x80\x80\xf3RRsVH\xc490\x10\x10\x10\x917@\xf2\x06\x00\xcf@@\xca\x86pooo\xa3!&\xc1\x1d\x18\xcf//\x1f\x1f\x1f\xdf\x00\x00\xd2\x16\x00\xcb\x90x\xbf\x1f\x00\x19\x13\x10\xf3\xd0\xd0\xe399&\x1d\x18Yy\x8e\x8f\x8f\x8f\xff\xa9\xa9\xcb\x13\x13\xbf00SF@\xb6& >\x1d\x18\xfb\xdd\xdd@@@\x99\x93\x90\xff\xbc\xbc\x7fPP\xaf\xaf\xaf\xc6VHzsp\x93& \xb7pp\xb3\x86ptPP|pp\xafOO\xd0\xd0\xd0\xef\xef\xefL90\xbc\xa9\xa0o0(\xeb\xb0\xb0\xff\xe0\xe0\xff\xd0\xd0\x870(K0(\xc9|h\x9f__lct\xebFF\xcf\xcf\xcf\xe0\xe0\xe0b& \xff },(@0(\xa9\x93\x88\xa6|h\x1f\xdf\xdf\xd5\xac\x97\xe2\xc5\xb7\xc7`POOO\x9cyhppp\xff\x80\x80\xff\x96\x96\xd7``\xcc\x99\x7f,\xb0\xcf\xbf\x00\x00\x00\x00\x00\x00\xff\xff\xff\x00\x00\xffff\xff\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00!\xf9\x04\x01\x00\x00\xa8\x00,\x00\x00\x00\x00=\x00D\x00\x00\x08\xff\x00Q\t\x1cH\xb0\xa0\xc1\x83\x08\x13*\\\xc8\xb0\xa1\xc0\x1b\x07\x0c8\x9cHq\xa1\x89\x14\xa72F\xac\xc8\xb1\xa2\t\x1f\x19Cj\x94\xd8\xb1$B\x03\x07D\xaa\x1ci\xb2%*#3V\xcad\xe9\xb2\xa2\x9d 3s\x9e\xdaX\x93!"\x8c:\x83\xf2\xeci\xf0c\xd0\xa3!\x87\x12E\x89\xb4iR\x92.a:\x9d\xfa\xb4\xe5\x0c\x9cT\xb3\xee\x84:\xf1\x06P\xad`\x95*4\n\xb6l\xd5\x84\x06>\x99]\x1b\xb2\xc5\x9c\x83F\xda\xb0\x9d{\xe4\x84\x00\x83W\xe7\xaeM\xe2f\xd4\xa8\xbb\x03\xbd\xea5kE\x88_\xbf\x80\x0fy\x1a\\\xb6\x08\x92\xc3\x87\x01\x070\xe5\x00\x02\xe3\xa9-\x80\xc4\x80\x1cY\xe0dS\x94-_\x0ezd3\xe7\xce\xa8>\x83\x0e=Zf\x92\x13\xa7Gm\x18 \xe1\xaf\xe7\xd5\xb8+\xb7\xceX8\xf6(\xda\xa2D\xd9N\x8d\xbb\xb8n\xc6\x8e}\x8f\xfa\x12<\xf8\xf0\xcf\x11\x1a\x14\x07}|mf\xdf\x00\x9elP\xd1\\\xb8dSaJ\x95\xffz }zu\xadiLs\xa6\xb0&8\x80\x01\xdd\x9f\x9b\x8a ^<\xf9\xe9\xac\xa9:\x82\x1d{\x83\x84\xe6\xef\xc5\xf7\x1d}\xf5\xd9W\x9eq\xa2\x1d\x95\x84a\xb1\xa9\xb0\x01\x00\xdd\x05\xd8\x9c|\x04\x16X\x8a\x02\x0b0\x80\x9f\x0b=\xe8\x94\\l\x1et \n\x00\x10\x02\x08\xdf\x84\x03ZX \x86\x1a\x16W\x03\x87+]\xe7[\x06\x00\x96\xe8\xde\x89\xce\xa5\xa8\xe2\x8a\x19N\xf7b\x87\x19\xa5\x17\x1b\x05\xa3P\x10\xa1\x8d#\xe2X\x9b\x8e;\xf2\xd8"n/\xd6\xd5\xdf\x13\xa2x\x80$\x89\x11\x9e\xd8\x81\x16\x146\xb9#\x8b\xd3\xf9\xe6\xc1\x7f\xa2\x0cp\xe5\x99\x12\xa8\x80\xdad\x15zi!\x98\xab\xf9Ff\x99gvG$g\xdf1\xa0\x80\x9bM\xc2\t\x19\x00\x19p\xd9\x9d\x99G6\xd7Hl\xdf\x99\xc2\xc8\x9e|~\t\x88)~Q@c\x99\xa3\x0cZg\x06\x00\xf8\x96\xa8)\x0c,\xc0h\xa3\x05^\x02\xe9(\x93Rji\x84\xcb)\'\x1fn\x9d~\nj)\xa3\x0e\xffZis\x84\x06\xd7\x81\xaak\xae\xc6\x01\x07\xa0\xb5\xfa*\xac~\xc9z\xaa\x04\x03l\x80+b\xb7\x81V@\x01$\xac\xd6\xe9\xab\xb1\xd2:kpj\x0ep\xe7\xb1\xab\x9aRA\x01!\x14\xd7\xc0\x03\x8dF\x1b\xdc\x00\xd3\x8ar-\xb6\xc8\x12\x07Z\t\x15\xf0:\xdd\xb7n\x8ak\xaa(\x1ddz\xac\x14\x86\x80\x92+~\xf8\xc1\xbb\xa3\xbc\xe4\xae\xe1\x01\xbaR\xfcAG\'\\\xa4\xab\x1a\xbf\xef\x82k\xa1\xbc\x03\xa3\xeb\xd7\x1d\xa4T\xcc\x87\xc2\xc5qP\x02\xc3\xab\xf9+\x9e\xb8OH\xec\xd7\x1bYTL\x8a\x1f~\xa1\x91\xecj"\xd8\xc01n\xfe\x8e\xdaA\x06\xe7\xa2;\t)Q\xb0AJ\x15\\\xa8\xbc2h!\x14\xe0\xee\xcb\xa05\x10\xc6\xa8"s&\x07\n\x13L\xb0sA\x0b\x9b\xa2\x81\x08"h\xf02\x0f\x15\xe0\x964g2\xa8\xd1D\xd3\xa4\xe8\x01\xf5t\x1c\x14`\xc6\xcb\xcbN\x11\xe7\xd6\x87]@\xca\xd7\x8f\x90\xf2\x01\x08#\x10t\x80$\xc5\x99\xc1-\xc7?\x14\xff@\xc6\xdal\x8f\xe2\x04)b0\xb1\t)}\x84\x12J&\x04\x05\x02\xc5\x18\xb8\xd9P\xc0\x0f\x1c\x93`5h\x81_\xb0H(j\x98\xacD( \xc0`P\xc5\x8f\x83\xa6\xc1\xb6;l1\x9d\x06\x1bk\x9d4\x18:(\x1e\n\x15&sR\xb7A9\xc0Q\xf1 \x18X\x00Z\xdf<\x84\xa0:h$H^\x1cgC\\\xa0\xdc\x10\x9a\xc8\xae8\x11gdQ\x07\x01\x07!\x10\n\x11W| {\xef\xa6\x90\xb0m\x01"T B\x01<\xa8\xed\xba_X|pE\x1e\xa7\xc9\xe0D\x19\xce\xcb\xbe\x04\xf5\x08\x11\x80@\x02\xf1+\xce}\t!\xecP\xc1\x0ed\xb8\xdc\xf9\x86\xa0\x88\x8aQA\x06\x90\xc1\x02\xfc\xf2G\x83\x1c4\xc4~\xf8\xcb\x1f\xf7^v\x98D\x98\x0c\x07\xca\x1b\xc5\x05\xba\x90\xbfP`Bt\x14\x81`\x07\'\xc8/\xbf\xc8@\toC\x01)\x9c\x00\xbb\x0e\xd2\xcd$"\x94\xa0\xef\xf0\xe3\x978\xe0l\x02^ \x05\x07\xf3\x97\x00\x04\xd0\xaf%1t\xde\x0b|X\xb0\x820\x8db\x0f\xa4`\xc2\x04\x16@\x8a\x0e\xce\x8f(\x02\t\xa2\xec\x86X\xc4\xb5\x15"\x898\xc4A\xfc\x1a\x08\xc5\x82HQqT\xc4\xdc("A\n<\x08\x02\x05\x94\x90\x1d\r@\xd8E\x83|1\x14T\xbc\x80\x0e>@\n\x14\x88An\xa0\xbb]\x1b\x13\xf2F\xd9Y\xc2dg\xe8\xe1\x1e\x1d\xd2\xc7P\xa0\x10\x07\x84\xf8\xe1 \x1fx\xbf\xfc\x11\xa1\x12\x90XdG\x82\xb8FI\x02q\t/\xb4\xa4&[\x12\x10\x00;') # NOQA
self.assertEquals(response.status_code, 200)
self.assertEquals(response.headers.get('Content-Type'), "image/gif")
def test_accept_json_should_return_base64(self):
# This test is asserting the behavior we currently have. I find it strange that we will return a Content-Type
# that does not match the Accept headers
path = '/getimagegifbinarydata'
response = requests.get(self.url + path, headers={"Accept": "application/json"})
actual = response.content
self.assertEquals(actual.decode('utf-8'), "R0lGODlhPQBEAPeoAJosM//AwO/AwHVYZ/z595kzAP/s7P+goOXMv8+fhw/v739/f+8PD98fH/8mJl+fn/9ZWb8/PzWlwv///6wWGbImAPgTEMImIN9gUFCEm/gDALULDN8PAD6atYdCTX9gUNKlj8wZAKUsAOzZz+UMAOsJAP/Z2ccMDA8PD/95eX5NWvsJCOVNQPtfX/8zM8+QePLl38MGBr8JCP+zs9myn/8GBqwpAP/GxgwJCPny78lzYLgjAJ8vAP9fX/+MjMUcAN8zM/9wcM8ZGcATEL+QePdZWf/29uc/P9cmJu9MTDImIN+/r7+/vz8/P8VNQGNugV8AAF9fX8swMNgTAFlDOICAgPNSUnNWSMQ5MBAQEJE3QPIGAM9AQMqGcG9vb6MhJsEdGM8vLx8fH98AANIWAMuQeL8fABkTEPPQ0OM5OSYdGFl5jo+Pj/+pqcsTE78wMFNGQLYmID4dGPvd3UBAQJmTkP+8vH9QUK+vr8ZWSHpzcJMmILdwcLOGcHRQUHxwcK9PT9DQ0O/v70w5MLypoG8wKOuwsP/g4P/Q0IcwKEswKMl8aJ9fX2xjdOtGRs/Pz+Dg4GImIP8gIH0sKEAwKKmTiKZ8aB/f39Wsl+LFt8dgUE9PT5x5aHBwcP+AgP+WltdgYMyZfyywz78AAAAAAAD///8AAP9mZv///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAKgALAAAAAA9AEQAAAj/AFEJHEiwoMGDCBMqXMiwocAbBww4nEhxoYkUpzJGrMixogkfGUNqlNixJEIDB0SqHGmyJSojM1bKZOmyop0gM3Oe2liTISKMOoPy7GnwY9CjIYcSRYm0aVKSLmE6nfq05QycVLPuhDrxBlCtYJUqNAq2bNWEBj6ZXRuyxZyDRtqwnXvkhACDV+euTeJm1Ki7A73qNWtFiF+/gA95Gly2CJLDhwEHMOUAAuOpLYDEgBxZ4GRTlC1fDnpkM+fOqD6DDj1aZpITp0dtGCDhr+fVuCu3zlg49ijaokTZTo27uG7Gjn2P+hI8+PDPERoUB318bWbfAJ5sUNFcuGRTYUqV/3ogfXp1rWlMc6awJjiAAd2fm4ogXjz56aypOoIde4OE5u/F9x199dlXnnGiHZWEYbGpsAEA3QXYnHwEFliKAgswgJ8LPeiUXGwedCAKABACCN+EA1pYIIYaFlcDhytd51sGAJbo3onOpajiihlO92KHGaUXGwWjUBChjSPiWJuOO/LYIm4v1tXfE6J4gCSJEZ7YgRYUNrkji9P55sF/ogxw5ZkSqIDaZBV6aSGYq/lGZplndkckZ98xoICbTcIJGQAZcNmdmUc210hs35nCyJ58fgmIKX5RQGOZowxaZwYA+JaoKQwswGijBV4C6SiTUmpphMspJx9unX4KaimjDv9aaXOEBteBqmuuxgEHoLX6Kqx+yXqqBANsgCtit4FWQAEkrNbpq7HSOmtwag5w57GrmlJBASEU18ADjUYb3ADTinIttsgSB1oJFfA63bduimuqKB1keqwUhoCSK374wbujvOSu4QG6UvxBRydcpKsav++Ca6G8A6Pr1x2kVMyHwsVxUALDq/krnrhPSOzXG1lUTIoffqGR7Goi2MAxbv6O2kEG56I7CSlRsEFKFVyovDJoIRTg7sugNRDGqCJzJgcKE0ywc0ELm6KBCCJo8DIPFeCWNGcyqNFE06ToAfV0HBRgxsvLThHn1oddQMrXj5DyAQgjEHSAJMWZwS3HPxT/QMbabI/iBCliMLEJKX2EEkomBAUCxRi42VDADxyTYDVogV+wSChqmKxEKCDAYFDFj4OmwbY7bDGdBhtrnTQYOigeChUmc1K3QTnAUfEgGFgAWt88hKA6aCRIXhxnQ1yg3BCayK44EWdkUQcBByEQChFXfCB776aQsG0BIlQgQgE8qO26X1h8cEUep8ngRBnOy74E9QgRgEAC8SvOfQkh7FDBDmS43PmGoIiKUUEGkMEC/PJHgxw0xH74yx/3XnaYRJgMB8obxQW6kL9QYEJ0FIFgByfIL7/IQAlvQwEpnAC7DtLNJCKUoO/w45c44GwCXiAFB/OXAATQryUxdN4LfFiwgjCNYg+kYMIEFkCKDs6PKAIJouyGWMS1FSKJOMRB/BoIxYJIUXFUxNwoIkEKPAgCBZSQHQ1A2EWDfDEUVLyADj5AChSIQW6gu10bE/JG2VnCZGfo4R4d0sdQoBAHhPjhIB94v/wRoRKQWGRHgrhGSQJxCS+0pCZbEhAAOw==") # NOQA
self.assertEquals(response.status_code, 200)
self.assertEquals(response.headers.get('Content-Type'), "image/gif")
class TestService_PostingBinary(TestCase):
@classmethod
def setUpClass(cls):
cls.code_abs_path = nodejs_lambda(API_GATEWAY_ECHO_BASE64_EVENT)
# Let's convert this absolute path to relative path. Let the parent be the CWD, and codeuri be the folder
cls.cwd = os.path.dirname(cls.code_abs_path)
cls.code_uri = os.path.relpath(cls.code_abs_path, cls.cwd) # Get relative path with respect to CWD
cls.function_name = "name"
cls.function = provider.Function(name=cls.function_name, runtime="nodejs4.3", memory=256, timeout=5,
handler="index.base54request", codeuri=cls.code_uri, environment=None,
rolearn=None, layers=[])
cls.mock_function_provider = Mock()
cls.mock_function_provider.get.return_value = cls.function
list_of_routes = [
Route(['POST'], cls.function_name, '/postbinarygif', binary_types=['image/gif']),
Route(['POST'], cls.function_name, '/postanybinary', binary_types=['*/*'])
]
cls.service, cls.port, cls.url, cls.scheme = make_service(list_of_routes, cls.mock_function_provider, cls.cwd)
cls.service.create()
t = threading.Thread(name='thread', target=cls.service.run, args=())
t.setDaemon(True)
t.start()
time.sleep(1)
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.code_abs_path)
def setUp(self):
# Print full diff when comparing large dictionaries
self.maxDiff = None
def test_post_binary_image_gif(self):
path = '/postbinarygif'
response = requests.post(self.url + path,
headers={"Content-Type": "image/gif"},
data='GIF89a=\x00D\x00\xf7\xa8\x00\x9a,3\xff\xc0\xc0\xef\xc0\xc0uXg\xfc\xf9\xf7\x993\x00\xff\xec\xec\xff\xa0\xa0\xe5\xcc\xbf\xcf\x9f\x87\x0f\xef\xef\x7f\x7f\x7f\xef\x0f\x0f\xdf\x1f\x1f\xff&&_\x9f\x9f\xffYY\xbf??5\xa5\xc2\xff\xff\xff\xac\x16\x19\xb2&\x00\xf8\x13\x10\xc2& \xdf`PP\x84\x9b\xf8\x03\x00\xb5\x0b\x0c\xdf\x0f\x00>\x9a\xb5\x87BM\x7f`P\xd2\xa5\x8f\xcc\x19\x00\xa5,\x00\xec\xd9\xcf\xe5\x0c\x00\xeb\t\x00\xff\xd9\xd9\xc7\x0c\x0c\x0f\x0f\x0f\xffyy~MZ\xfb\t\x08\xe5M@\xfb__\xff33\xcf\x90x\xf2\xe5\xdf\xc3\x06\x06\xbf\t\x08\xff\xb3\xb3\xd9\xb2\x9f\xff\x06\x06\xac)\x00\xff\xc6\xc6\x0c\t\x08\xf9\xf2\xef\xc9s`\xb8#\x00\x9f/\x00\xff__\xff\x8c\x8c\xc5\x1c\x00\xdf33\xffpp\xcf\x19\x19\xc0\x13\x10\xbf\x90x\xf7YY\xff\xf6\xf6\xe7??\xd7&&\xefLL2& \xdf\xbf\xaf\xbf\xbf\xbf???\xc5M@cn\x81_\x00\x00___\xcb00\xd8\x13\x00YC8\x80\x80\x80\xf3RRsVH\xc490\x10\x10\x10\x917@\xf2\x06\x00\xcf@@\xca\x86pooo\xa3!&\xc1\x1d\x18\xcf//\x1f\x1f\x1f\xdf\x00\x00\xd2\x16\x00\xcb\x90x\xbf\x1f\x00\x19\x13\x10\xf3\xd0\xd0\xe399&\x1d\x18Yy\x8e\x8f\x8f\x8f\xff\xa9\xa9\xcb\x13\x13\xbf00SF@\xb6& >\x1d\x18\xfb\xdd\xdd@@@\x99\x93\x90\xff\xbc\xbc\x7fPP\xaf\xaf\xaf\xc6VHzsp\x93& \xb7pp\xb3\x86ptPP|pp\xafOO\xd0\xd0\xd0\xef\xef\xefL90\xbc\xa9\xa0o0(\xeb\xb0\xb0\xff\xe0\xe0\xff\xd0\xd0\x870(K0(\xc9|h\x9f__lct\xebFF\xcf\xcf\xcf\xe0\xe0\xe0b& \xff },(@0(\xa9\x93\x88\xa6|h\x1f\xdf\xdf\xd5\xac\x97\xe2\xc5\xb7\xc7`POOO\x9cyhppp\xff\x80\x80\xff\x96\x96\xd7``\xcc\x99\x7f,\xb0\xcf\xbf\x00\x00\x00\x00\x00\x00\xff\xff\xff\x00\x00\xffff\xff\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00!\xf9\x04\x01\x00\x00\xa8\x00,\x00\x00\x00\x00=\x00D\x00\x00\x08\xff\x00Q\t\x1cH\xb0\xa0\xc1\x83\x08\x13*\\\xc8\xb0\xa1\xc0\x1b\x07\x0c8\x9cHq\xa1\x89\x14\xa72F\xac\xc8\xb1\xa2\t\x1f\x19Cj\x94\xd8\xb1$B\x03\x07D\xaa\x1ci\xb2%*#3V\xcad\xe9\xb2\xa2\x9d 3s\x9e\xdaX\x93!"\x8c:\x83\xf2\xeci\xf0c\xd0\xa3!\x87\x12E\x89\xb4iR\x92.a:\x9d\xfa\xb4\xe5\x0c\x9cT\xb3\xee\x84:\xf1\x06P\xad`\x95*4\n\xb6l\xd5\x84\x06>\x99]\x1b\xb2\xc5\x9c\x83F\xda\xb0\x9d{\xe4\x84\x00\x83W\xe7\xaeM\xe2f\xd4\xa8\xbb\x03\xbd\xea5kE\x88_\xbf\x80\x0fy\x1a\\\xb6\x08\x92\xc3\x87\x01\x070\xe5\x00\x02\xe3\xa9-\x80\xc4\x80\x1cY\xe0dS\x94-_\x0ezd3\xe7\xce\xa8>\x83\x0e=Zf\x92\x13\xa7Gm\x18 \xe1\xaf\xe7\xd5\xb8+\xb7\xceX8\xf6(\xda\xa2D\xd9N\x8d\xbb\xb8n\xc6\x8e}\x8f\xfa\x12<\xf8\xf0\xcf\x11\x1a\x14\x07}|mf\xdf\x00\x9elP\xd1\\\xb8dSaJ\x95\xffz }zu\xadiLs\xa6\xb0&8\x80\x01\xdd\x9f\x9b\x8a ^<\xf9\xe9\xac\xa9:\x82\x1d{\x83\x84\xe6\xef\xc5\xf7\x1d}\xf5\xd9W\x9eq\xa2\x1d\x95\x84a\xb1\xa9\xb0\x01\x00\xdd\x05\xd8\x9c|\x04\x16X\x8a\x02\x0b0\x80\x9f\x0b=\xe8\x94\\l\x1et \n\x00\x10\x02\x08\xdf\x84\x03ZX \x86\x1a\x16W\x03\x87+]\xe7[\x06\x00\x96\xe8\xde\x89\xce\xa5\xa8\xe2\x8a\x19N\xf7b\x87\x19\xa5\x17\x1b\x05\xa3P\x10\xa1\x8d#\xe2X\x9b\x8e;\xf2\xd8"n/\xd6\xd5\xdf\x13\xa2x\x80$\x89\x11\x9e\xd8\x81\x16\x146\xb9#\x8b\xd3\xf9\xe6\xc1\x7f\xa2\x0cp\xe5\x99\x12\xa8\x80\xdad\x15zi!\x98\xab\xf9Ff\x99gvG$g\xdf1\xa0\x80\x9bM\xc2\t\x19\x00\x19p\xd9\x9d\x99G6\xd7Hl\xdf\x99\xc2\xc8\x9e|~\t\x88)~Q@c\x99\xa3\x0cZg\x06\x00\xf8\x96\xa8)\x0c,\xc0h\xa3\x05^\x02\xe9(\x93Rji\x84\xcb)\'\x1fn\x9d~\nj)\xa3\x0e\xffZis\x84\x06\xd7\x81\xaak\xae\xc6\x01\x07\xa0\xb5\xfa*\xac~\xc9z\xaa\x04\x03l\x80+b\xb7\x81V@\x01$\xac\xd6\xe9\xab\xb1\xd2:kpj\x0ep\xe7\xb1\xab\x9aRA\x01!\x14\xd7\xc0\x03\x8dF\x1b\xdc\x00\xd3\x8ar-\xb6\xc8\x12\x07Z\t\x15\xf0:\xdd\xb7n\x8ak\xaa(\x1ddz\xac\x14\x86\x80\x92+~\xf8\xc1\xbb\xa3\xbc\xe4\xae\xe1\x01\xbaR\xfcAG\'\\\xa4\xab\x1a\xbf\xef\x82k\xa1\xbc\x03\xa3\xeb\xd7\x1d\xa4T\xcc\x87\xc2\xc5qP\x02\xc3\xab\xf9+\x9e\xb8OH\xec\xd7\x1bYTL\x8a\x1f~\xa1\x91\xecj"\xd8\xc01n\xfe\x8e\xdaA\x06\xe7\xa2;\t)Q\xb0AJ\x15\\\xa8\xbc2h!\x14\xe0\xee\xcb\xa05\x10\xc6\xa8"s&\x07\n\x13L\xb0sA\x0b\x9b\xa2\x81\x08"h\xf02\x0f\x15\xe0\x964g2\xa8\xd1D\xd3\xa4\xe8\x01\xf5t\x1c\x14`\xc6\xcb\xcbN\x11\xe7\xd6\x87]@\xca\xd7\x8f\x90\xf2\x01\x08#\x10t\x80$\xc5\x99\xc1-\xc7?\x14\xff@\xc6\xdal\x8f\xe2\x04)b0\xb1\t)}\x84\x12J&\x04\x05\x02\xc5\x18\xb8\xd9P\xc0\x0f\x1c\x93`5h\x81_\xb0H(j\x98\xacD( \xc0`P\xc5\x8f\x83\xa6\xc1\xb6;l1\x9d\x06\x1bk\x9d4\x18:(\x1e\n\x15&sR\xb7A9\xc0Q\xf1 \x18X\x00Z\xdf<\x84\xa0:h$H^\x1cgC\\\xa0\xdc\x10\x9a\xc8\xae8\x11gdQ\x07\x01\x07!\x10\n\x11W| {\xef\xa6\x90\xb0m\x01"T B\x01<\xa8\xed\xba_X|pE\x1e\xa7\xc9\xe0D\x19\xce\xcb\xbe\x04\xf5\x08\x11\x80@\x02\xf1+\xce}\t!\xecP\xc1\x0ed\xb8\xdc\xf9\x86\xa0\x88\x8aQA\x06\x90\xc1\x02\xfc\xf2G\x83\x1c4\xc4~\xf8\xcb\x1f\xf7^v\x98D\x98\x0c\x07\xca\x1b\xc5\x05\xba\x90\xbfP`Bt\x14\x81`\x07\'\xc8/\xbf\xc8@\toC\x01)\x9c\x00\xbb\x0e\xd2\xcd$"\x94\xa0\xef\xf0\xe3\x978\xe0l\x02^ \x05\x07\xf3\x97\x00\x04\xd0\xaf%1t\xde\x0b|X\xb0\x820\x8db\x0f\xa4`\xc2\x04\x16@\x8a\x0e\xce\x8f(\x02\t\xa2\xec\x86X\xc4\xb5\x15"\x898\xc4A\xfc\x1a\x08\xc5\x82HQqT\xc4\xdc("A\n<\x08\x02\x05\x94\x90\x1d\r@\xd8E\x83|1\x14T\xbc\x80\x0e>@\n\x14\x88An\xa0\xbb]\x1b\x13\xf2F\xd9Y\xc2dg\xe8\xe1\x1e\x1d\xd2\xc7P\xa0\x10\x07\x84\xf8\xe1 \x1fx\xbf\xfc\x11\xa1\x12\x90XdG\x82\xb8FI\x02q\t/\xb4\xa4&[\x12\x10\x00;') # NOQA
actual = response.content
self.assertEquals(actual, b'GIF89a=\x00D\x00\xf7\xa8\x00\x9a,3\xff\xc0\xc0\xef\xc0\xc0uXg\xfc\xf9\xf7\x993\x00\xff\xec\xec\xff\xa0\xa0\xe5\xcc\xbf\xcf\x9f\x87\x0f\xef\xef\x7f\x7f\x7f\xef\x0f\x0f\xdf\x1f\x1f\xff&&_\x9f\x9f\xffYY\xbf??5\xa5\xc2\xff\xff\xff\xac\x16\x19\xb2&\x00\xf8\x13\x10\xc2& \xdf`PP\x84\x9b\xf8\x03\x00\xb5\x0b\x0c\xdf\x0f\x00>\x9a\xb5\x87BM\x7f`P\xd2\xa5\x8f\xcc\x19\x00\xa5,\x00\xec\xd9\xcf\xe5\x0c\x00\xeb\t\x00\xff\xd9\xd9\xc7\x0c\x0c\x0f\x0f\x0f\xffyy~MZ\xfb\t\x08\xe5M@\xfb__\xff33\xcf\x90x\xf2\xe5\xdf\xc3\x06\x06\xbf\t\x08\xff\xb3\xb3\xd9\xb2\x9f\xff\x06\x06\xac)\x00\xff\xc6\xc6\x0c\t\x08\xf9\xf2\xef\xc9s`\xb8#\x00\x9f/\x00\xff__\xff\x8c\x8c\xc5\x1c\x00\xdf33\xffpp\xcf\x19\x19\xc0\x13\x10\xbf\x90x\xf7YY\xff\xf6\xf6\xe7??\xd7&&\xefLL2& \xdf\xbf\xaf\xbf\xbf\xbf???\xc5M@cn\x81_\x00\x00___\xcb00\xd8\x13\x00YC8\x80\x80\x80\xf3RRsVH\xc490\x10\x10\x10\x917@\xf2\x06\x00\xcf@@\xca\x86pooo\xa3!&\xc1\x1d\x18\xcf//\x1f\x1f\x1f\xdf\x00\x00\xd2\x16\x00\xcb\x90x\xbf\x1f\x00\x19\x13\x10\xf3\xd0\xd0\xe399&\x1d\x18Yy\x8e\x8f\x8f\x8f\xff\xa9\xa9\xcb\x13\x13\xbf00SF@\xb6& >\x1d\x18\xfb\xdd\xdd@@@\x99\x93\x90\xff\xbc\xbc\x7fPP\xaf\xaf\xaf\xc6VHzsp\x93& \xb7pp\xb3\x86ptPP|pp\xafOO\xd0\xd0\xd0\xef\xef\xefL90\xbc\xa9\xa0o0(\xeb\xb0\xb0\xff\xe0\xe0\xff\xd0\xd0\x870(K0(\xc9|h\x9f__lct\xebFF\xcf\xcf\xcf\xe0\xe0\xe0b& \xff },(@0(\xa9\x93\x88\xa6|h\x1f\xdf\xdf\xd5\xac\x97\xe2\xc5\xb7\xc7`POOO\x9cyhppp\xff\x80\x80\xff\x96\x96\xd7``\xcc\x99\x7f,\xb0\xcf\xbf\x00\x00\x00\x00\x00\x00\xff\xff\xff\x00\x00\xffff\xff\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00!\xf9\x04\x01\x00\x00\xa8\x00,\x00\x00\x00\x00=\x00D\x00\x00\x08\xff\x00Q\t\x1cH\xb0\xa0\xc1\x83\x08\x13*\\\xc8\xb0\xa1\xc0\x1b\x07\x0c8\x9cHq\xa1\x89\x14\xa72F\xac\xc8\xb1\xa2\t\x1f\x19Cj\x94\xd8\xb1$B\x03\x07D\xaa\x1ci\xb2%*#3V\xcad\xe9\xb2\xa2\x9d 3s\x9e\xdaX\x93!"\x8c:\x83\xf2\xeci\xf0c\xd0\xa3!\x87\x12E\x89\xb4iR\x92.a:\x9d\xfa\xb4\xe5\x0c\x9cT\xb3\xee\x84:\xf1\x06P\xad`\x95*4\n\xb6l\xd5\x84\x06>\x99]\x1b\xb2\xc5\x9c\x83F\xda\xb0\x9d{\xe4\x84\x00\x83W\xe7\xaeM\xe2f\xd4\xa8\xbb\x03\xbd\xea5kE\x88_\xbf\x80\x0fy\x1a\\\xb6\x08\x92\xc3\x87\x01\x070\xe5\x00\x02\xe3\xa9-\x80\xc4\x80\x1cY\xe0dS\x94-_\x0ezd3\xe7\xce\xa8>\x83\x0e=Zf\x92\x13\xa7Gm\x18 \xe1\xaf\xe7\xd5\xb8+\xb7\xceX8\xf6(\xda\xa2D\xd9N\x8d\xbb\xb8n\xc6\x8e}\x8f\xfa\x12<\xf8\xf0\xcf\x11\x1a\x14\x07}|mf\xdf\x00\x9elP\xd1\\\xb8dSaJ\x95\xffz }zu\xadiLs\xa6\xb0&8\x80\x01\xdd\x9f\x9b\x8a ^<\xf9\xe9\xac\xa9:\x82\x1d{\x83\x84\xe6\xef\xc5\xf7\x1d}\xf5\xd9W\x9eq\xa2\x1d\x95\x84a\xb1\xa9\xb0\x01\x00\xdd\x05\xd8\x9c|\x04\x16X\x8a\x02\x0b0\x80\x9f\x0b=\xe8\x94\\l\x1et \n\x00\x10\x02\x08\xdf\x84\x03ZX \x86\x1a\x16W\x03\x87+]\xe7[\x06\x00\x96\xe8\xde\x89\xce\xa5\xa8\xe2\x8a\x19N\xf7b\x87\x19\xa5\x17\x1b\x05\xa3P\x10\xa1\x8d#\xe2X\x9b\x8e;\xf2\xd8"n/\xd6\xd5\xdf\x13\xa2x\x80$\x89\x11\x9e\xd8\x81\x16\x146\xb9#\x8b\xd3\xf9\xe6\xc1\x7f\xa2\x0cp\xe5\x99\x12\xa8\x80\xdad\x15zi!\x98\xab\xf9Ff\x99gvG$g\xdf1\xa0\x80\x9bM\xc2\t\x19\x00\x19p\xd9\x9d\x99G6\xd7Hl\xdf\x99\xc2\xc8\x9e|~\t\x88)~Q@c\x99\xa3\x0cZg\x06\x00\xf8\x96\xa8)\x0c,\xc0h\xa3\x05^\x02\xe9(\x93Rji\x84\xcb)\'\x1fn\x9d~\nj)\xa3\x0e\xffZis\x84\x06\xd7\x81\xaak\xae\xc6\x01\x07\xa0\xb5\xfa*\xac~\xc9z\xaa\x04\x03l\x80+b\xb7\x81V@\x01$\xac\xd6\xe9\xab\xb1\xd2:kpj\x0ep\xe7\xb1\xab\x9aRA\x01!\x14\xd7\xc0\x03\x8dF\x1b\xdc\x00\xd3\x8ar-\xb6\xc8\x12\x07Z\t\x15\xf0:\xdd\xb7n\x8ak\xaa(\x1ddz\xac\x14\x86\x80\x92+~\xf8\xc1\xbb\xa3\xbc\xe4\xae\xe1\x01\xbaR\xfcAG\'\\\xa4\xab\x1a\xbf\xef\x82k\xa1\xbc\x03\xa3\xeb\xd7\x1d\xa4T\xcc\x87\xc2\xc5qP\x02\xc3\xab\xf9+\x9e\xb8OH\xec\xd7\x1bYTL\x8a\x1f~\xa1\x91\xecj"\xd8\xc01n\xfe\x8e\xdaA\x06\xe7\xa2;\t)Q\xb0AJ\x15\\\xa8\xbc2h!\x14\xe0\xee\xcb\xa05\x10\xc6\xa8"s&\x07\n\x13L\xb0sA\x0b\x9b\xa2\x81\x08"h\xf02\x0f\x15\xe0\x964g2\xa8\xd1D\xd3\xa4\xe8\x01\xf5t\x1c\x14`\xc6\xcb\xcbN\x11\xe7\xd6\x87]@\xca\xd7\x8f\x90\xf2\x01\x08#\x10t\x80$\xc5\x99\xc1-\xc7?\x14\xff@\xc6\xdal\x8f\xe2\x04)b0\xb1\t)}\x84\x12J&\x04\x05\x02\xc5\x18\xb8\xd9P\xc0\x0f\x1c\x93`5h\x81_\xb0H(j\x98\xacD( \xc0`P\xc5\x8f\x83\xa6\xc1\xb6;l1\x9d\x06\x1bk\x9d4\x18:(\x1e\n\x15&sR\xb7A9\xc0Q\xf1 \x18X\x00Z\xdf<\x84\xa0:h$H^\x1cgC\\\xa0\xdc\x10\x9a\xc8\xae8\x11gdQ\x07\x01\x07!\x10\n\x11W| {\xef\xa6\x90\xb0m\x01"T B\x01<\xa8\xed\xba_X|pE\x1e\xa7\xc9\xe0D\x19\xce\xcb\xbe\x04\xf5\x08\x11\x80@\x02\xf1+\xce}\t!\xecP\xc1\x0ed\xb8\xdc\xf9\x86\xa0\x88\x8aQA\x06\x90\xc1\x02\xfc\xf2G\x83\x1c4\xc4~\xf8\xcb\x1f\xf7^v\x98D\x98\x0c\x07\xca\x1b\xc5\x05\xba\x90\xbfP`Bt\x14\x81`\x07\'\xc8/\xbf\xc8@\toC\x01)\x9c\x00\xbb\x0e\xd2\xcd$"\x94\xa0\xef\xf0\xe3\x978\xe0l\x02^ \x05\x07\xf3\x97\x00\x04\xd0\xaf%1t\xde\x0b|X\xb0\x820\x8db\x0f\xa4`\xc2\x04\x16@\x8a\x0e\xce\x8f(\x02\t\xa2\xec\x86X\xc4\xb5\x15"\x898\xc4A\xfc\x1a\x08\xc5\x82HQqT\xc4\xdc("A\n<\x08\x02\x05\x94\x90\x1d\r@\xd8E\x83|1\x14T\xbc\x80\x0e>@\n\x14\x88An\xa0\xbb]\x1b\x13\xf2F\xd9Y\xc2dg\xe8\xe1\x1e\x1d\xd2\xc7P\xa0\x10\x07\x84\xf8\xe1 \x1fx\xbf\xfc\x11\xa1\x12\x90XdG\x82\xb8FI\x02q\t/\xb4\xa4&[\x12\x10\x00;') # NOQA
self.assertEquals(response.status_code, 200)
self.assertEquals(response.headers.get('Content-Type'), "image/gif")
def test_post_binary_and_accept_any(self):
path = '/postanybinary'
response = requests.post(self.url + path,
headers={"Content-Type": "image/gif"},
data='GIF89a=\x00D\x00\xf7\xa8\x00\x9a,3\xff\xc0\xc0\xef\xc0\xc0uXg\xfc\xf9\xf7\x993\x00\xff\xec\xec\xff\xa0\xa0\xe5\xcc\xbf\xcf\x9f\x87\x0f\xef\xef\x7f\x7f\x7f\xef\x0f\x0f\xdf\x1f\x1f\xff&&_\x9f\x9f\xffYY\xbf??5\xa5\xc2\xff\xff\xff\xac\x16\x19\xb2&\x00\xf8\x13\x10\xc2& \xdf`PP\x84\x9b\xf8\x03\x00\xb5\x0b\x0c\xdf\x0f\x00>\x9a\xb5\x87BM\x7f`P\xd2\xa5\x8f\xcc\x19\x00\xa5,\x00\xec\xd9\xcf\xe5\x0c\x00\xeb\t\x00\xff\xd9\xd9\xc7\x0c\x0c\x0f\x0f\x0f\xffyy~MZ\xfb\t\x08\xe5M@\xfb__\xff33\xcf\x90x\xf2\xe5\xdf\xc3\x06\x06\xbf\t\x08\xff\xb3\xb3\xd9\xb2\x9f\xff\x06\x06\xac)\x00\xff\xc6\xc6\x0c\t\x08\xf9\xf2\xef\xc9s`\xb8#\x00\x9f/\x00\xff__\xff\x8c\x8c\xc5\x1c\x00\xdf33\xffpp\xcf\x19\x19\xc0\x13\x10\xbf\x90x\xf7YY\xff\xf6\xf6\xe7??\xd7&&\xefLL2& \xdf\xbf\xaf\xbf\xbf\xbf???\xc5M@cn\x81_\x00\x00___\xcb00\xd8\x13\x00YC8\x80\x80\x80\xf3RRsVH\xc490\x10\x10\x10\x917@\xf2\x06\x00\xcf@@\xca\x86pooo\xa3!&\xc1\x1d\x18\xcf//\x1f\x1f\x1f\xdf\x00\x00\xd2\x16\x00\xcb\x90x\xbf\x1f\x00\x19\x13\x10\xf3\xd0\xd0\xe399&\x1d\x18Yy\x8e\x8f\x8f\x8f\xff\xa9\xa9\xcb\x13\x13\xbf00SF@\xb6& >\x1d\x18\xfb\xdd\xdd@@@\x99\x93\x90\xff\xbc\xbc\x7fPP\xaf\xaf\xaf\xc6VHzsp\x93& \xb7pp\xb3\x86ptPP|pp\xafOO\xd0\xd0\xd0\xef\xef\xefL90\xbc\xa9\xa0o0(\xeb\xb0\xb0\xff\xe0\xe0\xff\xd0\xd0\x870(K0(\xc9|h\x9f__lct\xebFF\xcf\xcf\xcf\xe0\xe0\xe0b& \xff },(@0(\xa9\x93\x88\xa6|h\x1f\xdf\xdf\xd5\xac\x97\xe2\xc5\xb7\xc7`POOO\x9cyhppp\xff\x80\x80\xff\x96\x96\xd7``\xcc\x99\x7f,\xb0\xcf\xbf\x00\x00\x00\x00\x00\x00\xff\xff\xff\x00\x00\xffff\xff\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00!\xf9\x04\x01\x00\x00\xa8\x00,\x00\x00\x00\x00=\x00D\x00\x00\x08\xff\x00Q\t\x1cH\xb0\xa0\xc1\x83\x08\x13*\\\xc8\xb0\xa1\xc0\x1b\x07\x0c8\x9cHq\xa1\x89\x14\xa72F\xac\xc8\xb1\xa2\t\x1f\x19Cj\x94\xd8\xb1$B\x03\x07D\xaa\x1ci\xb2%*#3V\xcad\xe9\xb2\xa2\x9d 3s\x9e\xdaX\x93!"\x8c:\x83\xf2\xeci\xf0c\xd0\xa3!\x87\x12E\x89\xb4iR\x92.a:\x9d\xfa\xb4\xe5\x0c\x9cT\xb3\xee\x84:\xf1\x06P\xad`\x95*4\n\xb6l\xd5\x84\x06>\x99]\x1b\xb2\xc5\x9c\x83F\xda\xb0\x9d{\xe4\x84\x00\x83W\xe7\xaeM\xe2f\xd4\xa8\xbb\x03\xbd\xea5kE\x88_\xbf\x80\x0fy\x1a\\\xb6\x08\x92\xc3\x87\x01\x070\xe5\x00\x02\xe3\xa9-\x80\xc4\x80\x1cY\xe0dS\x94-_\x0ezd3\xe7\xce\xa8>\x83\x0e=Zf\x92\x13\xa7Gm\x18 \xe1\xaf\xe7\xd5\xb8+\xb7\xceX8\xf6(\xda\xa2D\xd9N\x8d\xbb\xb8n\xc6\x8e}\x8f\xfa\x12<\xf8\xf0\xcf\x11\x1a\x14\x07}|mf\xdf\x00\x9elP\xd1\\\xb8dSaJ\x95\xffz }zu\xadiLs\xa6\xb0&8\x80\x01\xdd\x9f\x9b\x8a ^<\xf9\xe9\xac\xa9:\x82\x1d{\x83\x84\xe6\xef\xc5\xf7\x1d}\xf5\xd9W\x9eq\xa2\x1d\x95\x84a\xb1\xa9\xb0\x01\x00\xdd\x05\xd8\x9c|\x04\x16X\x8a\x02\x0b0\x80\x9f\x0b=\xe8\x94\\l\x1et \n\x00\x10\x02\x08\xdf\x84\x03ZX \x86\x1a\x16W\x03\x87+]\xe7[\x06\x00\x96\xe8\xde\x89\xce\xa5\xa8\xe2\x8a\x19N\xf7b\x87\x19\xa5\x17\x1b\x05\xa3P\x10\xa1\x8d#\xe2X\x9b\x8e;\xf2\xd8"n/\xd6\xd5\xdf\x13\xa2x\x80$\x89\x11\x9e\xd8\x81\x16\x146\xb9#\x8b\xd3\xf9\xe6\xc1\x7f\xa2\x0cp\xe5\x99\x12\xa8\x80\xdad\x15zi!\x98\xab\xf9Ff\x99gvG$g\xdf1\xa0\x80\x9bM\xc2\t\x19\x00\x19p\xd9\x9d\x99G6\xd7Hl\xdf\x99\xc2\xc8\x9e|~\t\x88)~Q@c\x99\xa3\x0cZg\x06\x00\xf8\x96\xa8)\x0c,\xc0h\xa3\x05^\x02\xe9(\x93Rji\x84\xcb)\'\x1fn\x9d~\nj)\xa3\x0e\xffZis\x84\x06\xd7\x81\xaak\xae\xc6\x01\x07\xa0\xb5\xfa*\xac~\xc9z\xaa\x04\x03l\x80+b\xb7\x81V@\x01$\xac\xd6\xe9\xab\xb1\xd2:kpj\x0ep\xe7\xb1\xab\x9aRA\x01!\x14\xd7\xc0\x03\x8dF\x1b\xdc\x00\xd3\x8ar-\xb6\xc8\x12\x07Z\t\x15\xf0:\xdd\xb7n\x8ak\xaa(\x1ddz\xac\x14\x86\x80\x92+~\xf8\xc1\xbb\xa3\xbc\xe4\xae\xe1\x01\xbaR\xfcAG\'\\\xa4\xab\x1a\xbf\xef\x82k\xa1\xbc\x03\xa3\xeb\xd7\x1d\xa4T\xcc\x87\xc2\xc5qP\x02\xc3\xab\xf9+\x9e\xb8OH\xec\xd7\x1bYTL\x8a\x1f~\xa1\x91\xecj"\xd8\xc01n\xfe\x8e\xdaA\x06\xe7\xa2;\t)Q\xb0AJ\x15\\\xa8\xbc2h!\x14\xe0\xee\xcb\xa05\x10\xc6\xa8"s&\x07\n\x13L\xb0sA\x0b\x9b\xa2\x81\x08"h\xf02\x0f\x15\xe0\x964g2\xa8\xd1D\xd3\xa4\xe8\x01\xf5t\x1c\x14`\xc6\xcb\xcbN\x11\xe7\xd6\x87]@\xca\xd7\x8f\x90\xf2\x01\x08#\x10t\x80$\xc5\x99\xc1-\xc7?\x14\xff@\xc6\xdal\x8f\xe2\x04)b0\xb1\t)}\x84\x12J&\x04\x05\x02\xc5\x18\xb8\xd9P\xc0\x0f\x1c\x93`5h\x81_\xb0H(j\x98\xacD( \xc0`P\xc5\x8f\x83\xa6\xc1\xb6;l1\x9d\x06\x1bk\x9d4\x18:(\x1e\n\x15&sR\xb7A9\xc0Q\xf1 \x18X\x00Z\xdf<\x84\xa0:h$H^\x1cgC\\\xa0\xdc\x10\x9a\xc8\xae8\x11gdQ\x07\x01\x07!\x10\n\x11W| {\xef\xa6\x90\xb0m\x01"T B\x01<\xa8\xed\xba_X|pE\x1e\xa7\xc9\xe0D\x19\xce\xcb\xbe\x04\xf5\x08\x11\x80@\x02\xf1+\xce}\t!\xecP\xc1\x0ed\xb8\xdc\xf9\x86\xa0\x88\x8aQA\x06\x90\xc1\x02\xfc\xf2G\x83\x1c4\xc4~\xf8\xcb\x1f\xf7^v\x98D\x98\x0c\x07\xca\x1b\xc5\x05\xba\x90\xbfP`Bt\x14\x81`\x07\'\xc8/\xbf\xc8@\toC\x01)\x9c\x00\xbb\x0e\xd2\xcd$"\x94\xa0\xef\xf0\xe3\x978\xe0l\x02^ \x05\x07\xf3\x97\x00\x04\xd0\xaf%1t\xde\x0b|X\xb0\x820\x8db\x0f\xa4`\xc2\x04\x16@\x8a\x0e\xce\x8f(\x02\t\xa2\xec\x86X\xc4\xb5\x15"\x898\xc4A\xfc\x1a\x08\xc5\x82HQqT\xc4\xdc("A\n<\x08\x02\x05\x94\x90\x1d\r@\xd8E\x83|1\x14T\xbc\x80\x0e>@\n\x14\x88An\xa0\xbb]\x1b\x13\xf2F\xd9Y\xc2dg\xe8\xe1\x1e\x1d\xd2\xc7P\xa0\x10\x07\x84\xf8\xe1 \x1fx\xbf\xfc\x11\xa1\x12\x90XdG\x82\xb8FI\x02q\t/\xb4\xa4&[\x12\x10\x00;') # NOQA
actual = response.content
self.assertEquals(actual, b'GIF89a=\x00D\x00\xf7\xa8\x00\x9a,3\xff\xc0\xc0\xef\xc0\xc0uXg\xfc\xf9\xf7\x993\x00\xff\xec\xec\xff\xa0\xa0\xe5\xcc\xbf\xcf\x9f\x87\x0f\xef\xef\x7f\x7f\x7f\xef\x0f\x0f\xdf\x1f\x1f\xff&&_\x9f\x9f\xffYY\xbf??5\xa5\xc2\xff\xff\xff\xac\x16\x19\xb2&\x00\xf8\x13\x10\xc2& \xdf`PP\x84\x9b\xf8\x03\x00\xb5\x0b\x0c\xdf\x0f\x00>\x9a\xb5\x87BM\x7f`P\xd2\xa5\x8f\xcc\x19\x00\xa5,\x00\xec\xd9\xcf\xe5\x0c\x00\xeb\t\x00\xff\xd9\xd9\xc7\x0c\x0c\x0f\x0f\x0f\xffyy~MZ\xfb\t\x08\xe5M@\xfb__\xff33\xcf\x90x\xf2\xe5\xdf\xc3\x06\x06\xbf\t\x08\xff\xb3\xb3\xd9\xb2\x9f\xff\x06\x06\xac)\x00\xff\xc6\xc6\x0c\t\x08\xf9\xf2\xef\xc9s`\xb8#\x00\x9f/\x00\xff__\xff\x8c\x8c\xc5\x1c\x00\xdf33\xffpp\xcf\x19\x19\xc0\x13\x10\xbf\x90x\xf7YY\xff\xf6\xf6\xe7??\xd7&&\xefLL2& \xdf\xbf\xaf\xbf\xbf\xbf???\xc5M@cn\x81_\x00\x00___\xcb00\xd8\x13\x00YC8\x80\x80\x80\xf3RRsVH\xc490\x10\x10\x10\x917@\xf2\x06\x00\xcf@@\xca\x86pooo\xa3!&\xc1\x1d\x18\xcf//\x1f\x1f\x1f\xdf\x00\x00\xd2\x16\x00\xcb\x90x\xbf\x1f\x00\x19\x13\x10\xf3\xd0\xd0\xe399&\x1d\x18Yy\x8e\x8f\x8f\x8f\xff\xa9\xa9\xcb\x13\x13\xbf00SF@\xb6& >\x1d\x18\xfb\xdd\xdd@@@\x99\x93\x90\xff\xbc\xbc\x7fPP\xaf\xaf\xaf\xc6VHzsp\x93& \xb7pp\xb3\x86ptPP|pp\xafOO\xd0\xd0\xd0\xef\xef\xefL90\xbc\xa9\xa0o0(\xeb\xb0\xb0\xff\xe0\xe0\xff\xd0\xd0\x870(K0(\xc9|h\x9f__lct\xebFF\xcf\xcf\xcf\xe0\xe0\xe0b& \xff },(@0(\xa9\x93\x88\xa6|h\x1f\xdf\xdf\xd5\xac\x97\xe2\xc5\xb7\xc7`POOO\x9cyhppp\xff\x80\x80\xff\x96\x96\xd7``\xcc\x99\x7f,\xb0\xcf\xbf\x00\x00\x00\x00\x00\x00\xff\xff\xff\x00\x00\xffff\xff\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00!\xf9\x04\x01\x00\x00\xa8\x00,\x00\x00\x00\x00=\x00D\x00\x00\x08\xff\x00Q\t\x1cH\xb0\xa0\xc1\x83\x08\x13*\\\xc8\xb0\xa1\xc0\x1b\x07\x0c8\x9cHq\xa1\x89\x14\xa72F\xac\xc8\xb1\xa2\t\x1f\x19Cj\x94\xd8\xb1$B\x03\x07D\xaa\x1ci\xb2%*#3V\xcad\xe9\xb2\xa2\x9d 3s\x9e\xdaX\x93!"\x8c:\x83\xf2\xeci\xf0c\xd0\xa3!\x87\x12E\x89\xb4iR\x92.a:\x9d\xfa\xb4\xe5\x0c\x9cT\xb3\xee\x84:\xf1\x06P\xad`\x95*4\n\xb6l\xd5\x84\x06>\x99]\x1b\xb2\xc5\x9c\x83F\xda\xb0\x9d{\xe4\x84\x00\x83W\xe7\xaeM\xe2f\xd4\xa8\xbb\x03\xbd\xea5kE\x88_\xbf\x80\x0fy\x1a\\\xb6\x08\x92\xc3\x87\x01\x070\xe5\x00\x02\xe3\xa9-\x80\xc4\x80\x1cY\xe0dS\x94-_\x0ezd3\xe7\xce\xa8>\x83\x0e=Zf\x92\x13\xa7Gm\x18 \xe1\xaf\xe7\xd5\xb8+\xb7\xceX8\xf6(\xda\xa2D\xd9N\x8d\xbb\xb8n\xc6\x8e}\x8f\xfa\x12<\xf8\xf0\xcf\x11\x1a\x14\x07}|mf\xdf\x00\x9elP\xd1\\\xb8dSaJ\x95\xffz }zu\xadiLs\xa6\xb0&8\x80\x01\xdd\x9f\x9b\x8a ^<\xf9\xe9\xac\xa9:\x82\x1d{\x83\x84\xe6\xef\xc5\xf7\x1d}\xf5\xd9W\x9eq\xa2\x1d\x95\x84a\xb1\xa9\xb0\x01\x00\xdd\x05\xd8\x9c|\x04\x16X\x8a\x02\x0b0\x80\x9f\x0b=\xe8\x94\\l\x1et \n\x00\x10\x02\x08\xdf\x84\x03ZX \x86\x1a\x16W\x03\x87+]\xe7[\x06\x00\x96\xe8\xde\x89\xce\xa5\xa8\xe2\x8a\x19N\xf7b\x87\x19\xa5\x17\x1b\x05\xa3P\x10\xa1\x8d#\xe2X\x9b\x8e;\xf2\xd8"n/\xd6\xd5\xdf\x13\xa2x\x80$\x89\x11\x9e\xd8\x81\x16\x146\xb9#\x8b\xd3\xf9\xe6\xc1\x7f\xa2\x0cp\xe5\x99\x12\xa8\x80\xdad\x15zi!\x98\xab\xf9Ff\x99gvG$g\xdf1\xa0\x80\x9bM\xc2\t\x19\x00\x19p\xd9\x9d\x99G6\xd7Hl\xdf\x99\xc2\xc8\x9e|~\t\x88)~Q@c\x99\xa3\x0cZg\x06\x00\xf8\x96\xa8)\x0c,\xc0h\xa3\x05^\x02\xe9(\x93Rji\x84\xcb)\'\x1fn\x9d~\nj)\xa3\x0e\xffZis\x84\x06\xd7\x81\xaak\xae\xc6\x01\x07\xa0\xb5\xfa*\xac~\xc9z\xaa\x04\x03l\x80+b\xb7\x81V@\x01$\xac\xd6\xe9\xab\xb1\xd2:kpj\x0ep\xe7\xb1\xab\x9aRA\x01!\x14\xd7\xc0\x03\x8dF\x1b\xdc\x00\xd3\x8ar-\xb6\xc8\x12\x07Z\t\x15\xf0:\xdd\xb7n\x8ak\xaa(\x1ddz\xac\x14\x86\x80\x92+~\xf8\xc1\xbb\xa3\xbc\xe4\xae\xe1\x01\xbaR\xfcAG\'\\\xa4\xab\x1a\xbf\xef\x82k\xa1\xbc\x03\xa3\xeb\xd7\x1d\xa4T\xcc\x87\xc2\xc5qP\x02\xc3\xab\xf9+\x9e\xb8OH\xec\xd7\x1bYTL\x8a\x1f~\xa1\x91\xecj"\xd8\xc01n\xfe\x8e\xdaA\x06\xe7\xa2;\t)Q\xb0AJ\x15\\\xa8\xbc2h!\x14\xe0\xee\xcb\xa05\x10\xc6\xa8"s&\x07\n\x13L\xb0sA\x0b\x9b\xa2\x81\x08"h\xf02\x0f\x15\xe0\x964g2\xa8\xd1D\xd3\xa4\xe8\x01\xf5t\x1c\x14`\xc6\xcb\xcbN\x11\xe7\xd6\x87]@\xca\xd7\x8f\x90\xf2\x01\x08#\x10t\x80$\xc5\x99\xc1-\xc7?\x14\xff@\xc6\xdal\x8f\xe2\x04)b0\xb1\t)}\x84\x12J&\x04\x05\x02\xc5\x18\xb8\xd9P\xc0\x0f\x1c\x93`5h\x81_\xb0H(j\x98\xacD( \xc0`P\xc5\x8f\x83\xa6\xc1\xb6;l1\x9d\x06\x1bk\x9d4\x18:(\x1e\n\x15&sR\xb7A9\xc0Q\xf1 \x18X\x00Z\xdf<\x84\xa0:h$H^\x1cgC\\\xa0\xdc\x10\x9a\xc8\xae8\x11gdQ\x07\x01\x07!\x10\n\x11W| {\xef\xa6\x90\xb0m\x01"T B\x01<\xa8\xed\xba_X|pE\x1e\xa7\xc9\xe0D\x19\xce\xcb\xbe\x04\xf5\x08\x11\x80@\x02\xf1+\xce}\t!\xecP\xc1\x0ed\xb8\xdc\xf9\x86\xa0\x88\x8aQA\x06\x90\xc1\x02\xfc\xf2G\x83\x1c4\xc4~\xf8\xcb\x1f\xf7^v\x98D\x98\x0c\x07\xca\x1b\xc5\x05\xba\x90\xbfP`Bt\x14\x81`\x07\'\xc8/\xbf\xc8@\toC\x01)\x9c\x00\xbb\x0e\xd2\xcd$"\x94\xa0\xef\xf0\xe3\x978\xe0l\x02^ \x05\x07\xf3\x97\x00\x04\xd0\xaf%1t\xde\x0b|X\xb0\x820\x8db\x0f\xa4`\xc2\x04\x16@\x8a\x0e\xce\x8f(\x02\t\xa2\xec\x86X\xc4\xb5\x15"\x898\xc4A\xfc\x1a\x08\xc5\x82HQqT\xc4\xdc("A\n<\x08\x02\x05\x94\x90\x1d\r@\xd8E\x83|1\x14T\xbc\x80\x0e>@\n\x14\x88An\xa0\xbb]\x1b\x13\xf2F\xd9Y\xc2dg\xe8\xe1\x1e\x1d\xd2\xc7P\xa0\x10\x07\x84\xf8\xe1 \x1fx\xbf\xfc\x11\xa1\x12\x90XdG\x82\xb8FI\x02q\t/\xb4\xa4&[\x12\x10\x00;') # NOQA
self.assertEquals(response.status_code, 200)
self.assertEquals(response.headers.get('Content-Type'), "image/gif")
def test_post_binary_with_incorrect_content_type(self):
expected = {"message": "Internal server error"}
path = '/postbinarygif'
response = requests.post(self.url + path,
headers={"Content-Type": "application/json"},
data='GIF89a=\x00D\x00\xf7\xa8\x00\x9a,3\xff\xc0\xc0\xef\xc0\xc0uXg\xfc\xf9\xf7\x993\x00\xff\xec\xec\xff\xa0\xa0\xe5\xcc\xbf\xcf\x9f\x87\x0f\xef\xef\x7f\x7f\x7f\xef\x0f\x0f\xdf\x1f\x1f\xff&&_\x9f\x9f\xffYY\xbf??5\xa5\xc2\xff\xff\xff\xac\x16\x19\xb2&\x00\xf8\x13\x10\xc2& \xdf`PP\x84\x9b\xf8\x03\x00\xb5\x0b\x0c\xdf\x0f\x00>\x9a\xb5\x87BM\x7f`P\xd2\xa5\x8f\xcc\x19\x00\xa5,\x00\xec\xd9\xcf\xe5\x0c\x00\xeb\t\x00\xff\xd9\xd9\xc7\x0c\x0c\x0f\x0f\x0f\xffyy~MZ\xfb\t\x08\xe5M@\xfb__\xff33\xcf\x90x\xf2\xe5\xdf\xc3\x06\x06\xbf\t\x08\xff\xb3\xb3\xd9\xb2\x9f\xff\x06\x06\xac)\x00\xff\xc6\xc6\x0c\t\x08\xf9\xf2\xef\xc9s`\xb8#\x00\x9f/\x00\xff__\xff\x8c\x8c\xc5\x1c\x00\xdf33\xffpp\xcf\x19\x19\xc0\x13\x10\xbf\x90x\xf7YY\xff\xf6\xf6\xe7??\xd7&&\xefLL2& \xdf\xbf\xaf\xbf\xbf\xbf???\xc5M@cn\x81_\x00\x00___\xcb00\xd8\x13\x00YC8\x80\x80\x80\xf3RRsVH\xc490\x10\x10\x10\x917@\xf2\x06\x00\xcf@@\xca\x86pooo\xa3!&\xc1\x1d\x18\xcf//\x1f\x1f\x1f\xdf\x00\x00\xd2\x16\x00\xcb\x90x\xbf\x1f\x00\x19\x13\x10\xf3\xd0\xd0\xe399&\x1d\x18Yy\x8e\x8f\x8f\x8f\xff\xa9\xa9\xcb\x13\x13\xbf00SF@\xb6& >\x1d\x18\xfb\xdd\xdd@@@\x99\x93\x90\xff\xbc\xbc\x7fPP\xaf\xaf\xaf\xc6VHzsp\x93& \xb7pp\xb3\x86ptPP|pp\xafOO\xd0\xd0\xd0\xef\xef\xefL90\xbc\xa9\xa0o0(\xeb\xb0\xb0\xff\xe0\xe0\xff\xd0\xd0\x870(K0(\xc9|h\x9f__lct\xebFF\xcf\xcf\xcf\xe0\xe0\xe0b& \xff },(@0(\xa9\x93\x88\xa6|h\x1f\xdf\xdf\xd5\xac\x97\xe2\xc5\xb7\xc7`POOO\x9cyhppp\xff\x80\x80\xff\x96\x96\xd7``\xcc\x99\x7f,\xb0\xcf\xbf\x00\x00\x00\x00\x00\x00\xff\xff\xff\x00\x00\xffff\xff\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00!\xf9\x04\x01\x00\x00\xa8\x00,\x00\x00\x00\x00=\x00D\x00\x00\x08\xff\x00Q\t\x1cH\xb0\xa0\xc1\x83\x08\x13*\\\xc8\xb0\xa1\xc0\x1b\x07\x0c8\x9cHq\xa1\x89\x14\xa72F\xac\xc8\xb1\xa2\t\x1f\x19Cj\x94\xd8\xb1$B\x03\x07D\xaa\x1ci\xb2%*#3V\xcad\xe9\xb2\xa2\x9d 3s\x9e\xdaX\x93!"\x8c:\x83\xf2\xeci\xf0c\xd0\xa3!\x87\x12E\x89\xb4iR\x92.a:\x9d\xfa\xb4\xe5\x0c\x9cT\xb3\xee\x84:\xf1\x06P\xad`\x95*4\n\xb6l\xd5\x84\x06>\x99]\x1b\xb2\xc5\x9c\x83F\xda\xb0\x9d{\xe4\x84\x00\x83W\xe7\xaeM\xe2f\xd4\xa8\xbb\x03\xbd\xea5kE\x88_\xbf\x80\x0fy\x1a\\\xb6\x08\x92\xc3\x87\x01\x070\xe5\x00\x02\xe3\xa9-\x80\xc4\x80\x1cY\xe0dS\x94-_\x0ezd3\xe7\xce\xa8>\x83\x0e=Zf\x92\x13\xa7Gm\x18 \xe1\xaf\xe7\xd5\xb8+\xb7\xceX8\xf6(\xda\xa2D\xd9N\x8d\xbb\xb8n\xc6\x8e}\x8f\xfa\x12<\xf8\xf0\xcf\x11\x1a\x14\x07}|mf\xdf\x00\x9elP\xd1\\\xb8dSaJ\x95\xffz }zu\xadiLs\xa6\xb0&8\x80\x01\xdd\x9f\x9b\x8a ^<\xf9\xe9\xac\xa9:\x82\x1d{\x83\x84\xe6\xef\xc5\xf7\x1d}\xf5\xd9W\x9eq\xa2\x1d\x95\x84a\xb1\xa9\xb0\x01\x00\xdd\x05\xd8\x9c|\x04\x16X\x8a\x02\x0b0\x80\x9f\x0b=\xe8\x94\\l\x1et \n\x00\x10\x02\x08\xdf\x84\x03ZX \x86\x1a\x16W\x03\x87+]\xe7[\x06\x00\x96\xe8\xde\x89\xce\xa5\xa8\xe2\x8a\x19N\xf7b\x87\x19\xa5\x17\x1b\x05\xa3P\x10\xa1\x8d#\xe2X\x9b\x8e;\xf2\xd8"n/\xd6\xd5\xdf\x13\xa2x\x80$\x89\x11\x9e\xd8\x81\x16\x146\xb9#\x8b\xd3\xf9\xe6\xc1\x7f\xa2\x0cp\xe5\x99\x12\xa8\x80\xdad\x15zi!\x98\xab\xf9Ff\x99gvG$g\xdf1\xa0\x80\x9bM\xc2\t\x19\x00\x19p\xd9\x9d\x99G6\xd7Hl\xdf\x99\xc2\xc8\x9e|~\t\x88)~Q@c\x99\xa3\x0cZg\x06\x00\xf8\x96\xa8)\x0c,\xc0h\xa3\x05^\x02\xe9(\x93Rji\x84\xcb)\'\x1fn\x9d~\nj)\xa3\x0e\xffZis\x84\x06\xd7\x81\xaak\xae\xc6\x01\x07\xa0\xb5\xfa*\xac~\xc9z\xaa\x04\x03l\x80+b\xb7\x81V@\x01$\xac\xd6\xe9\xab\xb1\xd2:kpj\x0ep\xe7\xb1\xab\x9aRA\x01!\x14\xd7\xc0\x03\x8dF\x1b\xdc\x00\xd3\x8ar-\xb6\xc8\x12\x07Z\t\x15\xf0:\xdd\xb7n\x8ak\xaa(\x1ddz\xac\x14\x86\x80\x92+~\xf8\xc1\xbb\xa3\xbc\xe4\xae\xe1\x01\xbaR\xfcAG\'\\\xa4\xab\x1a\xbf\xef\x82k\xa1\xbc\x03\xa3\xeb\xd7\x1d\xa4T\xcc\x87\xc2\xc5qP\x02\xc3\xab\xf9+\x9e\xb8OH\xec\xd7\x1bYTL\x8a\x1f~\xa1\x91\xecj"\xd8\xc01n\xfe\x8e\xdaA\x06\xe7\xa2;\t)Q\xb0AJ\x15\\\xa8\xbc2h!\x14\xe0\xee\xcb\xa05\x10\xc6\xa8"s&\x07\n\x13L\xb0sA\x0b\x9b\xa2\x81\x08"h\xf02\x0f\x15\xe0\x964g2\xa8\xd1D\xd3\xa4\xe8\x01\xf5t\x1c\x14`\xc6\xcb\xcbN\x11\xe7\xd6\x87]@\xca\xd7\x8f\x90\xf2\x01\x08#\x10t\x80$\xc5\x99\xc1-\xc7?\x14\xff@\xc6\xdal\x8f\xe2\x04)b0\xb1\t)}\x84\x12J&\x04\x05\x02\xc5\x18\xb8\xd9P\xc0\x0f\x1c\x93`5h\x81_\xb0H(j\x98\xacD( \xc0`P\xc5\x8f\x83\xa6\xc1\xb6;l1\x9d\x06\x1bk\x9d4\x18:(\x1e\n\x15&sR\xb7A9\xc0Q\xf1 \x18X\x00Z\xdf<\x84\xa0:h$H^\x1cgC\\\xa0\xdc\x10\x9a\xc8\xae8\x11gdQ\x07\x01\x07!\x10\n\x11W| {\xef\xa6\x90\xb0m\x01"T B\x01<\xa8\xed\xba_X|pE\x1e\xa7\xc9\xe0D\x19\xce\xcb\xbe\x04\xf5\x08\x11\x80@\x02\xf1+\xce}\t!\xecP\xc1\x0ed\xb8\xdc\xf9\x86\xa0\x88\x8aQA\x06\x90\xc1\x02\xfc\xf2G\x83\x1c4\xc4~\xf8\xcb\x1f\xf7^v\x98D\x98\x0c\x07\xca\x1b\xc5\x05\xba\x90\xbfP`Bt\x14\x81`\x07\'\xc8/\xbf\xc8@\toC\x01)\x9c\x00\xbb\x0e\xd2\xcd$"\x94\xa0\xef\xf0\xe3\x978\xe0l\x02^ \x05\x07\xf3\x97\x00\x04\xd0\xaf%1t\xde\x0b|X\xb0\x820\x8db\x0f\xa4`\xc2\x04\x16@\x8a\x0e\xce\x8f(\x02\t\xa2\xec\x86X\xc4\xb5\x15"\x898\xc4A\xfc\x1a\x08\xc5\x82HQqT\xc4\xdc("A\n<\x08\x02\x05\x94\x90\x1d\r@\xd8E\x83|1\x14T\xbc\x80\x0e>@\n\x14\x88An\xa0\xbb]\x1b\x13\xf2F\xd9Y\xc2dg\xe8\xe1\x1e\x1d\xd2\xc7P\xa0\x10\x07\x84\xf8\xe1 \x1fx\xbf\xfc\x11\xa1\x12\x90XdG\x82\xb8FI\x02q\t/\xb4\xa4&[\x12\x10\x00;') # NOQA
actual = response.json()
self.assertEquals(actual, expected)
self.assertEquals(response.status_code, 502)
self.assertEquals(response.headers.get('Content-Type'), "application/json")
class TestService_FlaskDefaultOptionsDisabled(TestCase):
@classmethod
def setUpClass(cls):
cls.code_abs_path = nodejs_lambda(API_GATEWAY_ECHO_EVENT)
# Let's convert this absolute path to relative path. Let the parent be the CWD, and codeuri be the folder
cls.cwd = os.path.dirname(cls.code_abs_path)
cls.code_uri = os.path.relpath(cls.code_abs_path, cls.cwd) # Get relative path with respect to CWD
cls.function_name = "name"
cls.function = provider.Function(name=cls.function_name, runtime="nodejs4.3", memory=256, timeout=5,
handler="index.handler", codeuri=cls.code_uri, environment=None,
rolearn=None, layers=[])
cls.base64_response_function = provider.Function(name=cls.function_name, runtime="nodejs4.3", memory=256, timeout=5,
handler="index.handler", codeuri=cls.code_uri, environment=None,
rolearn=None, layers=[])
cls.mock_function_provider = Mock()
cls.mock_function_provider.get.return_value = cls.function
list_of_routes = [Route(['GET'], cls.function_name, '/something'),
Route(['OPTIONS'], cls.function_name, '/something')
]
cls.service, cls.port, cls.url, cls.scheme = make_service(list_of_routes, cls.mock_function_provider, cls.cwd)
cls.service.create()
t = threading.Thread(name='thread', target=cls.service.run, args=())
t.setDaemon(True)
t.start()
time.sleep(1)
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.code_abs_path)
def setUp(self):
# Print full diff when comparing large dictionaries
self.maxDiff = None
def test_flask_default_options_is_disabled(self):
expected = make_service_response(self.port,
scheme=self.scheme,
method="OPTIONS",
resourcePath="/something",
resolvedResourcePath="/something",
pathParameters=None,
body=None,
queryParams=None,
headers={"Content-Length": "0"})
response = requests.options(self.url + '/something')
actual = response.json()
self.assertEquals(actual, expected)
self.assertEquals(response.status_code, 200)
def make_service(list_of_routes, function_provider, cwd):
port = random_port()
manager = ContainerManager()
layer_downloader = LayerDownloader("./", "./")
lambda_image = LambdaImage(layer_downloader, False, False)
local_runtime = LambdaRuntime(manager, lambda_image)
lambda_runner = LocalLambdaRunner(local_runtime=local_runtime,
function_provider=function_provider,
cwd=cwd)
service = LocalApigwService(list_of_routes, lambda_runner, port=port)
scheme = "http"
url = '{}://127.0.0.1:{}'.format(scheme, port)
return service, port, url, scheme
def make_service_response(port, method, scheme, resourcePath, resolvedResourcePath, pathParameters=None,
body=None, headers=None, queryParams=None, isBase64Encoded=False):
response = {
"httpMethod": "GET",
"body": None,
"resource": "/something/{event}",
"requestContext": {
"resourceId": "123456",
"apiId": "1234567890",
"resourcePath": "/something/{event}",
"httpMethod": "GET",
"requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef",
"accountId": "123456789012",
"stage": "prod",
"identity": {
"apiKey": None,
"userArn": None,
"cognitoAuthenticationType": None,
"caller": None,
"userAgent": "Custom User Agent String",
"user": None,
"cognitoIdentityPoolId": None,
"cognitoAuthenticationProvider": None,
"sourceIp": "127.0.0.1",
"accountId": None
},
"extendedRequestId": None,
"path": "/something/{event}"
},
"queryStringParameters": None,
"headers": {
"Host": "0.0.0.0:33651",
"User-Agent": "python-requests/{}".format(requests.__version__),
"Accept-Encoding": "gzip, deflate",
"Accept": "*/*",
"Connection": "keep-alive"
},
"pathParameters": {"event": "event1"},
"stageVariables": None,
"path": "/something/event1",
"isBase64Encoded": False
}
if body:
response["body"] = body
response["httpMethod"] = method
response['requestContext']["httpMethod"] = method
response["requestContext"]["resourcePath"] = resourcePath
response["requestContext"]["path"] = resourcePath
response["resource"] = resourcePath
response["path"] = resolvedResourcePath
response["pathParameters"] = pathParameters
response["queryStringParameters"] = queryParams
response["isBase64Encoded"] = isBase64Encoded
headers = headers or {}
for header, value in headers.items():
response["headers"][header] = value
response["headers"]["Host"] = "127.0.0.1:{}".format(port)
response["headers"]["X-Forwarded-Port"] = str(port)
response["headers"]["X-Forwarded-Proto"] = scheme
return response
def random_port():
return random.randint(30000, 40000)
|
manager.py | # -*- coding: utf-8 -*-
#
# profiler : a Wi-Fi client capability analyzer tool
# Copyright : (c) 2020-2021 Josh Schmelzle
# License : BSD-3-Clause
# Maintainer : josh@joshschmelzle.com
"""
profiler.manager
~~~~~~~~~~~~~~~~
handle profiler
"""
# standard library imports
import argparse
import inspect
import logging
import multiprocessing as mp
import os
import platform
import sys
from datetime import datetime
from signal import SIGINT, signal
# third party imports
import scapy
from scapy.all import rdpcap
# app imports
from . import helpers
from .__version__ import __version__
def signal_handler(signum, frame):
""" Handle noisy keyboardinterrupt """
if signum == 2:
print(f"profiler PID {os.getpid()} detected SIGINT or Control-C... exiting...")
sys.exit(2)
def are_we_root() -> bool:
""" Do we have root permissions? """
if os.geteuid() == 0:
return True
else:
return False
def start(args: argparse.Namespace):
""" Begin work """
log = logging.getLogger(inspect.stack()[0][3])
if args.pytest:
sys.exit("pytest")
if not are_we_root():
log.error("profiler must be run with root permissions... exiting...")
sys.exit(-1)
helpers.setup_logger(args)
log.debug("%s version %s", __name__.split(".")[0], __version__)
log.debug("python platform version is %s", platform.python_version())
scapy_version = ""
try:
scapy_version = scapy.__version__
log.debug("scapy version is %s", scapy_version)
except AttributeError:
log.exception("could not get version information from scapy.__version__")
log.debug("args: %s", args)
if args.oui_update:
# run manuf oui update and exit
sys.exit(0) if helpers.update_manuf() else sys.exit(-1)
config = helpers.setup_config(args)
if args.clean and args.files:
clients_dir = os.path.join(config["GENERAL"].get("files_path"), "clients")
helpers.files_cleanup(clients_dir, args.yes)
sys.exit(0)
if args.clean:
reports_dir = os.path.join(config["GENERAL"].get("files_path"), "reports")
helpers.files_cleanup(reports_dir, args.yes)
sys.exit(0)
signal(SIGINT, signal_handler)
processes = []
finished_processes = []
queue = mp.Queue()
pcap_analysis = config.get("GENERAL").get("pcap_analysis")
parent_pid = os.getpid()
log.debug("%s pid %s", __name__, parent_pid)
if pcap_analysis:
log.info(
"not starting beacon or sniffer because user requested pcap file analysis"
)
helpers.verify_reporting_directories(config)
try:
frames = rdpcap(pcap_analysis)
except FileNotFoundError:
log.exception("could not find file %s", pcap_analysis)
print("exiting...")
sys.exit(-1)
for frame in frames:
# extract frames that are Dot11
if frame.haslayer(scapy.layers.dot11.Dot11AssoReq):
# put frame into the multiprocessing queue for the profiler to analyze
queue.put(frame)
else:
if helpers.validate(config):
log.debug("config %s", config)
else:
log.error("configuration validation failed... exiting...")
sys.exit(-1)
interface = config.get("GENERAL").get("interface")
channel = int(config.get("GENERAL").get("channel"))
listen_only = config.get("GENERAL").get("listen_only")
from .fakeap import Sniffer, TxBeacons
boot_time = datetime.now().timestamp()
lock = mp.Lock()
sequence_number = mp.Value("i", 0)
if args.no_interface_prep:
log.warning("skipping interface prep...")
else:
log.debug("interface prep...")
if not helpers.prep_interface(interface, "monitor", channel):
log.error("failed to stage the interface... exiting...")
sys.exit(-1)
log.debug("finish interface prep...")
helpers.generate_run_message(config)
if listen_only:
log.info("beacon process not started due to listen only mode")
else:
log.debug("beacon process")
txbeacons = mp.Process(
name="txbeacons",
target=TxBeacons,
args=(config, boot_time, lock, sequence_number),
)
processes.append(txbeacons)
txbeacons.start()
log.debug("sniffer process")
sniffer = mp.Process(
name="sniffer",
target=Sniffer,
args=(config, boot_time, lock, sequence_number, queue, args),
)
processes.append(sniffer)
sniffer.start()
from .profiler import Profiler
log.debug("profiler process")
profiler = mp.Process(name="profiler", target=Profiler, args=(config, queue))
processes.append(profiler)
profiler.start()
shutdown = False
while processes:
for process in processes:
if shutdown:
process.kill()
if process.exitcode is not None:
log.debug(process)
processes.remove(process)
finished_processes.append(process)
if process.exitcode == 15:
shutdown = True
|
brightbar.py | from Adafruit_BBIO.SPI import SPI
#from PIL import Image
from pprint import pprint
from traceback import print_exception
#import numpy
import time
import logging
import threading
import sys
from startup_sequence import startup_sequence
#from gif_animation import GifAnimation
from sparkle_animation import SparkleAnimation
from lines_animation import LinesAnimation
from rain_animation import RainAnimation
from config import *
logging.basicConfig(level=logging.DEBUG, format='[%(levelname)s] (%(threadName)-10s) %(message)s',)
class Brightbar:
#[brightness, blue, green, red]
pixel_buffer = [POWER,0,0,0] * LEDS_PER_PANEL * NUM_PANELS
start_clock = None
animation_time = 20000
def __init__(self):
self.init_spi()
#animation = GifAnimation('gifs/extracted/trippy_39_30x30')
#animation = SparkleAnimation(None, SparkleAnimation.SPEED_SLOW, [POWER,255,255,255], 1000)
#animation = SparkleAnimation(None, 2000, [POWER,255,255,255], 1000)
#animation = LinesAnimation(None, 3000, [POWER,255,255,255], 0)
animation = RainAnimation(None, .1, [POWER, 0.0, 200.0, 0.0])
self.animations = [
SparkleAnimation(None, 2000, [POWER,255,255,255], 1000),
LinesAnimation(None, 3000, [POWER,255,255,255], 0),
RainAnimation(None, .1, [POWER, 0.0, 200.0, 0.0])
]
self.render_thread = None
def init_spi(self):
logging.debug("Initializing spi...")
self.spi = SPI(0,0) #/dev/spidev1.0
# SPI Mode Clock Polarity (CPOL/CKP) Clock Phase (CPHA) Clock Edge (CKE/NCPHA)
# 0 0 0 1
# 1 0 1 0
# 2 1 0 1
# 3 1 1 0
self.spi.mode=0
self.spi.msh=SPI_CLOCK_RATE #this is clock speed setting
self.spi.open(0,0)
def debug_frame(self, data):
for y in range(PANEL_Y):
line = str(y) + ": "
for x in range(PANEL_X):
offset = (y * PANEL_X + x) * 4
line += "|" + str(data[offset]) + "," + str(data[offset + 1]) + "," + str(data[offset+2]) + "," + str(data[offset + 3])
print line
#render a full frame
def render(self):
#logging.debug("buffer size: " + str(len(self.pixel_buffer)) + " start render: " + str(time.time()))
start_time = time.time()
#logging.debug(" start render: " + str(start_time))
#make a copy of the buffer to work on in case we need to switch the order of bytes
#data = self.pixel_buffer[:]
offset = 0
#the panels run in a snake S shape, so every other line needs to have bytes reversed
if REVERSE_ALTERNATE_LINES:
for i in range(0,PANEL_Y):
if (i % 2) == 0:
continue
offset = i * PANEL_X * 4
line_length = PANEL_X * 4
line = data[offset:offset + line_length]
reversed_line = [0] * line_length
j = line_length - 4 #start one color from the end, and go backwards through the line
while j >= 0:
reversed_line[line_length - j - 4] = line[j]
reversed_line[line_length - j - 3] = line[j + 1]
reversed_line[line_length - j - 2] = line[j + 2]
reversed_line[line_length - j - 1] = line[j + 3]
j = j - 4
data[offset:offset + PANEL_X * 4] = reversed_line
#self.write_apa102(data)
#logging.debug("length of buffer: " + str(len(self.pixel_buffer)))
#logging.debug(self.pixel_buffer)
self.write_apa102(self.pixel_buffer)
end_time = time.time();
#logging.debug("end render: " + str(end_time) + " elapsed: " + str(end_time - start_time))
#import pdb
#pdb.set_trace()
def write_apa102(self, data):
#start frame, 32 bits of zero
self.spi.writebytes([0] * 4)
#write RGB data
#chunk the data out in 1024 byte blocks
for i in range(0,len(data),1024):
length = len(data)
if((i + 1024) > length):
#end = length - (i+1024 - length)
chunk = data[i:]
else:
#end = i + 1024
chunk = data[i:i+1024]
self.spi.writebytes(chunk)
#write footer. This is total numnber of LEDS / 2 bits of 1's
num_dwords = LEDS_PER_PANEL * NUM_PANELS / 32
for i in range(num_dwords):
self.spi.writebytes([0xff, 0x00, 0x00, 0x00]) #the datasheet calls for 1's here, but internet says 0s work better? the fast LED lib does both?
def clear(self):
self.pixel_buffer = [POWER,0,0,0] * LEDS_PER_PANEL * NUM_PANELS
def calculate_fps(self):
now = time.time()
delta = now - self.start_clock
frame_time = delta/self.frame_count
self.fps = 1/frame_time
logging.debug("elapsed seconds: " + str(delta) + " frame count: " + str(self.frame_count) + " current fps: " + str(self.fps))
def animate(self):
if self.start_clock == None:
self.frame_count = 0
self.start_clock = time.time()
elapsed_time = time.time() - self.start_clock
num_animations = int(round(elapsed_time / (self.animation_time / 1000)))
current_animation = int(num_animations) % len(self.animations)
#logging.debug("elapsed time: " + str(elapsed_time) + " num animations:" + str(num_animations) + " current animation:" + str(current_animation))
animation = self.animations[current_animation]
frame = animation.get_next_frame()
if frame == None:
time.sleep(.001)
return
self.frame_count = self.frame_count + 1
if self.frame_count % 100 == 0:
self.calculate_fps()
line_length = animation.width * 4
for y in range(animation.height):
frame_offset = y * line_length
line = frame[frame_offset:frame_offset + line_length]
buffer_offset = ( ( (int(animation.destination_y_offset) + y) * PANEL_X ) + int(animation.destination_x_offset) ) * 4
self.pixel_buffer[buffer_offset:buffer_offset + line_length] = line
def render_loop(self):
try:
while 1:
brightbar.animate()
brightbar.render()
except:
print_exception(*sys.exc_info())
def start(self):
if STARTUP_SEQUENCE:
startup_sequence(self);
if self.render_thread == None:
self.render_thread = threading.Thread(name="RenderThread", target=self.render_loop)
self.render_thread.start()
def stop(self):
self.render_thread.stop()
logging.debug("Starting program...")
brightbar = Brightbar()
logging.debug("rendering...")
brightbar.start()
|
programs_with_labels.py | # ----------------------------------------------------------------------------------------
# 001.0003-print-hello-world.py
# ----------------------------------------------------------------------------------------
from __future__ import print_function # flat_style (-> +1), imperative_style (-> +1), import:__future__:print_function, import_module:__future__, import_name:print_function, node:ImportFrom, one_liner_style (-> +1), variety:2 (-> +1), whole_span:2 (-> +1)
print("Hello World") # argument:, external_free_call:print, free_call:print, free_call_without_result:print, literal:Str, node:Call, node:Expr, node:Name, node:Str
# ----------------------------------------------------------------------------------------
# 001.1159-print-hello-world.py
# ----------------------------------------------------------------------------------------
print("Hello World") # argument:, external_free_call:print, flat_style, free_call:print, free_call_without_result:print, imperative_style, literal:Str, node:Call, node:Expr, node:Name, node:Str, one_liner_style, variety:1, whole_span:1
# ----------------------------------------------------------------------------------------
# 002.0011-print-hello-10-times.py
# ----------------------------------------------------------------------------------------
for i in range(10): # argument:10, external_free_call:range, for:i (-> +1), for_range:10 (-> +1), free_call:range, global_scope:i (-> +1), imperative_style (-> +1), iteration_variable:i, literal:10, loop:for (-> +1), loop_with_late_exit:for (-> +1), magic_number:10, node:Call, node:For (-> +1), node:Name, node:Num, range:10, scope:i (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
print("Hello") # argument:, external_free_call:print, free_call:print, free_call_without_result:print, literal:Str, node:Call, node:Expr, node:Name, node:Str
# ----------------------------------------------------------------------------------------
# 002.1493-print-hello-10-times.py
# ----------------------------------------------------------------------------------------
print("Hello\n" * 10) # argument:, binary_operator:Mult, external_free_call:print, flat_style, free_call:print, free_call_without_result:print, imperative_style, literal:10, literal:Str, magic_number:10, node:BinOp, node:Call, node:Expr, node:Name, node:Num, node:Str, one_liner_style, replication_operator:Str, special_literal_string:Hello\n, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 002.3117-print-hello-10-times.py
# ----------------------------------------------------------------------------------------
print("Hello\n" * 10) # argument:, binary_operator:Mult, external_free_call:print, flat_style, free_call:print, free_call_without_result:print, imperative_style, literal:10, literal:Str, magic_number:10, node:BinOp, node:Call, node:Expr, node:Name, node:Num, node:Str, one_liner_style, replication_operator:Str, special_literal_string:Hello\n, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 003.0019-create-a-procedure.py
# ----------------------------------------------------------------------------------------
def finish(name): # function:finish (-> +1), function_line_count:2 (-> +1), function_parameter:name, function_parameter_flavor:arg, function_returning_nothing:finish (-> +1), local_scope:name (-> +1), node:FunctionDef (-> +1), node:arg, one_liner_style (-> +1), procedural_style (-> +1), scope:name (-> +1), variety:2 (-> +1), whole_span:2 (-> +1)
print("My job here is done. Goodbye " + name) # argument:, binary_operator:Add, concatenation_operator:Str, external_free_call:print, free_call:print, free_call_without_result:print, literal:Str, loaded_variable:name, node:BinOp, node:Call, node:Expr, node:Name, node:Str
# ----------------------------------------------------------------------------------------
# 003.2372-create-a-procedure.py
# ----------------------------------------------------------------------------------------
def a(): # function:a (-> +1), function_line_count:2 (-> +1), function_returning_nothing:a (-> +1), function_without_parameters:a (-> +1), node:FunctionDef (-> +1), one_liner_style (-> +1), procedural_style (-> +1), variety:2 (-> +1), whole_span:2 (-> +1)
pass # no_operation, node:Pass
# ----------------------------------------------------------------------------------------
# 004.0024-create-a-function-which-returns-the-square-of-an-integer.py
# ----------------------------------------------------------------------------------------
def square(x): # function:square (-> +1), function_line_count:2 (-> +1), function_parameter:x, function_parameter_flavor:arg, function_returning_something:square (-> +1), functional_style (-> +1), local_scope:x (-> +1), node:FunctionDef (-> +1), node:arg, one_liner_style (-> +1), pure_function:square (-> +1), scope:x (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
return x * x # binary_operator:Mult, loaded_variable:x, multiplication_operator, node:BinOp, node:Name, node:Return, return
# ----------------------------------------------------------------------------------------
# 004.2921-create-a-function-which-returns-the-square-of-an-integer.py
# ----------------------------------------------------------------------------------------
def square(x): # function:square (-> +1), function_line_count:2 (-> +1), function_parameter:x, function_parameter_flavor:arg, function_returning_something:square (-> +1), functional_style (-> +1), local_scope:x (-> +1), node:FunctionDef (-> +1), node:arg, one_liner_style (-> +1), pure_function:square (-> +1), scope:x (-> +1), variety:2 (-> +1), whole_span:2 (-> +1)
return x ** 2 # binary_operator:Pow, literal:2, loaded_variable:x, node:BinOp, node:Name, node:Num, node:Return, return
# ----------------------------------------------------------------------------------------
# 005.0663-create-a-2d-point-data-structure.py
# ----------------------------------------------------------------------------------------
from dataclasses import dataclass # import:dataclasses:dataclass, import_module:dataclasses, import_name:dataclass, node:ImportFrom, object_oriented_style (-> +4), variety:3 (-> +4), whole_span:5 (-> +4)
@dataclass # loaded_variable:dataclass, node:Name
class Point: # class:Point (-> +2), node:ClassDef (-> +2)
x: float # loaded_variable:float, node:AnnAssign, node:Name
y: float # loaded_variable:float, node:AnnAssign, node:Name
# ----------------------------------------------------------------------------------------
# 006.0032-iterate-over-list-values.py
# ----------------------------------------------------------------------------------------
for x in items: # for:x (-> +1), for_each:x (-> +1), global_scope:x (-> +1), imperative_style (-> +1), iteration_variable:x, loaded_variable:items, loop:for (-> +1), loop_with_late_exit:for (-> +1), node:For (-> +1), node:Name, scope:x (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
doSomething(x) # argument:x, external_free_call:doSomething, free_call:doSomething, free_call_without_result:doSomething, loaded_variable:x, node:Call, node:Expr, node:Name
# ----------------------------------------------------------------------------------------
# 007.0183-iterate-over-list-indexes-and-values.py
# ----------------------------------------------------------------------------------------
for i, x in enumerate(items): # argument:items, external_free_call:enumerate, for:i (-> +1), for:x (-> +1), for_indexes_elements:i (-> +1), free_call:enumerate, global_scope:i (-> +1), global_scope:x (-> +1), imperative_style (-> +1), iteration_variable:i, iteration_variable:x, literal:Tuple, loaded_variable:items, loop:for (-> +1), loop_with_late_exit:for (-> +1), node:Call, node:For (-> +1), node:Name, node:Tuple, scope:i (-> +1), scope:x (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
print(i, x) # argument:i, argument:x, external_free_call:print, free_call:print, free_call_without_result:print, loaded_variable:i, loaded_variable:x, node:Call, node:Expr, node:Name
# ----------------------------------------------------------------------------------------
# 008.0039-initialize-a-new-map-associative-array.py
# ----------------------------------------------------------------------------------------
x = {"one": 1, "two": 2} # assignment, assignment_lhs_identifier:x, assignment_rhs_atom:1, assignment_rhs_atom:2, flat_style, global_scope:x, imperative_style, literal:1, literal:2, literal:Dict, literal:Str, node:Assign, node:Dict, node:Name, node:Num, node:Str, one_liner_style, scope:x, single_assignment:x, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 009.1410-create-a-binary-tree-data-structure.py
# ----------------------------------------------------------------------------------------
class Node: # class:Node (-> +4), class_method_count:1 (-> +4), node:ClassDef (-> +4), object_oriented_style (-> +4), variety:2 (-> +4), whole_span:5 (-> +4)
def __init__(self, data): # function:__init__ (-> +3), function_line_count:4 (-> +3), function_parameter:data, function_parameter:self, function_parameter_flavor:arg, function_returning_nothing:__init__ (-> +3), instance_method:__init__ (-> +3), local_scope:data (-> +3), local_scope:self (-> +3), method:__init__ (-> +3), node:FunctionDef (-> +3), node:arg, scope:data (-> +3), scope:self (-> +3)
self.data = data # assignment, assignment_lhs_identifier:self, assignment_rhs_atom:data, loaded_variable:data, loaded_variable:self, node:Assign, node:Attribute, node:Name
self.left = None # assignment:None, assignment_lhs_identifier:self, assignment_rhs_atom:None, literal:None, loaded_variable:self, node:Assign, node:Attribute, node:Name, node:NameConstant
self.right = None # assignment:None, assignment_lhs_identifier:self, assignment_rhs_atom:None, literal:None, loaded_variable:self, node:Assign, node:Attribute, node:Name, node:NameConstant
# ----------------------------------------------------------------------------------------
# 009.3176-create-a-binary-tree-data-structure.py
# ----------------------------------------------------------------------------------------
class Node: # class:Node (-> +4), class_method_count:1 (-> +4), node:ClassDef (-> +4), object_oriented_style (-> +4), variety:2 (-> +4), whole_span:5 (-> +4)
def __init__(self, data, left_child, right_child): # function:__init__ (-> +3), function_line_count:4 (-> +3), function_parameter:data, function_parameter:left_child, function_parameter:right_child, function_parameter:self, function_parameter_flavor:arg, function_returning_nothing:__init__ (-> +3), instance_method:__init__ (-> +3), local_scope:data (-> +3), local_scope:left_child (-> +3), local_scope:right_child (-> +3), local_scope:self (-> +3), method:__init__ (-> +3), node:FunctionDef (-> +3), node:arg, scope:data (-> +3), scope:left_child (-> +3), scope:right_child (-> +3), scope:self (-> +3)
self.data = data # assignment, assignment_lhs_identifier:self, assignment_rhs_atom:data, loaded_variable:data, loaded_variable:self, node:Assign, node:Attribute, node:Name
self._left_child = left_child # assignment, assignment_lhs_identifier:self, assignment_rhs_atom:left_child, loaded_variable:left_child, loaded_variable:self, node:Assign, node:Attribute, node:Name
self._right_child = right_child # assignment, assignment_lhs_identifier:self, assignment_rhs_atom:right_child, loaded_variable:right_child, loaded_variable:self, node:Assign, node:Attribute, node:Name
# ----------------------------------------------------------------------------------------
# 010.0182-shuffle-a-list.py
# ----------------------------------------------------------------------------------------
from random import shuffle # flat_style (-> +1), imperative_style (-> +1), import:random:shuffle, import_module:random, import_name:shuffle, node:ImportFrom, one_liner_style (-> +1), variety:2 (-> +1), whole_span:2 (-> +1)
shuffle(x) # argument:x, external_free_call:shuffle, free_call:shuffle, free_call_without_result:shuffle, loaded_variable:x, node:Call, node:Expr, node:Name
# ----------------------------------------------------------------------------------------
# 010.1478-shuffle-a-list.py
# ----------------------------------------------------------------------------------------
import random # flat_style (-> +1), imperative_style (-> +1), import:random, import_module:random, node:Import, one_liner_style (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
random.shuffle(list) # argument:list, loaded_variable:list, loaded_variable:random, member_call:random:shuffle, member_call_method:shuffle, member_call_object:random, node:Attribute, node:Call, node:Expr, node:Name
# ----------------------------------------------------------------------------------------
# 011.0047-pick-a-random-element-from-a-list.py
# ----------------------------------------------------------------------------------------
import random # flat_style (-> +1), imperative_style (-> +1), import:random, import_module:random, node:Import, one_liner_style (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
random.choice(x) # argument:x, loaded_variable:random, loaded_variable:x, member_call:random:choice, member_call_method:choice, member_call_object:random, node:Attribute, node:Call, node:Expr, node:Name
# ----------------------------------------------------------------------------------------
# 012.0181-check-if-list-contains-a-value.py
# ----------------------------------------------------------------------------------------
x in list # comparison_operator:In, flat_style, imperative_style, loaded_variable:list, loaded_variable:x, node:Compare, node:Expr, node:Name, one_liner_style, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 013.0574-iterate-over-map-keys-and-values.py
# ----------------------------------------------------------------------------------------
for k, v in mymap.items(): # for:k (-> +1), for:v (-> +1), global_scope:k (-> +1), global_scope:v (-> +1), imperative_style (-> +1), iteration_variable:k, iteration_variable:v, literal:Tuple, loaded_variable:mymap, loop:for (-> +1), loop_with_late_exit:for (-> +1), member_call_method:items, node:Attribute, node:Call, node:For (-> +1), node:Name, node:Tuple, scope:k (-> +1), scope:v (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
print(k, v) # argument:k, argument:v, external_free_call:print, free_call:print, free_call_without_result:print, loaded_variable:k, loaded_variable:v, node:Call, node:Expr, node:Name
# ----------------------------------------------------------------------------------------
# 014.0185-pick-uniformly-a-random-floating-point-number-in-ab.py
# ----------------------------------------------------------------------------------------
import random # functional_style (-> +2), import:random, import_module:random, node:Import, one_liner_style (-> +2), variety:2 (-> +2), whole_span:3 (-> +2)
def pick(a, b): # function:pick (-> +1), function_line_count:2 (-> +1), function_parameter:a, function_parameter:b, function_parameter_flavor:arg, function_returning_something:pick (-> +1), local_scope:a (-> +1), local_scope:b (-> +1), node:FunctionDef (-> +1), node:arg, pure_function:pick (-> +1), scope:a (-> +1), scope:b (-> +1)
return random.randrange(a, b) # argument:a, argument:b, loaded_variable:a, loaded_variable:b, loaded_variable:random, member_call:random:randrange, member_call_method:randrange, member_call_object:random, node:Attribute, node:Call, node:Name, node:Return, return
# ----------------------------------------------------------------------------------------
# 014.3410-pick-uniformly-a-random-floating-point-number-in-ab.py
# ----------------------------------------------------------------------------------------
import random # flat_style (-> +1), imperative_style (-> +1), import:random, import_module:random, node:Import, one_liner_style (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
random.uniform(a, b) # argument:a, argument:b, loaded_variable:a, loaded_variable:b, loaded_variable:random, member_call:random:uniform, member_call_method:uniform, member_call_object:random, node:Attribute, node:Call, node:Expr, node:Name
# ----------------------------------------------------------------------------------------
# 015.0184-pick-uniformly-a-random-integer-in-ab.py
# ----------------------------------------------------------------------------------------
import random # flat_style (-> +1), imperative_style (-> +1), import:random, import_module:random, node:Import, one_liner_style (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
random.randint(a, b) # argument:a, argument:b, loaded_variable:a, loaded_variable:b, loaded_variable:random, member_call:random:randint, member_call_method:randint, member_call_object:random, node:Attribute, node:Call, node:Expr, node:Name
# ----------------------------------------------------------------------------------------
# 016.1530-depth-first-traversing-of-a-binary-tree.py
# ----------------------------------------------------------------------------------------
def dfs(bt): # body_recursive_function:dfs (-> +5), function:dfs (-> +5), function_line_count:6 (-> +5), function_parameter:bt, function_parameter_flavor:arg, function_returning_nothing:dfs (-> +5), local_scope:bt (-> +5), node:FunctionDef (-> +5), node:arg, procedural_style (-> +5), recursive_call_count:2 (-> +5), recursive_function:dfs (-> +5), scope:bt (-> +5), variety:4 (-> +5), whole_span:6 (-> +5)
if bt is None: # comparison_operator:Is, if (-> +1), if_guard (-> +1), if_test_atom:None, if_test_atom:bt, if_without_else (-> +1), literal:None, loaded_variable:bt, node:Compare, node:If (-> +1), node:Name, node:NameConstant
return # if_then_branch, node:Return, return:None
dfs(bt.left) # argument:, free_call:dfs, free_call_without_result:dfs, internal_free_call:dfs, loaded_variable:bt, node:Attribute, node:Call, node:Expr, node:Name
f(bt) # argument:bt, external_free_call:f, free_call:f, free_call_without_result:f, loaded_variable:bt, node:Call, node:Expr, node:Name
dfs(bt.right) # argument:, free_call:dfs, free_call_without_result:dfs, internal_free_call:dfs, loaded_variable:bt, node:Attribute, node:Call, node:Expr, node:Name
# ----------------------------------------------------------------------------------------
# 017.1103-create-a-tree-data-structure.py
# ----------------------------------------------------------------------------------------
class Node(object): # class:Node (-> +3), class_method_count:1 (-> +3), loaded_variable:object, node:ClassDef (-> +3), node:Name, object_oriented_style (-> +3), variety:2 (-> +3), whole_span:4 (-> +3)
def __init__(self, value, *children): # function:__init__ (-> +2), function_line_count:3 (-> +2), function_parameter:children, function_parameter:self, function_parameter:value, function_parameter_flavor:arg, function_parameter_flavor:vararg, function_returning_nothing:__init__ (-> +2), instance_method:__init__ (-> +2), local_scope:children (-> +2), local_scope:self (-> +2), local_scope:value (-> +2), method:__init__ (-> +2), node:FunctionDef (-> +2), node:arg, scope:children (-> +2), scope:self (-> +2), scope:value (-> +2)
self.value = value # assignment, assignment_lhs_identifier:self, assignment_rhs_atom:value, loaded_variable:self, loaded_variable:value, node:Assign, node:Attribute, node:Name
self.children = list(children) # argument:children, assignment:list, assignment_lhs_identifier:self, assignment_rhs_atom:children, external_free_call:list, free_call:list, loaded_variable:children, loaded_variable:self, node:Assign, node:Attribute, node:Call, node:Name
# ----------------------------------------------------------------------------------------
# 018.2084-depth-first-traversing-of-a-tree.py
# ----------------------------------------------------------------------------------------
def DFS(f, root): # body_recursive_function:DFS (-> +3), function:DFS (-> +3), function_line_count:4 (-> +3), function_parameter:f, function_parameter:root, function_parameter_flavor:arg, function_returning_nothing:DFS (-> +3), higher_order_function:f (-> +3), local_scope:child (-> +3), local_scope:f (-> +3), local_scope:root (-> +3), node:FunctionDef (-> +3), node:arg, procedural_style (-> +3), recursive_call_count:1 (-> +3), recursive_function:DFS (-> +3), scope:child (-> +3), scope:f (-> +3), scope:root (-> +3), variety:2 (-> +3), whole_span:4 (-> +3)
f(root) # argument:root, external_free_call:f, free_call:f, free_call_without_result:f, loaded_variable:root, node:Call, node:Expr, node:Name
for child in root: # for:child (-> +1), for_each:child (-> +1), iteration_variable:child, loaded_variable:root, loop:for (-> +1), loop_with_late_exit:for (-> +1), node:For (-> +1), node:Name
DFS(f, child) # argument:child, argument:f, free_call:DFS, free_call_without_result:DFS, internal_free_call:DFS, loaded_variable:child, loaded_variable:f, node:Call, node:Expr, node:Name
# ----------------------------------------------------------------------------------------
# 019.0197-reverse-a-list.py
# ----------------------------------------------------------------------------------------
x = reversed(x) # argument:x, assignment:reversed, assignment_lhs_identifier:x, assignment_rhs_atom:x, external_free_call:reversed, flat_style, free_call:reversed, global_scope:x, imperative_style, loaded_variable:x, node:Assign, node:Call, node:Name, one_liner_style, scope:x, single_assignment:x, variety:1, whole_span:1
# ----------------------------------------------------------------------------------------
# 019.1983-reverse-a-list.py
# ----------------------------------------------------------------------------------------
y = x[::-1] # assignment, assignment_lhs_identifier:y, assignment_rhs_atom:-1, assignment_rhs_atom:x, flat_style, global_scope:y, imperative_style, literal:-1, loaded_variable:x, node:Assign, node:Name, node:Num, node:Subscript, one_liner_style, scope:y, single_assignment:y, slice:::-1, slice_lower:, slice_step:-1, slice_upper:, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 019.3164-reverse-a-list.py
# ----------------------------------------------------------------------------------------
x.reverse() # flat_style, imperative_style, loaded_variable:x, member_call:x:reverse, member_call_method:reverse, member_call_object:x, node:Attribute, node:Call, node:Expr, node:Name, one_liner_style, variety:1, whole_span:1
# ----------------------------------------------------------------------------------------
# 020.0573-return-two-values.py
# ----------------------------------------------------------------------------------------
def search(m, x): # function:search (-> +3), function_line_count:4 (-> +3), function_parameter:m, function_parameter:x, function_parameter_flavor:arg, function_returning_something:search (-> +3), impure_function:search (-> +3), local_scope:idx (-> +3), local_scope:item (-> +3), local_scope:m (-> +3), local_scope:x (-> +3), node:FunctionDef (-> +3), node:arg, procedural_style (-> +3), scope:idx (-> +3), scope:item (-> +3), scope:m (-> +3), scope:x (-> +3), variety:2 (-> +3), whole_span:4 (-> +3)
for idx, item in enumerate(m): # argument:m, external_free_call:enumerate, for:idx (-> +2), for:item (-> +2), for_indexes_elements:idx (-> +2), free_call:enumerate, iteration_variable:idx, iteration_variable:item, literal:Tuple, loaded_variable:m, loop:for (-> +2), loop_with_early_exit:for:return (-> +2), loop_with_return:for (-> +2), node:Call, node:For (-> +2), node:Name, node:Tuple
if x in item: # comparison_operator:In, if (-> +1), if_test_atom:item, if_test_atom:x, if_without_else (-> +1), loaded_variable:item, loaded_variable:x, node:Compare, node:If (-> +1), node:Name
return idx, item.index(x) # argument:x, if_then_branch, literal:Tuple, loaded_variable:idx, loaded_variable:item, loaded_variable:x, member_call_method:index, node:Attribute, node:Call, node:Name, node:Return, node:Tuple, return
# ----------------------------------------------------------------------------------------
# 021.0084-swap-values-of-variables-a-and-b.py
# ----------------------------------------------------------------------------------------
a, b = b, a # assignment, assignment_lhs_identifier:a, assignment_lhs_identifier:b, assignment_rhs_atom:a, assignment_rhs_atom:b, flat_style, global_scope:a, global_scope:b, imperative_style, literal:Tuple, loaded_variable:a, loaded_variable:b, node:Assign, node:Name, node:Tuple, one_liner_style, parallel_assignment:2, scope:a, scope:b, swap, update:a:b, update:b:a, update_by_assignment:a:b, update_by_assignment:b:a, update_by_assignment_with, update_with, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 022.0243-convert-string-to-integer.py
# ----------------------------------------------------------------------------------------
i = int(s) # argument:s, assignment:int, assignment_lhs_identifier:i, assignment_rhs_atom:s, external_free_call:int, flat_style, free_call:int, global_scope:i, imperative_style, loaded_variable:s, node:Assign, node:Call, node:Name, one_liner_style, scope:i, single_assignment:i, variety:1, whole_span:1
# ----------------------------------------------------------------------------------------
# 023.1102-convert-real-number-to-string-with-2-decimal-places.py
# ----------------------------------------------------------------------------------------
s = "{:.2f}".format(x) # argument:x, assignment:format, assignment_lhs_identifier:s, assignment_rhs_atom:x, flat_style, global_scope:s, imperative_style, literal:Str, loaded_variable:x, member_call_method:format, node:Assign, node:Attribute, node:Call, node:Name, node:Str, one_liner_style, scope:s, single_assignment:s, variety:1, whole_span:1
# ----------------------------------------------------------------------------------------
# 024.0664-assign-to-string-the-japanese-word-.py
# ----------------------------------------------------------------------------------------
s = "ใใณ" # assignment, assignment_lhs_identifier:s, flat_style, global_scope:s, imperative_style, literal:Str, node:Assign, node:Name, node:Str, one_liner_style, scope:s, single_assignment:s, special_literal_string:ใใณ, variety:1, whole_span:1
# ----------------------------------------------------------------------------------------
# 025.0195-send-a-value-to-another-thread.py
# ----------------------------------------------------------------------------------------
import Queue # flat_style (-> +5), global_scope:q (-> +5), global_scope:t (-> +5), imperative_style (-> +5), import:Queue, import_module:Queue, node:Import, scope:q (-> +5), scope:t (-> +5), variety:3 (-> +5), whole_span:6 (-> +5)
q = Queue() # assignment:Queue, assignment_lhs_identifier:q, external_free_call:Queue, free_call:Queue, free_call_no_arguments:Queue, node:Assign, node:Call, node:Name, single_assignment:q
t = Thread(target=worker) # argument:worker, assignment:Thread, assignment_lhs_identifier:t, assignment_rhs_atom:worker, external_free_call:Thread, free_call:Thread, free_call_with_keyword_argument:Thread:target, keyword_argument:target, loaded_variable:worker, node:Assign, node:Call, node:Name, single_assignment:t
t.daemon = True # assignment:True, assignment_lhs_identifier:t, assignment_rhs_atom:True, literal:True, loaded_variable:t, node:Assign, node:Attribute, node:Name, node:NameConstant
t.start() # loaded_variable:t, member_call:t:start, member_call_method:start, member_call_object:t, node:Attribute, node:Call, node:Expr, node:Name
q.put("Alan") # argument:, literal:Str, loaded_variable:q, member_call:q:put, member_call_method:put, member_call_object:q, node:Attribute, node:Call, node:Expr, node:Name, node:Str
# ----------------------------------------------------------------------------------------
# 026.0194-create-a-2-dimensional-array.py
# ----------------------------------------------------------------------------------------
x = [[0 for j in xrange(n)] for i in xrange(m)] # argument:m, argument:n, assignment, assignment_lhs_identifier:x, assignment_rhs_atom:0, assignment_rhs_atom:i, assignment_rhs_atom:j, assignment_rhs_atom:m, assignment_rhs_atom:n, comprehension:List, comprehension_for_count:1, external_free_call:xrange, flat_style, free_call:xrange, imperative_style, iteration_variable:i, iteration_variable:j, literal:0, loaded_variable:m, loaded_variable:n, local_scope:i, local_scope:j, local_scope:x, node:Assign, node:Call, node:ListComp, node:Name, node:Num, one_liner_style, scope:i, scope:j, scope:x, single_assignment:x, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 027.0192-create-a-3-dimensional-array.py
# ----------------------------------------------------------------------------------------
x = [[[0 for k in xrange(p)] for j in xrange(n)] for i in xrange(m)] # argument:m, argument:n, argument:p, assignment, assignment_lhs_identifier:x, assignment_rhs_atom:0, assignment_rhs_atom:i, assignment_rhs_atom:j, assignment_rhs_atom:k, assignment_rhs_atom:m, assignment_rhs_atom:n, assignment_rhs_atom:p, comprehension:List, comprehension_for_count:1, external_free_call:xrange, flat_style, free_call:xrange, imperative_style, iteration_variable:i, iteration_variable:j, iteration_variable:k, literal:0, loaded_variable:m, loaded_variable:n, loaded_variable:p, local_scope:i, local_scope:j, local_scope:k, local_scope:x, node:Assign, node:Call, node:ListComp, node:Name, node:Num, one_liner_style, scope:i, scope:j, scope:k, scope:x, single_assignment:x, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 027.0193-create-a-3-dimensional-array.py
# ----------------------------------------------------------------------------------------
import numpy # flat_style (-> +1), global_scope:x (-> +1), imperative_style (-> +1), import:numpy, import_module:numpy, node:Import, one_liner_style (-> +1), scope:x (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
x = numpy.zeros((m, n, p)) # argument:, assignment:zeros, assignment_lhs_identifier:x, assignment_rhs_atom:m, assignment_rhs_atom:n, assignment_rhs_atom:numpy, assignment_rhs_atom:p, literal:Tuple, loaded_variable:m, loaded_variable:n, loaded_variable:numpy, loaded_variable:p, member_call_method:zeros, node:Assign, node:Attribute, node:Call, node:Name, node:Tuple, single_assignment:x
# ----------------------------------------------------------------------------------------
# 028.0350-sort-by-a-property.py
# ----------------------------------------------------------------------------------------
items = sorted(items, key=lambda x: x.p) # argument:, argument:items, assignment:sorted, assignment_lhs_identifier:items, assignment_rhs_atom:items, assignment_rhs_atom:x, external_free_call:sorted, flat_style, free_call:sorted, free_call_with_keyword_argument:sorted:key, function_parameter:x, function_parameter_flavor:arg, global_scope:items, global_scope:x, imperative_style, keyword_argument:key, loaded_variable:items, loaded_variable:x, node:Assign, node:Attribute, node:Call, node:Lambda, node:Name, node:arg, one_liner_style, scope:items, scope:x, single_assignment:items, update:items:x, update_by_assignment:items:x, update_by_assignment_with:sorted, update_with:sorted, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 029.0199-remove-item-from-list-by-its-index.py
# ----------------------------------------------------------------------------------------
del items[i] # flat_style, imperative_style, index:i, loaded_variable:i, loaded_variable:items, node:Delete, node:Name, node:Subscript, one_liner_style, subscript_deletion:Name, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 030.0189-parallelize-execution-of-1000-independent-tasks.py
# ----------------------------------------------------------------------------------------
from multiprocessing import Pool # global_scope:i (-> +3), global_scope:pool (-> +3), imperative_style (-> +3), import:multiprocessing:Pool, import_module:multiprocessing, import_name:Pool, node:ImportFrom, scope:i (-> +3), scope:pool (-> +3), variety:2 (-> +3), whole_span:4 (-> +3)
pool = Pool() # assignment:Pool, assignment_lhs_identifier:pool, external_free_call:Pool, free_call:Pool, free_call_no_arguments:Pool, node:Assign, node:Call, node:Name, single_assignment:pool
for i in range(1, 1001): # argument:1, argument:1001, external_free_call:range, for:i (-> +1), for_range:1:1001 (-> +1), free_call:range, iteration_variable:i, literal:1, literal:1001, loop:for (-> +1), loop_with_late_exit:for (-> +1), magic_number:1001, node:Call, node:For (-> +1), node:Name, node:Num, range:1:1001
pool.apply_async(f, [i]) # argument:, argument:f, literal:List, loaded_variable:f, loaded_variable:i, loaded_variable:pool, member_call:pool:apply_async, member_call_method:apply_async, member_call_object:pool, node:Attribute, node:Call, node:Expr, node:List, node:Name
# ----------------------------------------------------------------------------------------
# 031.0188-recursive-factorial-simple.py
# ----------------------------------------------------------------------------------------
def f(i): # body_recursive_function:f (-> +4), function:f (-> +4), function_line_count:5 (-> +4), function_parameter:i, function_parameter_flavor:arg, function_returning_something:f (-> +4), functional_style (-> +4), local_scope:i (-> +4), node:FunctionDef (-> +4), node:arg, pure_function:f (-> +4), recursive_call_count:1 (-> +4), recursive_function:f (-> +4), scope:i (-> +4), variety:3 (-> +4), whole_span:5 (-> +4)
if i == 0: # comparison_operator:Eq, if (-> +3), if_test_atom:0, if_test_atom:i, literal:0, loaded_variable:i, node:Compare, node:If (-> +3), node:Name, node:Num
return 1 # if_then_branch, literal:1, node:Num, node:Return, return:1
else:
return i * f(i - 1) # argument:, binary_operator:Mult, binary_operator:Sub, free_call:f, if_else_branch, internal_free_call:f, literal:1, loaded_variable:i, multiplication_operator, node:BinOp, node:Call, node:Name, node:Num, node:Return, return
# ----------------------------------------------------------------------------------------
# 032.0196-integer-exponentiation-by-squaring.py
# ----------------------------------------------------------------------------------------
def exp(x, n): # function:exp (-> +1), function_line_count:2 (-> +1), function_parameter:n, function_parameter:x, function_parameter_flavor:arg, function_returning_something:exp (-> +1), functional_style (-> +1), local_scope:n (-> +1), local_scope:x (-> +1), node:FunctionDef (-> +1), node:arg, one_liner_style (-> +1), pure_function:exp (-> +1), scope:n (-> +1), scope:x (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
return x ** n # binary_operator:Pow, loaded_variable:n, loaded_variable:x, node:BinOp, node:Name, node:Return, return
# ----------------------------------------------------------------------------------------
# 033.1420-atomically-read-and-update-variable.py
# ----------------------------------------------------------------------------------------
import threading # flat_style (-> +6), global_scope:lock (-> +6), global_scope:x (-> +6), imperative_style (-> +6), import:threading, import_module:threading, node:Import, scope:lock (-> +6), scope:x (-> +6), variety:2 (-> +6), whole_span:7 (-> +6)
lock = threading.Lock() # assignment:Lock, assignment_lhs_identifier:lock, assignment_rhs_atom:threading, loaded_variable:threading, member_call_method:Lock, node:Assign, node:Attribute, node:Call, node:Name, single_assignment:lock
lock.acquire() # loaded_variable:lock, member_call:lock:acquire, member_call_method:acquire, member_call_object:lock, node:Attribute, node:Call, node:Expr, node:Name
try: # node:Try (-> +3)
x = f(x) # argument:x, assignment:f, assignment_lhs_identifier:x, assignment_rhs_atom:x, external_free_call:f, free_call:f, loaded_variable:x, node:Assign, node:Call, node:Name, single_assignment:x
finally:
lock.release() # loaded_variable:lock, member_call:lock:release, member_call_method:release, member_call_object:lock, node:Attribute, node:Call, node:Expr, node:Name
# ----------------------------------------------------------------------------------------
# 034.0625-create-a-set-of-objects.py
# ----------------------------------------------------------------------------------------
class T(object): # class:T (-> +1), global_scope:x (-> +2), loaded_variable:object, node:ClassDef (-> +1), node:Name, object_oriented_style (-> +2), scope:x (-> +2), variety:2 (-> +2), whole_span:3 (-> +2)
pass # no_operation, node:Pass
x = set(T()) # argument:, assignment:set, assignment_lhs_identifier:x, composition, external_free_call:T, external_free_call:set, free_call:T, free_call:set, free_call_no_arguments:T, node:Assign, node:Call, node:Name, single_assignment:x
# ----------------------------------------------------------------------------------------
# 035.0667-first-class-function--compose.py
# ----------------------------------------------------------------------------------------
def compose(f, g): # function:compose (-> +1), function_line_count:2 (-> +1), function_parameter:f, function_parameter:g, function_parameter_flavor:arg, function_returning_something:compose (-> +1), functional_style (-> +1), higher_order_function:f (-> +1), higher_order_function:g (-> +1), local_scope:a (-> +1), local_scope:f (-> +1), local_scope:g (-> +1), node:FunctionDef (-> +1), node:arg, one_liner_style (-> +1), pure_function:compose (-> +1), scope:a (-> +1), scope:f (-> +1), scope:g (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
return lambda a: g(f(a)) # argument:, argument:a, composition, external_free_call:f, external_free_call:g, free_call:f, free_call:g, function_parameter:a, function_parameter_flavor:arg, loaded_variable:a, node:Call, node:Lambda, node:Name, node:Return, node:arg, return
# ----------------------------------------------------------------------------------------
# 036.0670-first-class-function--generic-composition.py
# ----------------------------------------------------------------------------------------
def compose(f, g): # function:compose (-> +1), function_line_count:2 (-> +1), function_parameter:f, function_parameter:g, function_parameter_flavor:arg, function_returning_something:compose (-> +1), functional_style (-> +1), higher_order_function:f (-> +1), higher_order_function:g (-> +1), local_scope:f (-> +1), local_scope:g (-> +1), local_scope:x (-> +1), node:FunctionDef (-> +1), node:arg, one_liner_style (-> +1), pure_function:compose (-> +1), scope:f (-> +1), scope:g (-> +1), scope:x (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
return lambda x: g(f(x)) # argument:, argument:x, composition, external_free_call:f, external_free_call:g, free_call:f, free_call:g, function_parameter:x, function_parameter_flavor:arg, loaded_variable:x, node:Call, node:Lambda, node:Name, node:Return, node:arg, return
# ----------------------------------------------------------------------------------------
# 037.0671-currying.py
# ----------------------------------------------------------------------------------------
from functools import partial # functional_style (-> +5), import:functools:partial, import_module:functools, import_name:partial, node:ImportFrom, variety:3 (-> +5), whole_span:6 (-> +5)
def f(a): # closure:f (-> +3), function:f (-> +3), function_line_count:4 (-> +3), function_parameter:a, function_parameter_flavor:arg, function_returning_something:f (-> +3), local_scope:a (-> +3), nested_function:f (-> +3), node:FunctionDef (-> +3), node:arg, pure_function:f (-> +3), scope:a (-> +3)
def add(b): # access_outer_scope:a (-> +1), function:add (-> +1), function_line_count:2 (-> +1), function_parameter:b, function_parameter_flavor:arg, function_returning_something:add (-> +1), local_scope:b (-> +1), node:FunctionDef (-> +1), node:arg, pure_function:add (-> +1), scope:b (-> +1)
return a + b # addition_operator, binary_operator:Add, loaded_variable:a, loaded_variable:b, node:BinOp, node:Name, node:Return, return
return add # loaded_variable:add, node:Name, node:Return, return:add
print(f(2)(1)) # argument:, argument:1, argument:2, composition, external_free_call:print, free_call:f, free_call:print, free_call_without_result:print, internal_free_call:f, literal:1, literal:2, node:Call, node:Expr, node:Name, node:Num
# ----------------------------------------------------------------------------------------
# 038.0186-extract-a-substring.py
# ----------------------------------------------------------------------------------------
t = s[i:j] # assignment, assignment_lhs_identifier:t, assignment_rhs_atom:i, assignment_rhs_atom:j, assignment_rhs_atom:s, flat_style, global_scope:t, imperative_style, loaded_variable:i, loaded_variable:j, loaded_variable:s, node:Assign, node:Name, node:Subscript, one_liner_style, scope:t, single_assignment:t, slice:i:j:, slice_lower:i, slice_step:, slice_upper:j, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 039.0571-check-if-string-contains-a-word.py
# ----------------------------------------------------------------------------------------
ok = word in s # assignment, assignment_lhs_identifier:ok, assignment_rhs_atom:s, assignment_rhs_atom:word, comparison_operator:In, flat_style, global_scope:ok, imperative_style, loaded_variable:s, loaded_variable:word, node:Assign, node:Compare, node:Name, one_liner_style, scope:ok, single_assignment:ok, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 040.2279-graph-with-adjacency-lists.py
# ----------------------------------------------------------------------------------------
from collections import defaultdict # global_scope:G (-> +12), import:collections:defaultdict, import_module:collections, import_name:defaultdict, node:ImportFrom, object_oriented_style (-> +12), scope:G (-> +12), variety:4 (-> +12), whole_span:13 (-> +12)
class Vertex(set): # class:Vertex (-> +1), class_method_count:2 (-> +1), loaded_variable:set, node:ClassDef (-> +1), node:Name
pass # no_operation, node:Pass
class Graph(defaultdict): # class:Graph (-> +8), class_method_count:2 (-> +8), loaded_variable:defaultdict, node:ClassDef (-> +8), node:Name
def __init__(self, *paths): # function:__init__ (-> +3), function_line_count:4 (-> +3), function_parameter:paths, function_parameter:self, function_parameter_flavor:arg, function_parameter_flavor:vararg, function_returning_nothing:__init__ (-> +3), instance_method:__init__ (-> +3), local_scope:path (-> +3), local_scope:paths (-> +3), local_scope:self (-> +3), method:__init__ (-> +3), node:FunctionDef (-> +3), node:arg, scope:path (-> +3), scope:paths (-> +3), scope:self (-> +3)
self.default_factory = Vertex # assignment, assignment_lhs_identifier:self, assignment_rhs_atom:Vertex, loaded_variable:Vertex, loaded_variable:self, node:Assign, node:Attribute, node:Name
for path in paths: # for:path (-> +1), for_each:path (-> +1), iteration_variable:path, loaded_variable:paths, loop:for (-> +1), loop_with_late_exit:for (-> +1), node:For (-> +1), node:Name
self.make_path(path) # argument:path, loaded_variable:path, loaded_variable:self, member_call:self:make_path, member_call_method:make_path, member_call_object:self, node:Attribute, node:Call, node:Expr, node:Name
def make_path(self, labels): # function:make_path (-> +3), function_line_count:4 (-> +3), function_parameter:labels, function_parameter:self, function_parameter_flavor:arg, function_returning_nothing:make_path (-> +3), instance_method:make_path (-> +3), local_scope:l1 (-> +3), local_scope:l2 (-> +3), local_scope:labels (-> +3), local_scope:self (-> +3), method:make_path (-> +3), node:FunctionDef (-> +3), node:arg, scope:l1 (-> +3), scope:l2 (-> +3), scope:labels (-> +3), scope:self (-> +3)
for l1, l2 in zip(labels, labels[1:]): # argument:, argument:labels, external_free_call:zip, for:l1 (-> +2), for:l2 (-> +2), free_call:zip, iteration_variable:l1, iteration_variable:l2, literal:1, literal:Tuple, loaded_variable:labels, loop:for (-> +2), loop_with_late_exit:for (-> +2), node:Call, node:For (-> +2), node:Name, node:Num, node:Subscript, node:Tuple, slice:1::, slice_lower:1, slice_step:, slice_upper:
self[l1].add(l2) # argument:l2, index:l1, loaded_variable:l1, loaded_variable:l2, loaded_variable:self, member_call_method:add, node:Attribute, node:Call, node:Expr, node:Name, node:Subscript
self[l2].add(l1) # argument:l1, index:l2, loaded_variable:l1, loaded_variable:l2, loaded_variable:self, member_call_method:add, node:Attribute, node:Call, node:Expr, node:Name, node:Subscript
G = Graph((0, 1, 2, 3), (1, 4, 2)) # argument:, assignment:Graph, assignment_lhs_identifier:G, assignment_rhs_atom:0, assignment_rhs_atom:1, assignment_rhs_atom:2, assignment_rhs_atom:3, assignment_rhs_atom:4, external_free_call:Graph, free_call:Graph, literal:0, literal:1, literal:2, literal:3, literal:4, literal:Tuple, node:Assign, node:Call, node:Name, node:Num, node:Tuple, single_assignment:G
# ----------------------------------------------------------------------------------------
# 041.0187-reverse-a-string.py
# ----------------------------------------------------------------------------------------
t = s.decode("utf8")[::-1].encode("utf8") # argument:, assignment:encode, assignment_lhs_identifier:t, assignment_rhs_atom:-1, assignment_rhs_atom:s, flat_style, global_scope:t, imperative_style, literal:-1, literal:Str, loaded_variable:s, member_call:s:decode, member_call:s:encode, member_call_method:decode, member_call_method:encode, member_call_object:s, node:Assign, node:Attribute, node:Call, node:Name, node:Num, node:Str, node:Subscript, one_liner_style, scope:t, single_assignment:t, slice:::-1, slice_lower:, slice_step:-1, slice_upper:, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 041.2714-reverse-a-string.py
# ----------------------------------------------------------------------------------------
t = s[::-1] # assignment, assignment_lhs_identifier:t, assignment_rhs_atom:-1, assignment_rhs_atom:s, flat_style, global_scope:t, imperative_style, literal:-1, loaded_variable:s, node:Assign, node:Name, node:Num, node:Subscript, one_liner_style, scope:t, single_assignment:t, slice:::-1, slice_lower:, slice_step:-1, slice_upper:, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 042.1264-continue-outer-loop.py
# ----------------------------------------------------------------------------------------
for v in a: # for:v (-> +7), for_each:v (-> +7), global_scope:u (-> +7), global_scope:v (-> +7), imperative_style (-> +7), iteration_variable:v, loaded_variable:a, loop:for (-> +7), loop_with_early_exit:for:raise (-> +7), loop_with_raise:for (-> +7), node:For (-> +7), node:Name, scope:u (-> +7), scope:v (-> +7), variety:4 (-> +7), whole_span:8 (-> +7)
try: # node:Try (-> +6), try_except:Exception (-> +6), try_raise:Exception (-> +6)
for u in b: # for:u (-> +2), for_each:u (-> +2), iteration_variable:u, loaded_variable:b, loop:for (-> +2), loop_with_early_exit:for:raise (-> +2), loop_with_raise:for (-> +2), nested_for:1 (-> +2), node:For (-> +2), node:Name
if v == u: # comparison_operator:Eq, if (-> +1), if_test_atom:u, if_test_atom:v, if_without_else (-> +1), loaded_variable:u, loaded_variable:v, node:Compare, node:If (-> +1), node:Name
raise Exception() # external_free_call:Exception, free_call:Exception, free_call_no_arguments:Exception, if_then_branch, node:Call, node:Name, node:Raise, raise:Exception
print(v) # argument:v, external_free_call:print, free_call:print, free_call_without_result:print, loaded_variable:v, node:Call, node:Expr, node:Name
except Exception: # except:Exception, loaded_variable:Exception, node:ExceptHandler (-> +1), node:Name
continue # node:Continue
# ----------------------------------------------------------------------------------------
# 042.3168-continue-outer-loop.py
# ----------------------------------------------------------------------------------------
for v in a: # for:v (-> +4), for_each:v (-> +4), global_scope:v (-> +4), global_scope:v_ (-> +4), imperative_style (-> +4), iteration_variable:v, loaded_variable:a, loop:for (-> +4), loop_with_late_exit:for (-> +4), node:For (-> +4), node:Name, scope:v (-> +4), scope:v_ (-> +4), variety:3 (-> +4), whole_span:5 (-> +4)
for v_ in b: # for:v_ (-> +3), for_each:v_ (-> +3), iteration_variable:v_, loaded_variable:b, loop:for (-> +3), loop_with_late_exit:for (-> +3), nested_for:1 (-> +3), node:For (-> +3), node:Name
if v == v_: # comparison_operator:Eq, if (-> +1), if_test_atom:v, if_test_atom:v_, if_without_else (-> +1), loaded_variable:v, loaded_variable:v_, node:Compare, node:If (-> +1), node:Name
continue # if_then_branch, node:Continue
print(v) # argument:v, external_free_call:print, free_call:print, free_call_without_result:print, loaded_variable:v, node:Call, node:Expr, node:Name
# ----------------------------------------------------------------------------------------
# 043.0676-break-outer-loop.py
# ----------------------------------------------------------------------------------------
class BreakOuterLoop(Exception): # class:BreakOuterLoop (-> +1), global_scope:column (-> +10), global_scope:position (-> +10), global_scope:row (-> +10), loaded_variable:Exception, node:ClassDef (-> +1), node:Name, object_oriented_style (-> +10), scope:column (-> +10), scope:position (-> +10), scope:row (-> +10), variety:5 (-> +10), whole_span:11 (-> +10)
pass # no_operation, node:Pass
try: # node:Try (-> +8), try_except:BreakOuterLoop (-> +8), try_raise:BreakOuterLoop (-> +8)
position = None # assignment:None, assignment_lhs_identifier:position, assignment_rhs_atom:None, literal:None, node:Assign, node:Name, node:NameConstant, single_assignment:position
for row in m: # for:row (-> +4), for_each:row (-> +4), iteration_variable:row, loaded_variable:m, loop:for (-> +4), loop_with_early_exit:for:raise (-> +4), loop_with_raise:for (-> +4), node:For (-> +4), node:Name
for column in m[row]: # for:column (-> +3), index:row, iteration_variable:column, loaded_variable:m, loaded_variable:row, loop:for (-> +3), loop_with_early_exit:for:raise (-> +3), loop_with_raise:for (-> +3), nested_for:1 (-> +3), node:For (-> +3), node:Name, node:Subscript
if m[row][column] == v: # comparison_operator:Eq, if (-> +2), if_test_atom:column, if_test_atom:m, if_test_atom:row, if_test_atom:v, if_without_else (-> +2), index:column, index:row, index_shape:2, loaded_variable:column, loaded_variable:m, loaded_variable:row, loaded_variable:v, nested_index, node:Compare, node:If (-> +2), node:Name, node:Subscript
position = (row, column) # assignment, assignment_lhs_identifier:position, assignment_rhs_atom:column, assignment_rhs_atom:row, if_then_branch (-> +1), literal:Tuple, loaded_variable:column, loaded_variable:row, node:Assign, node:Name, node:Tuple, single_assignment:position
raise BreakOuterLoop # loaded_variable:BreakOuterLoop, node:Name, node:Raise, raise:BreakOuterLoop
except BreakOuterLoop: # except:BreakOuterLoop, loaded_variable:BreakOuterLoop, node:ExceptHandler (-> +1), node:Name
pass # no_operation, node:Pass
# ----------------------------------------------------------------------------------------
# 043.2733-break-outer-loop.py
# ----------------------------------------------------------------------------------------
def loop_breaking(m, v): # function:loop_breaking (-> +5), function_line_count:6 (-> +5), function_parameter:m, function_parameter:v, function_parameter_flavor:arg, function_returning_something:loop_breaking (-> +5), impure_function:loop_breaking (-> +5), local_scope:i (-> +5), local_scope:j (-> +5), local_scope:m (-> +5), local_scope:row (-> +5), local_scope:v (-> +5), local_scope:value (-> +5), node:FunctionDef (-> +5), node:arg, procedural_style (-> +6), scope:i (-> +5), scope:j (-> +5), scope:m (-> +5), scope:row (-> +5), scope:v (-> +5), scope:value (-> +5), variety:2 (-> +6), whole_span:7 (-> +6)
for i, row in enumerate(m): # argument:m, external_free_call:enumerate, for:i (-> +3), for:row (-> +3), for_indexes_elements:i (-> +3), free_call:enumerate, iteration_variable:i, iteration_variable:row, literal:Tuple, loaded_variable:m, loop:for (-> +3), loop_with_early_exit:for:return (-> +3), loop_with_return:for (-> +3), node:Call, node:For (-> +3), node:Name, node:Tuple
for j, value in enumerate(row): # argument:row, external_free_call:enumerate, for:j (-> +2), for:value (-> +2), for_indexes_elements:j (-> +2), free_call:enumerate, iteration_variable:j, iteration_variable:value, literal:Tuple, loaded_variable:row, loop:for (-> +2), loop_with_early_exit:for:return (-> +2), loop_with_return:for (-> +2), nested_for:1 (-> +2), node:Call, node:For (-> +2), node:Name, node:Tuple
if value == v: # comparison_operator:Eq, if (-> +1), if_test_atom:v, if_test_atom:value, if_without_else (-> +1), loaded_variable:v, loaded_variable:value, node:Compare, node:If (-> +1), node:Name
return (i, j) # if_then_branch, literal:Tuple, loaded_variable:i, loaded_variable:j, node:Name, node:Return, node:Tuple, return
return None # literal:None, node:NameConstant, node:Return, return:None
print(loop_breaking(([1, 2, 3], [4, 5, 6], [7, 8, 9]), 6)) # argument:, argument:6, composition, external_free_call:print, free_call:loop_breaking, free_call:print, free_call_without_result:print, internal_free_call:loop_breaking, literal:1, literal:2, literal:3, literal:4, literal:5, literal:6, literal:7, literal:8, literal:9, literal:List, literal:Tuple, magic_number:3, magic_number:4, magic_number:5, magic_number:6, magic_number:7, magic_number:8, magic_number:9, node:Call, node:Expr, node:List, node:Name, node:Num, node:Tuple
# ----------------------------------------------------------------------------------------
# 044.0190-insert-element-in-list.py
# ----------------------------------------------------------------------------------------
s.insert(i, x) # argument:i, argument:x, flat_style, imperative_style, loaded_variable:i, loaded_variable:s, loaded_variable:x, member_call:s:insert, member_call_method:insert, member_call_object:s, node:Attribute, node:Call, node:Expr, node:Name, one_liner_style, update:s:i, update:s:x, update_by_member_call:s:i, update_by_member_call:s:x, update_by_member_call_with:insert, update_with:insert, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 045.0570-pause-execution-for-5-seconds.py
# ----------------------------------------------------------------------------------------
import time # flat_style (-> +1), imperative_style (-> +1), import:time, import_module:time, node:Import, one_liner_style (-> +1), variety:2 (-> +1), whole_span:2 (-> +1)
time.sleep(5) # argument:5, literal:5, loaded_variable:time, magic_number:5, member_call:time:sleep, member_call_method:sleep, member_call_object:time, node:Attribute, node:Call, node:Expr, node:Name, node:Num
# ----------------------------------------------------------------------------------------
# 046.0191-extract-beginning-of-string-prefix.py
# ----------------------------------------------------------------------------------------
t = s[:5] # assignment, assignment_lhs_identifier:t, assignment_rhs_atom:5, assignment_rhs_atom:s, flat_style, global_scope:t, imperative_style, literal:5, loaded_variable:s, magic_number:5, node:Assign, node:Name, node:Num, node:Subscript, one_liner_style, scope:t, single_assignment:t, slice::5:, slice_lower:, slice_step:, slice_upper:5, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 047.0198-extract-string-suffix.py
# ----------------------------------------------------------------------------------------
t = s[-5:] # assignment, assignment_lhs_identifier:t, assignment_rhs_atom:-5, assignment_rhs_atom:s, flat_style, global_scope:t, imperative_style, literal:-5, loaded_variable:s, magic_number:-5, node:Assign, node:Name, node:Num, node:Subscript, one_liner_style, scope:t, single_assignment:t, slice:-5::, slice_lower:-5, slice_step:, slice_upper:, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 048.0210-multi-line-string-literal.py
# ----------------------------------------------------------------------------------------
s = """Huey # assignment, assignment_lhs_identifier:s, flat_style, global_scope:s, imperative_style, literal:Str, node:Assign, node:Name, node:Str, one_liner_style, scope:s, single_assignment:s, special_literal_string:Huey\nDewey\nLouie, variety:1, whole_span:1
Dewey
Louie"""
# ----------------------------------------------------------------------------------------
# 049.0242-split-a-space-separated-string.py
# ----------------------------------------------------------------------------------------
chunks = s.split() # assignment:split, assignment_lhs_identifier:chunks, assignment_rhs_atom:s, flat_style, global_scope:chunks, imperative_style, loaded_variable:s, member_call_method:split, node:Assign, node:Attribute, node:Call, node:Name, one_liner_style, scope:chunks, single_assignment:chunks, variety:1, whole_span:1
# ----------------------------------------------------------------------------------------
# 050.0572-make-an-infinite-loop.py
# ----------------------------------------------------------------------------------------
while True: # imperative_style (-> +1), infinite_while (-> +1), literal:True, loop:while (-> +1), loop_with_late_exit:while (-> +1), node:NameConstant, node:While (-> +1), variety:2 (-> +1), whole_span:2 (-> +1)
pass # no_operation, node:Pass
# ----------------------------------------------------------------------------------------
# 051.0230-check-if-map-contains-key.py
# ----------------------------------------------------------------------------------------
k in m # comparison_operator:In, flat_style, imperative_style, loaded_variable:k, loaded_variable:m, node:Compare, node:Expr, node:Name, one_liner_style, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 052.0666-check-if-map-contains-value.py
# ----------------------------------------------------------------------------------------
v in map.values() # comparison_operator:In, flat_style, imperative_style, loaded_variable:map, loaded_variable:v, member_call_method:values, node:Attribute, node:Call, node:Compare, node:Expr, node:Name, one_liner_style, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 053.0240-join-a-list-of-strings.py
# ----------------------------------------------------------------------------------------
y = ", ".join(x) # argument:x, assignment:join, assignment_lhs_identifier:y, assignment_rhs_atom:x, flat_style, global_scope:y, imperative_style, literal:Str, loaded_variable:x, member_call_method:join, node:Assign, node:Attribute, node:Call, node:Name, node:Str, one_liner_style, scope:y, single_assignment:y, variety:1, whole_span:1
# ----------------------------------------------------------------------------------------
# 053.1933-join-a-list-of-strings.py
# ----------------------------------------------------------------------------------------
y = ", ".join(map(str, x)) # argument:, argument:str, argument:x, assignment:join, assignment_lhs_identifier:y, assignment_rhs_atom:str, assignment_rhs_atom:x, composition, external_free_call:map, flat_style, free_call:map, global_scope:y, imperative_style, literal:Str, loaded_variable:str, loaded_variable:x, member_call_method:join, node:Assign, node:Attribute, node:Call, node:Name, node:Str, one_liner_style, scope:y, single_assignment:y, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 054.0241-compute-sum-of-integers.py
# ----------------------------------------------------------------------------------------
s = sum(x) # argument:x, assignment:sum, assignment_lhs_identifier:s, assignment_rhs_atom:x, external_free_call:sum, flat_style, free_call:sum, global_scope:s, imperative_style, loaded_variable:x, node:Assign, node:Call, node:Name, one_liner_style, scope:s, single_assignment:s, variety:1, whole_span:1
# ----------------------------------------------------------------------------------------
# 055.0575-convert-integer-to-string.py
# ----------------------------------------------------------------------------------------
s = str(i) # argument:i, assignment:str, assignment_lhs_identifier:s, assignment_rhs_atom:i, external_free_call:str, flat_style, free_call:str, global_scope:s, imperative_style, loaded_variable:i, node:Assign, node:Call, node:Name, one_liner_style, scope:s, single_assignment:s, variety:1, whole_span:1
# ----------------------------------------------------------------------------------------
# 056.1424-launch-1000-parallel-tasks-and-wait-for-completion.py
# ----------------------------------------------------------------------------------------
from multiprocessing import Pool # import:multiprocessing:Pool, import_module:multiprocessing, import_name:Pool, node:ImportFrom, procedural_style (-> +5), variety:3 (-> +5), whole_span:6 (-> +5)
def f(i): # function:f (-> +1), function_line_count:2 (-> +1), function_parameter:i, function_parameter_flavor:arg, function_returning_nothing:f (-> +1), local_scope:i (-> +1), node:FunctionDef (-> +1), node:arg, scope:i (-> +1)
i * i # binary_operator:Mult, loaded_variable:i, multiplication_operator, node:BinOp, node:Expr, node:Name
with Pool(processes) as p: # argument:processes, external_free_call:Pool, free_call:Pool, loaded_variable:processes, node:Call, node:Name, node:With (-> +1)
p.map(func=f, iterable=range(1, 1001)) # argument:, argument:1, argument:1001, argument:f, external_free_call:range, free_call:range, keyword_argument:func, keyword_argument:iterable, literal:1, literal:1001, loaded_variable:f, loaded_variable:p, magic_number:1001, member_call:p:map, member_call_method:map, member_call_object:p, node:Attribute, node:Call, node:Expr, node:Name, node:Num, range:1:1001
print("Finished") # argument:, external_free_call:print, free_call:print, free_call_without_result:print, literal:Str, node:Call, node:Expr, node:Name, node:Str
# ----------------------------------------------------------------------------------------
# 057.0260-filter-list.py
# ----------------------------------------------------------------------------------------
y = filter(p, x) # argument:p, argument:x, assignment:filter, assignment_lhs_identifier:y, assignment_rhs_atom:p, assignment_rhs_atom:x, external_free_call:filter, flat_style, free_call:filter, global_scope:y, imperative_style, loaded_variable:p, loaded_variable:x, node:Assign, node:Call, node:Name, one_liner_style, scope:y, single_assignment:y, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 057.3173-filter-list.py
# ----------------------------------------------------------------------------------------
y = [element for element in x if p(element)] # argument:element, assignment, assignment_lhs_identifier:y, assignment_rhs_atom:element, assignment_rhs_atom:x, comprehension:List, comprehension_for_count:1, external_free_call:p, filtered_comprehension, flat_style, free_call:p, imperative_style, iteration_variable:element, loaded_variable:element, loaded_variable:x, local_scope:element, local_scope:y, node:Assign, node:Call, node:ListComp, node:Name, one_liner_style, scope:element, scope:y, single_assignment:y, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 058.0665-extract-file-content-to-a-string.py
# ----------------------------------------------------------------------------------------
lines = open(f).read() # argument:f, assignment:read, assignment_lhs_identifier:lines, assignment_rhs_atom:f, external_free_call:open, flat_style, free_call:open, global_scope:lines, imperative_style, loaded_variable:f, member_call_method:read, node:Assign, node:Attribute, node:Call, node:Name, one_liner_style, scope:lines, single_assignment:lines, variety:1, whole_span:1
# ----------------------------------------------------------------------------------------
# 059.0668-write-to-standard-error-stream.py
# ----------------------------------------------------------------------------------------
import sys # flat_style (-> +1), imperative_style (-> +1), import:sys, import_module:sys, node:Import, one_liner_style (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
print(x, "is negative", file=sys.stderr) # argument:, argument:x, external_free_call:print, free_call:print, free_call_with_keyword_argument:print:file, free_call_without_result:print, keyword_argument:file, literal:Str, loaded_variable:sys, loaded_variable:x, node:Attribute, node:Call, node:Expr, node:Name, node:Str, value_attr:stderr
# ----------------------------------------------------------------------------------------
# 060.1084-read-command-line-argument.py
# ----------------------------------------------------------------------------------------
import sys # flat_style (-> +1), global_scope:x (-> +1), imperative_style (-> +1), import:sys, import_module:sys, node:Import, one_liner_style (-> +1), scope:x (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
x = sys.argv[1] # assignment, assignment_lhs_identifier:x, assignment_rhs_atom:1, assignment_rhs_atom:sys, index:1, literal:1, loaded_variable:sys, node:Assign, node:Attribute, node:Name, node:Num, node:Subscript, single_assignment:x, value_attr:argv
# ----------------------------------------------------------------------------------------
# 061.0576-get-current-date.py
# ----------------------------------------------------------------------------------------
import datetime # flat_style (-> +1), global_scope:d (-> +1), imperative_style (-> +1), import:datetime, import_module:datetime, node:Import, one_liner_style (-> +1), scope:d (-> +1), variety:2 (-> +1), whole_span:2 (-> +1)
d = datetime.datetime.now() # assignment:now, assignment_lhs_identifier:d, assignment_rhs_atom:datetime, loaded_variable:datetime, member_call_method:now, node:Assign, node:Attribute, node:Call, node:Name, single_assignment:d, value_attr:datetime
# ----------------------------------------------------------------------------------------
# 062.1091-find-substring-position.py
# ----------------------------------------------------------------------------------------
i = x.find(y) # argument:y, assignment:find, assignment_lhs_identifier:i, assignment_rhs_atom:x, assignment_rhs_atom:y, flat_style, global_scope:i, imperative_style, loaded_variable:x, loaded_variable:y, member_call_method:find, node:Assign, node:Attribute, node:Call, node:Name, one_liner_style, scope:i, single_assignment:i, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 063.1088-replace-fragment-of-a-string.py
# ----------------------------------------------------------------------------------------
x2 = x.replace(y, z) # argument:y, argument:z, assignment:replace, assignment_lhs_identifier:x2, assignment_rhs_atom:x, assignment_rhs_atom:y, assignment_rhs_atom:z, flat_style, global_scope:x2, imperative_style, loaded_variable:x, loaded_variable:y, loaded_variable:z, member_call_method:replace, node:Assign, node:Attribute, node:Call, node:Name, one_liner_style, scope:x2, single_assignment:x2, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 064.0274-big-integer--value-3-power-247.py
# ----------------------------------------------------------------------------------------
x = 3 ** 247 # assignment:Pow, assignment_lhs_identifier:x, assignment_rhs_atom:247, assignment_rhs_atom:3, binary_operator:Pow, flat_style, global_scope:x, imperative_style, literal:247, literal:3, magic_number:247, magic_number:3, node:Assign, node:BinOp, node:Name, node:Num, one_liner_style, scope:x, single_assignment:x, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 065.1085-format-decimal-number.py
# ----------------------------------------------------------------------------------------
s = "{:.1%}".format(x) # argument:x, assignment:format, assignment_lhs_identifier:s, assignment_rhs_atom:x, flat_style, global_scope:s, imperative_style, literal:Str, loaded_variable:x, member_call_method:format, node:Assign, node:Attribute, node:Call, node:Name, node:Str, one_liner_style, scope:s, single_assignment:s, variety:1, whole_span:1
# ----------------------------------------------------------------------------------------
# 066.0672-big-integer-exponentiation.py
# ----------------------------------------------------------------------------------------
z = x ** n # assignment:Pow, assignment_lhs_identifier:z, assignment_rhs_atom:n, assignment_rhs_atom:x, binary_operator:Pow, flat_style, global_scope:z, imperative_style, loaded_variable:n, loaded_variable:x, node:Assign, node:BinOp, node:Name, one_liner_style, scope:z, single_assignment:z, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 067.1426-binomial-coefficient-n-choose-k.py
# ----------------------------------------------------------------------------------------
import math # functional_style (-> +2), import:math, import_module:math, node:Import, one_liner_style (-> +2), variety:1 (-> +2), whole_span:3 (-> +2)
def binom(n, k): # function:binom (-> +1), function_line_count:2 (-> +1), function_parameter:k, function_parameter:n, function_parameter_flavor:arg, function_returning_something:binom (-> +1), local_scope:k (-> +1), local_scope:n (-> +1), node:FunctionDef (-> +1), node:arg, pure_function:binom (-> +1), scope:k (-> +1), scope:n (-> +1)
return math.factorial(n) // math.factorial(k) // math.factorial(n - k) # argument:, argument:k, argument:n, binary_operator:FloorDiv, binary_operator:Sub, loaded_variable:k, loaded_variable:math, loaded_variable:n, member_call_method:factorial, node:Attribute, node:BinOp, node:Call, node:Name, node:Return, return
# ----------------------------------------------------------------------------------------
# 068.2271-create-a-bitset.py
# ----------------------------------------------------------------------------------------
from __future__ import division # flat_style (-> +2), global_scope:x (-> +2), imperative_style (-> +2), import:__future__:division, import_module:__future__, import_name:division, node:ImportFrom, one_liner_style (-> +2), scope:x (-> +2), variety:2 (-> +2), whole_span:3 (-> +2)
import math # import:math, import_module:math, node:Import
x = bytearray(int(math.ceil(n / 8.0))) # argument:, assignment:bytearray, assignment_lhs_identifier:x, assignment_rhs_atom:8.0, assignment_rhs_atom:math, assignment_rhs_atom:n, binary_operator:Div, composition, external_free_call:bytearray, external_free_call:int, free_call:bytearray, free_call:int, literal:8.0, loaded_variable:math, loaded_variable:n, magic_number:8.0, member_call_method:ceil, node:Assign, node:Attribute, node:BinOp, node:Call, node:Name, node:Num, single_assignment:x
# ----------------------------------------------------------------------------------------
# 069.1086-seed-random-generator.py
# ----------------------------------------------------------------------------------------
import random # flat_style (-> +1), global_scope:rand (-> +1), imperative_style (-> +1), import:random, import_module:random, node:Import, one_liner_style (-> +1), scope:rand (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
rand = random.Random(s) # argument:s, assignment:Random, assignment_lhs_identifier:rand, assignment_rhs_atom:random, assignment_rhs_atom:s, loaded_variable:random, loaded_variable:s, member_call_method:Random, node:Assign, node:Attribute, node:Call, node:Name, single_assignment:rand
# ----------------------------------------------------------------------------------------
# 070.1087-use-clock-as-random-generator-seed.py
# ----------------------------------------------------------------------------------------
import random # flat_style (-> +1), global_scope:rand (-> +1), imperative_style (-> +1), import:random, import_module:random, node:Import, one_liner_style (-> +1), scope:rand (-> +1), variety:2 (-> +1), whole_span:2 (-> +1)
rand = random.Random() # assignment:Random, assignment_lhs_identifier:rand, assignment_rhs_atom:random, loaded_variable:random, member_call_method:Random, node:Assign, node:Attribute, node:Call, node:Name, single_assignment:rand
# ----------------------------------------------------------------------------------------
# 071.0379-echo-program-implementation.py
# ----------------------------------------------------------------------------------------
import sys # flat_style (-> +1), imperative_style (-> +1), import:sys, import_module:sys, node:Import, one_liner_style (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
print(" ".join(sys.argv[1:])) # argument:, composition, external_free_call:print, free_call:print, free_call_without_result:print, literal:1, literal:Str, loaded_variable:sys, member_call_method:join, node:Attribute, node:Call, node:Expr, node:Name, node:Num, node:Str, node:Subscript, slice:1::, slice_lower:1, slice_step:, slice_upper:, value_attr:argv
# ----------------------------------------------------------------------------------------
# 073.0673-create-a-factory.py
# ----------------------------------------------------------------------------------------
def fact(a_class, str_): # function:fact (-> +2), function_line_count:3 (-> +2), function_parameter:a_class, function_parameter:str_, function_parameter_flavor:arg, function_returning_something:fact (-> +2), functional_style (-> +2), higher_order_function:a_class (-> +2), local_scope:a_class (-> +2), local_scope:str_ (-> +2), node:FunctionDef (-> +2), node:arg, pure_function:fact (-> +2), scope:a_class (-> +2), scope:str_ (-> +2), variety:1 (-> +2), whole_span:3 (-> +2)
if issubclass(a_class, Parent): # argument:Parent, argument:a_class, external_free_call:issubclass, free_call:issubclass, if (-> +1), if_test_atom:Parent, if_test_atom:a_class, if_without_else (-> +1), loaded_variable:Parent, loaded_variable:a_class, node:Call, node:If (-> +1), node:Name
return a_class(str_) # argument:str_, external_free_call:a_class, free_call:a_class, free_tail_call:a_class, if_then_branch, loaded_variable:str_, node:Call, node:Name, node:Return, return
# ----------------------------------------------------------------------------------------
# 074.0674-compute-gcd.py
# ----------------------------------------------------------------------------------------
from fractions import gcd # flat_style (-> +1), global_scope:x (-> +1), imperative_style (-> +1), import:fractions:gcd, import_module:fractions, import_name:gcd, node:ImportFrom, one_liner_style (-> +1), scope:x (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
x = gcd(a, b) # argument:a, argument:b, assignment:gcd, assignment_lhs_identifier:x, assignment_rhs_atom:a, assignment_rhs_atom:b, external_free_call:gcd, free_call:gcd, loaded_variable:a, loaded_variable:b, node:Assign, node:Call, node:Name, single_assignment:x
# ----------------------------------------------------------------------------------------
# 075.0675-compute-lcm.py
# ----------------------------------------------------------------------------------------
from fractions import gcd # flat_style (-> +1), global_scope:x (-> +1), imperative_style (-> +1), import:fractions:gcd, import_module:fractions, import_name:gcd, node:ImportFrom, one_liner_style (-> +1), scope:x (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
x = (a * b) // gcd(a, b) # argument:a, argument:b, assignment:FloorDiv, assignment_lhs_identifier:x, assignment_rhs_atom:a, assignment_rhs_atom:b, binary_operator:FloorDiv, binary_operator:Mult, external_free_call:gcd, free_call:gcd, loaded_variable:a, loaded_variable:b, multiplication_operator, node:Assign, node:BinOp, node:Call, node:Name, single_assignment:x
# ----------------------------------------------------------------------------------------
# 076.1083-binary-digits-from-an-integer.py
# ----------------------------------------------------------------------------------------
s = "{:b}".format(x) # argument:x, assignment:format, assignment_lhs_identifier:s, assignment_rhs_atom:x, flat_style, global_scope:s, imperative_style, literal:Str, loaded_variable:x, member_call_method:format, node:Assign, node:Attribute, node:Call, node:Name, node:Str, one_liner_style, scope:s, single_assignment:s, variety:1, whole_span:1
# ----------------------------------------------------------------------------------------
# 077.1093-complex-number.py
# ----------------------------------------------------------------------------------------
x = 3j - 2 # assignment:Sub, assignment_lhs_identifier:x, assignment_rhs_atom:2, assignment_rhs_atom:3j, binary_operator:Sub, flat_style (-> +1), global_scope:x (-> +1), global_scope:y (-> +1), imperative_style (-> +1), literal:2, literal:3j, node:Assign, node:BinOp, node:Name, node:Num, scope:x (-> +1), scope:y (-> +1), single_assignment:x, variety:1 (-> +1), whole_span:2 (-> +1)
y = x * 1j # assignment:Mult, assignment_lhs_identifier:y, assignment_rhs_atom:1j, assignment_rhs_atom:x, binary_operator:Mult, literal:1j, loaded_variable:x, multiplication_operator, node:Assign, node:BinOp, node:Name, node:Num, single_assignment:y
# ----------------------------------------------------------------------------------------
# 078.1089-do-while-loop.py
# ----------------------------------------------------------------------------------------
while True: # imperative_style (-> +3), infinite_while (-> +3), literal:True, loop:while (-> +3), loop_with_break:while (-> +3), loop_with_early_exit:while:break (-> +3), node:NameConstant, node:While (-> +3), variety:4 (-> +3), whole_span:4 (-> +3)
do_something() # external_free_call:do_something, free_call:do_something, free_call_no_arguments:do_something, free_call_without_result:do_something, node:Call, node:Expr, node:Name
if not c: # if (-> +1), if_test_atom:c, if_without_else (-> +1), loaded_variable:c, node:If (-> +1), node:Name, node:UnaryOp, unary_operator:Not
break # if_then_branch, node:Break
# ----------------------------------------------------------------------------------------
# 079.1090-convert-integer-to-floating-point-number.py
# ----------------------------------------------------------------------------------------
y = float(x) # argument:x, assignment:float, assignment_lhs_identifier:y, assignment_rhs_atom:x, external_free_call:float, flat_style, free_call:float, global_scope:y, imperative_style, loaded_variable:x, node:Assign, node:Call, node:Name, one_liner_style, scope:y, single_assignment:y, variety:1, whole_span:1
# ----------------------------------------------------------------------------------------
# 080.1092-truncate-floating-point-number-to-integer.py
# ----------------------------------------------------------------------------------------
y = int(x) # argument:x, assignment:int, assignment_lhs_identifier:y, assignment_rhs_atom:x, external_free_call:int, flat_style, free_call:int, global_scope:y, imperative_style, loaded_variable:x, node:Assign, node:Call, node:Name, one_liner_style, scope:y, single_assignment:y, variety:1, whole_span:1
# ----------------------------------------------------------------------------------------
# 081.2270-round-floating-point-number-to-integer.py
# ----------------------------------------------------------------------------------------
y = int(x + 0.5) # addition_operator, argument:, assignment:int, assignment_lhs_identifier:y, assignment_rhs_atom:0.5, assignment_rhs_atom:x, binary_operator:Add, external_free_call:int, flat_style, free_call:int, global_scope:y, imperative_style, literal:0.5, loaded_variable:x, magic_number:0.5, node:Assign, node:BinOp, node:Call, node:Name, node:Num, one_liner_style, scope:y, single_assignment:y, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 082.1096-count-substring-occurrences.py
# ----------------------------------------------------------------------------------------
count = s.count(t) # argument:t, assignment:count, assignment_lhs_identifier:count, assignment_rhs_atom:s, assignment_rhs_atom:t, flat_style, global_scope:count, imperative_style, loaded_variable:s, loaded_variable:t, member_call_method:count, node:Assign, node:Attribute, node:Call, node:Name, one_liner_style, scope:count, single_assignment:count, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 083.1805-regex-with-character-repetition.py
# ----------------------------------------------------------------------------------------
import re # flat_style (-> +1), global_scope:r (-> +1), imperative_style (-> +1), import:re, import_module:re, node:Import, one_liner_style (-> +1), scope:r (-> +1), variety:2 (-> +1), whole_span:2 (-> +1)
r = re.compile(r"htt+p") # argument:, assignment:compile, assignment_lhs_identifier:r, assignment_rhs_atom:re, literal:Str, loaded_variable:re, member_call_method:compile, node:Assign, node:Attribute, node:Call, node:Name, node:Str, single_assignment:r
# ----------------------------------------------------------------------------------------
# 084.1940-count-bits-set-in-integer-binary-representation.py
# ----------------------------------------------------------------------------------------
c = bin(i).count("1") # argument:, argument:i, assignment:count, assignment_lhs_identifier:c, assignment_rhs_atom:i, external_free_call:bin, flat_style, free_call:bin, global_scope:c, imperative_style, literal:Str, loaded_variable:i, member_call_method:count, node:Assign, node:Attribute, node:Call, node:Name, node:Str, one_liner_style, scope:c, single_assignment:c, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 085.1003-check-if-integer-addition-will-overflow.py
# ----------------------------------------------------------------------------------------
def adding_will_overflow(x, y): # function:adding_will_overflow (-> +1), function_line_count:2 (-> +1), function_parameter:x, function_parameter:y, function_parameter_flavor:arg, function_returning_something:adding_will_overflow (-> +1), functional_style (-> +1), local_scope:x (-> +1), local_scope:y (-> +1), node:FunctionDef (-> +1), node:arg, one_liner_style (-> +1), pure_function:adding_will_overflow (-> +1), scope:x (-> +1), scope:y (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
return False # literal:False, node:NameConstant, node:Return, return:False
# ----------------------------------------------------------------------------------------
# 086.1004-check-if-integer-multiplication-will-overflow.py
# ----------------------------------------------------------------------------------------
def multiplyWillOverflow(x, y): # function:multiplyWillOverflow (-> +1), function_line_count:2 (-> +1), function_parameter:x, function_parameter:y, function_parameter_flavor:arg, function_returning_something:multiplyWillOverflow (-> +1), functional_style (-> +1), local_scope:x (-> +1), local_scope:y (-> +1), node:FunctionDef (-> +1), node:arg, one_liner_style (-> +1), pure_function:multiplyWillOverflow (-> +1), scope:x (-> +1), scope:y (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
return False # literal:False, node:NameConstant, node:Return, return:False
# ----------------------------------------------------------------------------------------
# 087.1139-stop-program.py
# ----------------------------------------------------------------------------------------
import sys # flat_style (-> +1), imperative_style (-> +1), import:sys, import_module:sys, node:Import, one_liner_style (-> +1), variety:2 (-> +1), whole_span:2 (-> +1)
sys.exit(1) # argument:1, literal:1, loaded_variable:sys, member_call:sys:exit, member_call_method:exit, member_call_object:sys, node:Attribute, node:Call, node:Expr, node:Name, node:Num
# ----------------------------------------------------------------------------------------
# 088.2143-allocate-1m-bytes.py
# ----------------------------------------------------------------------------------------
buf = bytearray(1000000) # argument:1000000, assignment:bytearray, assignment_lhs_identifier:buf, assignment_rhs_atom:1000000, external_free_call:bytearray, flat_style, free_call:bytearray, global_scope:buf, imperative_style, literal:1000000, magic_number:1000000, node:Assign, node:Call, node:Name, node:Num, one_liner_style, scope:buf, single_assignment:buf, variety:1, whole_span:1
# ----------------------------------------------------------------------------------------
# 089.1097-handle-invalid-argument.py
# ----------------------------------------------------------------------------------------
raise ValueError("x is invalid") # argument:, external_free_call:ValueError, flat_style, free_call:ValueError, imperative_style, literal:Str, node:Call, node:Name, node:Raise, node:Str, one_liner_style, raise:ValueError, variety:1, whole_span:1
# ----------------------------------------------------------------------------------------
# 090.1099-read-only-outside.py
# ----------------------------------------------------------------------------------------
class Foo(object): # class:Foo (-> +5), class_method_count:2 (-> +5), loaded_variable:object, node:ClassDef (-> +5), node:Name, object_oriented_style (-> +5), variety:4 (-> +5), whole_span:6 (-> +5)
def __init__(self): # function:__init__ (-> +1), function_line_count:2 (-> +1), function_parameter:self, function_parameter_flavor:arg, function_returning_nothing:__init__ (-> +1), instance_method:__init__ (-> +1), local_scope:self (-> +1), method:__init__ (-> +1), node:FunctionDef (-> +1), node:arg, scope:self (-> +1)
self._x = 0 # assignment:0, assignment_lhs_identifier:self, assignment_rhs_atom:0, literal:0, loaded_variable:self, node:Assign, node:Attribute, node:Name, node:Num
@property # function_decorator:property (-> +2), loaded_variable:property, node:Name
def x(self): # decorated_function:x (-> +1), function:x (-> +1), function_line_count:2 (-> +1), function_parameter:self, function_parameter_flavor:arg, function_returning_something:x (-> +1), instance_method:x (-> +1), local_scope:self (-> +1), method:x (-> +1), node:FunctionDef (-> +1), node:arg, scope:self (-> +1)
return self._x # loaded_variable:self, node:Attribute, node:Name, node:Return, return, value_attr:_x
# ----------------------------------------------------------------------------------------
# 091.1098-load-json-file-into-struct.py
# ----------------------------------------------------------------------------------------
import json # flat_style (-> +2), global_scope:x (-> +2), imperative_style (-> +2), import:json, import_module:json, node:Import, scope:x (-> +2), variety:2 (-> +2), whole_span:3 (-> +2)
with open("data.json", "r") as input: # argument:, external_free_call:open, free_call:open, literal:Str, node:Call, node:Name, node:Str, node:With (-> +1)
x = json.load(input) # argument:input, assignment:load, assignment_lhs_identifier:x, assignment_rhs_atom:input, assignment_rhs_atom:json, loaded_variable:input, loaded_variable:json, member_call_method:load, node:Assign, node:Attribute, node:Call, node:Name, single_assignment:x
# ----------------------------------------------------------------------------------------
# 092.1100-save-object-into-json-file.py
# ----------------------------------------------------------------------------------------
import json # flat_style (-> +2), imperative_style (-> +2), import:json, import_module:json, node:Import, variety:2 (-> +2), whole_span:3 (-> +2)
with open("data.json", "w") as output: # argument:, external_free_call:open, free_call:open, literal:Str, node:Call, node:Name, node:Str, node:With (-> +1)
json.dump(x, output) # argument:output, argument:x, loaded_variable:json, loaded_variable:output, loaded_variable:x, member_call:json:dump, member_call_method:dump, member_call_object:json, node:Attribute, node:Call, node:Expr, node:Name
# ----------------------------------------------------------------------------------------
# 093.1082-pass-a-runnable-procedure-as-parameter.py
# ----------------------------------------------------------------------------------------
from __future__ import print_function # functional_style (-> +2), import:__future__:print_function, import_module:__future__, import_name:print_function, node:ImportFrom, one_liner_style (-> +2), variety:3 (-> +2), whole_span:3 (-> +2)
def control(f): # function:control (-> +1), function_line_count:2 (-> +1), function_parameter:f, function_parameter_flavor:arg, function_returning_something:control (-> +1), higher_order_function:f (-> +1), local_scope:f (-> +1), node:FunctionDef (-> +1), node:arg, pure_function:control (-> +1), scope:f (-> +1)
return f() # external_free_call:f, free_call:f, free_call_no_arguments:f, free_tail_call:f, node:Call, node:Name, node:Return, return
# ----------------------------------------------------------------------------------------
# 094.1101-print-type-of-variable.py
# ----------------------------------------------------------------------------------------
print(type(x)) # argument:, argument:x, composition, external_free_call:print, external_free_call:type, flat_style, free_call:print, free_call:type, free_call_without_result:print, imperative_style, loaded_variable:x, node:Call, node:Expr, node:Name, one_liner_style, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 094.1864-print-type-of-variable.py
# ----------------------------------------------------------------------------------------
print(x.__class__) # argument:, external_free_call:print, flat_style, free_call:print, free_call_without_result:print, imperative_style, loaded_variable:x, node:Attribute, node:Call, node:Expr, node:Name, one_liner_style, variety:1, whole_span:1
# ----------------------------------------------------------------------------------------
# 095.2140-get-file-size.py
# ----------------------------------------------------------------------------------------
import os # flat_style (-> +1), global_scope:x (-> +1), imperative_style (-> +1), import:os, import_module:os, node:Import, one_liner_style (-> +1), scope:x (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
x = os.path.getsize(path) # argument:path, assignment:getsize, assignment_lhs_identifier:x, assignment_rhs_atom:os, assignment_rhs_atom:path, loaded_variable:os, loaded_variable:path, member_call_method:getsize, node:Assign, node:Attribute, node:Call, node:Name, single_assignment:x, value_attr:path
# ----------------------------------------------------------------------------------------
# 096.1094-check-string-prefix.py
# ----------------------------------------------------------------------------------------
b = s.startswith(prefix) # argument:prefix, assignment:startswith, assignment_lhs_identifier:b, assignment_rhs_atom:prefix, assignment_rhs_atom:s, flat_style, global_scope:b, imperative_style, loaded_variable:prefix, loaded_variable:s, member_call_method:startswith, node:Assign, node:Attribute, node:Call, node:Name, one_liner_style, scope:b, single_assignment:b, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 097.1095-check-string-suffix.py
# ----------------------------------------------------------------------------------------
b = s.endswith(suffix) # argument:suffix, assignment:endswith, assignment_lhs_identifier:b, assignment_rhs_atom:s, assignment_rhs_atom:suffix, flat_style, global_scope:b, imperative_style, loaded_variable:s, loaded_variable:suffix, member_call_method:endswith, node:Assign, node:Attribute, node:Call, node:Name, one_liner_style, scope:b, single_assignment:b, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 098.2142-epoch-seconds-to-date-object.py
# ----------------------------------------------------------------------------------------
import datetime # flat_style (-> +1), global_scope:d (-> +1), imperative_style (-> +1), import:datetime, import_module:datetime, node:Import, one_liner_style (-> +1), scope:d (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
d = datetime.date.fromtimestamp(ts) # argument:ts, assignment:fromtimestamp, assignment_lhs_identifier:d, assignment_rhs_atom:datetime, assignment_rhs_atom:ts, loaded_variable:datetime, loaded_variable:ts, member_call_method:fromtimestamp, node:Assign, node:Attribute, node:Call, node:Name, single_assignment:d, value_attr:date
# ----------------------------------------------------------------------------------------
# 099.1429-format-date-yyyy-mm-dd.py
# ----------------------------------------------------------------------------------------
from datetime import date # flat_style (-> +2), global_scope:d (-> +2), global_scope:x (-> +2), imperative_style (-> +2), import:datetime:date, import_module:datetime, import_name:date, node:ImportFrom, scope:d (-> +2), scope:x (-> +2), variety:1 (-> +2), whole_span:3 (-> +2)
d = date(2016, 9, 28) # argument:2016, argument:28, argument:9, assignment:date, assignment_lhs_identifier:d, assignment_rhs_atom:2016, assignment_rhs_atom:28, assignment_rhs_atom:9, external_free_call:date, free_call:date, literal:2016, literal:28, literal:9, magic_number:2016, magic_number:28, magic_number:9, node:Assign, node:Call, node:Name, node:Num, single_assignment:d
x = d.strftime("%Y-%m-%d") # argument:, assignment:strftime, assignment_lhs_identifier:x, assignment_rhs_atom:d, literal:Str, loaded_variable:d, member_call_method:strftime, node:Assign, node:Attribute, node:Call, node:Name, node:Str, single_assignment:x
# ----------------------------------------------------------------------------------------
# 099.2693-format-date-yyyy-mm-dd.py
# ----------------------------------------------------------------------------------------
from datetime import date # flat_style (-> +2), global_scope:d (-> +2), global_scope:x (-> +2), imperative_style (-> +2), import:datetime:date, import_module:datetime, import_name:date, node:ImportFrom, scope:d (-> +2), scope:x (-> +2), variety:1 (-> +2), whole_span:3 (-> +2)
d = date.today() # assignment:today, assignment_lhs_identifier:d, assignment_rhs_atom:date, loaded_variable:date, member_call_method:today, node:Assign, node:Attribute, node:Call, node:Name, single_assignment:d
x = d.isoformat() # assignment:isoformat, assignment_lhs_identifier:x, assignment_rhs_atom:d, loaded_variable:d, member_call_method:isoformat, node:Assign, node:Attribute, node:Call, node:Name, single_assignment:x
# ----------------------------------------------------------------------------------------
# 100.1142-sort-by-a-comparator.py
# ----------------------------------------------------------------------------------------
items.sort(c) # argument:c, flat_style, imperative_style, loaded_variable:c, loaded_variable:items, member_call:items:sort, member_call_method:sort, member_call_object:items, node:Attribute, node:Call, node:Expr, node:Name, one_liner_style, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 101.2172-load-from-http-get-request-into-a-string.py
# ----------------------------------------------------------------------------------------
import urllib.request # flat_style (-> +2), global_scope:s (-> +2), imperative_style (-> +2), import:urllib.request, import_module:urllib.request, node:Import, scope:s (-> +2), variety:2 (-> +2), whole_span:3 (-> +2)
with urllib.request.urlopen(u) as f: # argument:u, loaded_variable:u, loaded_variable:urllib, member_call_method:urlopen, node:Attribute, node:Call, node:Name, node:With (-> +1), value_attr:request
s = f.read() # assignment:read, assignment_lhs_identifier:s, assignment_rhs_atom:f, loaded_variable:f, member_call_method:read, node:Assign, node:Attribute, node:Call, node:Name, single_assignment:s
# ----------------------------------------------------------------------------------------
# 102.2173-load-from-http-get-request-into-a-file.py
# ----------------------------------------------------------------------------------------
import urllib # flat_style (-> +1), global_scope:filename (-> +1), global_scope:headers (-> +1), imperative_style (-> +1), import:urllib, import_module:urllib, node:Import, one_liner_style (-> +1), scope:filename (-> +1), scope:headers (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
filename, headers = urllib.request.urlretrieve(u, "result.txt") # argument:, argument:u, assignment:urlretrieve, assignment_lhs_identifier:filename, assignment_lhs_identifier:headers, assignment_rhs_atom:u, assignment_rhs_atom:urllib, literal:Str, literal:Tuple, loaded_variable:u, loaded_variable:urllib, member_call_method:urlretrieve, node:Assign, node:Attribute, node:Call, node:Name, node:Str, node:Tuple, parallel_assignment:2, value_attr:request
# ----------------------------------------------------------------------------------------
# 103.2276-load-xml-file-into-struct.py
# ----------------------------------------------------------------------------------------
import lxml.etree # flat_style (-> +1), global_scope:x (-> +1), imperative_style (-> +1), import:lxml.etree, import_module:lxml.etree, node:Import, one_liner_style (-> +1), scope:x (-> +1), variety:2 (-> +1), whole_span:2 (-> +1)
x = lxml.etree.parse("data.xml") # argument:, assignment:parse, assignment_lhs_identifier:x, assignment_rhs_atom:lxml, literal:Str, loaded_variable:lxml, member_call_method:parse, node:Assign, node:Attribute, node:Call, node:Name, node:Str, single_assignment:x, value_attr:etree
# ----------------------------------------------------------------------------------------
# 104.3264-save-object-into-xml-file.py
# ----------------------------------------------------------------------------------------
import pyxser as pyx # global_scope:a (-> +11), global_scope:b (-> +11), global_scope:c (-> +11), global_scope:ser (-> +11), global_scope:tst (-> +11), import:pyxser, import_module:pyxser, node:Import, object_oriented_style (-> +11), scope:a (-> +11), scope:b (-> +11), scope:c (-> +11), scope:ser (-> +11), scope:tst (-> +11), variety:3 (-> +11), whole_span:12 (-> +11)
class TestClass(object): # class:TestClass (-> +7), class_method_count:1 (-> +7), loaded_variable:object, node:ClassDef (-> +7), node:Name
a = None # assignment:None, assignment_lhs_identifier:a, assignment_rhs_atom:None, literal:None, node:Assign, node:Name, node:NameConstant, single_assignment:a
b = None # assignment:None, assignment_lhs_identifier:b, assignment_rhs_atom:None, literal:None, node:Assign, node:Name, node:NameConstant, single_assignment:b
c = None # assignment:None, assignment_lhs_identifier:c, assignment_rhs_atom:None, literal:None, node:Assign, node:Name, node:NameConstant, single_assignment:c
def __init__(self, a, b, c): # function:__init__ (-> +3), function_line_count:4 (-> +3), function_parameter:a, function_parameter:b, function_parameter:c, function_parameter:self, function_parameter_flavor:arg, function_returning_nothing:__init__ (-> +3), instance_method:__init__ (-> +3), local_scope:a (-> +3), local_scope:b (-> +3), local_scope:c (-> +3), local_scope:self (-> +3), method:__init__ (-> +3), node:FunctionDef (-> +3), node:arg, scope:a (-> +3), scope:b (-> +3), scope:c (-> +3), scope:self (-> +3), shadowing_scope:a (-> +3), shadowing_scope:b (-> +3), shadowing_scope:c (-> +3)
self.a = a # assignment, assignment_lhs_identifier:self, assignment_rhs_atom:a, loaded_variable:a, loaded_variable:self, node:Assign, node:Attribute, node:Name
self.b = b # assignment, assignment_lhs_identifier:self, assignment_rhs_atom:b, loaded_variable:b, loaded_variable:self, node:Assign, node:Attribute, node:Name
self.c = c # assignment, assignment_lhs_identifier:self, assignment_rhs_atom:c, loaded_variable:c, loaded_variable:self, node:Assign, node:Attribute, node:Name
tst = TestClass("var_a", "var_b", "var_c") # argument:, assignment:TestClass, assignment_lhs_identifier:tst, external_free_call:TestClass, free_call:TestClass, literal:Str, node:Assign, node:Call, node:Name, node:Str, single_assignment:tst
ser = pyx.serialize(obj=tst, enc="utf-8") # argument:, argument:tst, assignment:serialize, assignment_lhs_identifier:ser, assignment_rhs_atom:pyx, assignment_rhs_atom:tst, keyword_argument:enc, keyword_argument:obj, literal:Str, loaded_variable:pyx, loaded_variable:tst, member_call_method:serialize, node:Assign, node:Attribute, node:Call, node:Name, node:Str, single_assignment:ser
print(ser) # argument:ser, external_free_call:print, free_call:print, free_call_without_result:print, loaded_variable:ser, node:Call, node:Expr, node:Name
# ----------------------------------------------------------------------------------------
# 105.1804-current-executable-name.py
# ----------------------------------------------------------------------------------------
import sys # flat_style (-> +1), global_scope:s (-> +1), imperative_style (-> +1), import:sys, import_module:sys, node:Import, one_liner_style (-> +1), scope:s (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
s = sys.argv[0] # assignment, assignment_lhs_identifier:s, assignment_rhs_atom:0, assignment_rhs_atom:sys, index:0, literal:0, loaded_variable:sys, node:Assign, node:Attribute, node:Name, node:Num, node:Subscript, single_assignment:s, value_attr:argv
# ----------------------------------------------------------------------------------------
# 106.2039-get-program-working-directory.py
# ----------------------------------------------------------------------------------------
import os # flat_style (-> +1), global_scope:dir (-> +1), imperative_style (-> +1), import:os, import_module:os, node:Import, one_liner_style (-> +1), scope:dir (-> +1), variety:2 (-> +1), whole_span:2 (-> +1)
dir = os.getcwd() # assignment:getcwd, assignment_lhs_identifier:dir, assignment_rhs_atom:os, loaded_variable:os, member_call_method:getcwd, node:Assign, node:Attribute, node:Call, node:Name, single_assignment:dir
# ----------------------------------------------------------------------------------------
# 107.2139-get-folder-containing-current-program.py
# ----------------------------------------------------------------------------------------
import os # flat_style (-> +1), global_scope:dir (-> +1), imperative_style (-> +1), import:os, import_module:os, node:Import, one_liner_style (-> +1), scope:dir (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
dir = os.path.dirname(os.path.abspath(__file__)) # argument:, argument:__file__, assignment:dirname, assignment_lhs_identifier:dir, assignment_rhs_atom:__file__, assignment_rhs_atom:os, composition, loaded_variable:__file__, loaded_variable:os, member_call_method:abspath, member_call_method:dirname, node:Assign, node:Attribute, node:Call, node:Name, single_assignment:dir, value_attr:path
# ----------------------------------------------------------------------------------------
# 108.1291-determine-if-variable-name-is-defined.py
# ----------------------------------------------------------------------------------------
if "x" in locals(): # comparison_operator:In, external_free_call:locals, free_call:locals, free_call_no_arguments:locals, if (-> +1), if_without_else (-> +1), imperative_style (-> +1), literal:Str, node:Call, node:Compare, node:If (-> +1), node:Name, node:Str, variety:1 (-> +1), whole_span:2 (-> +1)
print(x) # argument:x, external_free_call:print, free_call:print, free_call_without_result:print, if_then_branch, loaded_variable:x, node:Call, node:Expr, node:Name
# ----------------------------------------------------------------------------------------
# 109.2280-number-of-bytes-of-a-type.py
# ----------------------------------------------------------------------------------------
import pympler.asizeof # flat_style (-> +1), global_scope:n (-> +1), imperative_style (-> +1), import:pympler.asizeof, import_module:pympler.asizeof, node:Import, one_liner_style (-> +1), scope:n (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
n = pympler.asizeof.asizeof(t) # argument:t, assignment:asizeof, assignment_lhs_identifier:n, assignment_rhs_atom:pympler, assignment_rhs_atom:t, loaded_variable:pympler, loaded_variable:t, member_call_method:asizeof, node:Assign, node:Attribute, node:Call, node:Name, single_assignment:n, value_attr:asizeof
# ----------------------------------------------------------------------------------------
# 110.1455-check-if-string-is-blank.py
# ----------------------------------------------------------------------------------------
blank = s.strip() == "" # assignment, assignment_lhs_identifier:blank, assignment_rhs_atom:s, comparison_operator:Eq, empty_literal:Str, flat_style, global_scope:blank, imperative_style, literal:Str, loaded_variable:s, member_call_method:strip, node:Assign, node:Attribute, node:Call, node:Compare, node:Name, node:Str, one_liner_style, scope:blank, single_assignment:blank, variety:1, whole_span:1
# ----------------------------------------------------------------------------------------
# 111.2168-launch-other-program.py
# ----------------------------------------------------------------------------------------
import subprocess # flat_style (-> +1), imperative_style (-> +1), import:subprocess, import_module:subprocess, node:Import, one_liner_style (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
subprocess.call(["x", "a", "b"]) # argument:, literal:List, literal:Str, loaded_variable:subprocess, member_call:subprocess:call, member_call_method:call, member_call_object:subprocess, node:Attribute, node:Call, node:Expr, node:List, node:Name, node:Str
# ----------------------------------------------------------------------------------------
# 112.2144-iterate-over-map-entries-ordered-by-keys.py
# ----------------------------------------------------------------------------------------
for k in sorted(mymap): # argument:mymap, external_free_call:sorted, for:k (-> +1), free_call:sorted, global_scope:k (-> +1), imperative_style (-> +1), iteration_variable:k, loaded_variable:mymap, loop:for (-> +1), loop_with_late_exit:for (-> +1), node:Call, node:For (-> +1), node:Name, scope:k (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
print(mymap[k]) # argument:, external_free_call:print, free_call:print, free_call_without_result:print, index:k, loaded_variable:k, loaded_variable:mymap, node:Call, node:Expr, node:Name, node:Subscript
# ----------------------------------------------------------------------------------------
# 113.2157-iterate-over-map-entries-ordered-by-values.py
# ----------------------------------------------------------------------------------------
for x, k in sorted((x, k) for k, x in mymap.items()): # argument:, composition, comprehension:Generator, comprehension_for_count:1, external_free_call:sorted, for:k (-> +1), for:x (-> +1), free_call:sorted, global_scope:k (-> +1), global_scope:x (-> +1), imperative_style (-> +1), iteration_variable:k, iteration_variable:x, literal:Tuple, loaded_variable:k, loaded_variable:mymap, loaded_variable:x, local_scope:k, local_scope:x, loop:for (-> +1), loop_with_late_exit:for (-> +1), member_call_method:items, node:Attribute, node:Call, node:For (-> +1), node:GeneratorExp, node:Name, node:Tuple, scope:k, scope:k (-> +1), scope:x, scope:x (-> +1), shadowing_scope:k, shadowing_scope:x, variety:1 (-> +1), whole_span:2 (-> +1)
print(k, x) # argument:k, argument:x, external_free_call:print, free_call:print, free_call_without_result:print, loaded_variable:k, loaded_variable:x, node:Call, node:Expr, node:Name
# ----------------------------------------------------------------------------------------
# 114.2273-test-deep-equality.py
# ----------------------------------------------------------------------------------------
b = x == y # assignment, assignment_lhs_identifier:b, assignment_rhs_atom:x, assignment_rhs_atom:y, comparison_operator:Eq, flat_style, global_scope:b, imperative_style, loaded_variable:x, loaded_variable:y, node:Assign, node:Compare, node:Name, one_liner_style, scope:b, single_assignment:b, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 115.2138-compare-dates.py
# ----------------------------------------------------------------------------------------
import datetime # flat_style (-> +1), global_scope:b (-> +1), imperative_style (-> +1), import:datetime, import_module:datetime, node:Import, one_liner_style (-> +1), scope:b (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
b = d1 < d2 # assignment, assignment_lhs_identifier:b, assignment_rhs_atom:d1, assignment_rhs_atom:d2, comparison_operator:Lt, loaded_variable:d1, loaded_variable:d2, node:Assign, node:Compare, node:Name, single_assignment:b
# ----------------------------------------------------------------------------------------
# 116.1257-remove-occurrences-of-word-from-string.py
# ----------------------------------------------------------------------------------------
s2 = s1.replace(w, "") # argument:, argument:w, assignment:replace, assignment_lhs_identifier:s2, assignment_rhs_atom:s1, assignment_rhs_atom:w, empty_literal:Str, flat_style, global_scope:s2, imperative_style, literal:Str, loaded_variable:s1, loaded_variable:w, member_call_method:replace, node:Assign, node:Attribute, node:Call, node:Name, node:Str, one_liner_style, scope:s2, single_assignment:s2, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 117.1297-get-list-size.py
# ----------------------------------------------------------------------------------------
n = len(x) # argument:x, assignment:len, assignment_lhs_identifier:n, assignment_rhs_atom:x, external_free_call:len, flat_style, free_call:len, global_scope:n, imperative_style, loaded_variable:x, node:Assign, node:Call, node:Name, one_liner_style, scope:n, single_assignment:n, variety:1, whole_span:1
# ----------------------------------------------------------------------------------------
# 118.1254-list-to-set.py
# ----------------------------------------------------------------------------------------
y = set(x) # argument:x, assignment:set, assignment_lhs_identifier:y, assignment_rhs_atom:x, external_free_call:set, flat_style, free_call:set, global_scope:y, imperative_style, loaded_variable:x, node:Assign, node:Call, node:Name, one_liner_style, scope:y, single_assignment:y, variety:1, whole_span:1
# ----------------------------------------------------------------------------------------
# 118.3266-list-to-set.py
# ----------------------------------------------------------------------------------------
set(x) # argument:x, external_free_call:set, flat_style, free_call:set, free_call_without_result:set, imperative_style, loaded_variable:x, node:Call, node:Expr, node:Name, one_liner_style, variety:1, whole_span:1
# ----------------------------------------------------------------------------------------
# 119.1253-deduplicate-list.py
# ----------------------------------------------------------------------------------------
x = list(set(x)) # argument:, argument:x, assignment:list, assignment_lhs_identifier:x, assignment_rhs_atom:x, composition, external_free_call:list, external_free_call:set, flat_style, free_call:list, free_call:set, global_scope:x, imperative_style, loaded_variable:x, node:Assign, node:Call, node:Name, one_liner_style, scope:x, single_assignment:x, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 119.3263-deduplicate-list.py
# ----------------------------------------------------------------------------------------
elements = ["b", "a", "b", "c"] # assignment, assignment_lhs_identifier:elements, global_scope:elements (-> +7), global_scope:elements_unique (-> +7), global_scope:i (-> +7), global_scope:unique_set (-> +7), imperative_style (-> +7), literal:List, literal:Str, node:Assign, node:List, node:Name, node:Str, scope:elements (-> +7), scope:elements_unique (-> +7), scope:i (-> +7), scope:unique_set (-> +7), single_assignment:elements, variety:3 (-> +7), whole_span:8 (-> +7)
unique_set = set() # assignment:set, assignment_lhs_identifier:unique_set, external_free_call:set, free_call:set, free_call_no_arguments:set, node:Assign, node:Call, node:Name, single_assignment:unique_set
elements_unique = [] # assignment, assignment_lhs_identifier:elements_unique, empty_literal:List, literal:List, node:Assign, node:List, node:Name, single_assignment:elements_unique
for i in elements: # accumulate_elements:add (-> +3), accumulate_elements:append (-> +3), accumulate_some_elements:add (-> +3), accumulate_some_elements:append (-> +3), for:i (-> +3), for_each:i (-> +3), iteration_variable:i, loaded_variable:elements, loop:for (-> +3), loop_with_late_exit:for (-> +3), node:For (-> +3), node:Name
if i not in unique_set: # comparison_operator:NotIn, if (-> +2), if_test_atom:i, if_test_atom:unique_set, if_without_else (-> +2), loaded_variable:i, loaded_variable:unique_set, node:Compare, node:If (-> +2), node:Name
unique_set.add(i) # argument:i, if_then_branch (-> +1), loaded_variable:i, loaded_variable:unique_set, member_call:unique_set:add, member_call_method:add, member_call_object:unique_set, node:Attribute, node:Call, node:Expr, node:Name, update:unique_set:i, update_by_member_call:unique_set:i, update_by_member_call_with:add, update_with:add
elements_unique.append(i) # argument:i, loaded_variable:elements_unique, loaded_variable:i, member_call:elements_unique:append, member_call_method:append, member_call_object:elements_unique, node:Attribute, node:Call, node:Expr, node:Name, update:elements_unique:i, update_by_member_call:elements_unique:i, update_by_member_call_with:append, update_with:append
print(elements_unique) # argument:elements_unique, external_free_call:print, free_call:print, free_call_without_result:print, loaded_variable:elements_unique, node:Call, node:Expr, node:Name
# ----------------------------------------------------------------------------------------
# 120.1479-read-integer-from-stdin.py
# ----------------------------------------------------------------------------------------
input_var = int(raw_input("Input Prompting String: ")) # argument:, assignment:int, assignment_lhs_identifier:input_var, composition, external_free_call:int, external_free_call:raw_input, flat_style, free_call:int, free_call:raw_input, global_scope:input_var, imperative_style, literal:Str, node:Assign, node:Call, node:Name, node:Str, one_liner_style, scope:input_var, single_assignment:input_var, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 121.3029-udp-listen-and-read.py
# ----------------------------------------------------------------------------------------
import socket # global_scope:UDP_IP (-> +6), global_scope:addr (-> +6), global_scope:data (-> +6), global_scope:sock (-> +6), imperative_style (-> +6), import:socket, import_module:socket, node:Import, scope:UDP_IP (-> +6), scope:addr (-> +6), scope:data (-> +6), scope:sock (-> +6), variety:2 (-> +6), whole_span:7 (-> +6)
UDP_IP = "127.0.0.1" # assignment, assignment_lhs_identifier:UDP_IP, literal:Str, node:Assign, node:Name, node:Str, single_assignment:UDP_IP
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # argument:, assignment:socket, assignment_lhs_identifier:sock, assignment_rhs_atom:socket, loaded_variable:socket, member_call_method:socket, node:Assign, node:Attribute, node:Call, node:Name, single_assignment:sock
sock.bind((UDP_IP, p)) # argument:, literal:Tuple, loaded_variable:UDP_IP, loaded_variable:p, loaded_variable:sock, member_call:sock:bind, member_call_method:bind, member_call_object:sock, node:Attribute, node:Call, node:Expr, node:Name, node:Tuple
while True: # infinite_while (-> +2), literal:True, loop:while (-> +2), loop_with_late_exit:while (-> +2), node:NameConstant, node:While (-> +2)
data, addr = sock.recvfrom(1024) # argument:1024, assignment:recvfrom, assignment_lhs_identifier:addr, assignment_lhs_identifier:data, assignment_rhs_atom:1024, assignment_rhs_atom:sock, literal:1024, literal:Tuple, loaded_variable:sock, magic_number:1024, member_call_method:recvfrom, node:Assign, node:Attribute, node:Call, node:Name, node:Num, node:Tuple, parallel_assignment:2
print("received message:", data) # argument:, argument:data, external_free_call:print, free_call:print, free_call_without_result:print, literal:Str, loaded_variable:data, node:Call, node:Expr, node:Name, node:Str
# ----------------------------------------------------------------------------------------
# 122.1453-declare-enumeration.py
# ----------------------------------------------------------------------------------------
class Suit: # class:Suit (-> +1), global_scope:CLUBS (-> +1), global_scope:DIAMONDS (-> +1), global_scope:HEARTS (-> +1), global_scope:SPADES (-> +1), node:ClassDef (-> +1), object_oriented_style (-> +1), one_liner_style (-> +1), scope:CLUBS (-> +1), scope:DIAMONDS (-> +1), scope:HEARTS (-> +1), scope:SPADES (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
SPADES, HEARTS, DIAMONDS, CLUBS = range(4) # argument:4, assignment:range, assignment_lhs_identifier:CLUBS, assignment_lhs_identifier:DIAMONDS, assignment_lhs_identifier:HEARTS, assignment_lhs_identifier:SPADES, assignment_rhs_atom:4, external_free_call:range, free_call:range, literal:4, literal:Tuple, magic_number:4, node:Assign, node:Call, node:Name, node:Num, node:Tuple, parallel_assignment:4, range:4
# ----------------------------------------------------------------------------------------
# 122.1454-declare-enumeration.py
# ----------------------------------------------------------------------------------------
from enum import Enum # global_scope:CLUBS (-> +5), global_scope:DIAMONDS (-> +5), global_scope:HEARTS (-> +5), global_scope:SPADES (-> +5), import:enum:Enum, import_module:enum, import_name:Enum, node:ImportFrom, object_oriented_style (-> +5), scope:CLUBS (-> +5), scope:DIAMONDS (-> +5), scope:HEARTS (-> +5), scope:SPADES (-> +5), variety:2 (-> +5), whole_span:6 (-> +5)
class Suit(Enum): # class:Suit (-> +4), loaded_variable:Enum, node:ClassDef (-> +4), node:Name
SPADES = 1 # assignment:1, assignment_lhs_identifier:SPADES, assignment_rhs_atom:1, literal:1, node:Assign, node:Name, node:Num, single_assignment:SPADES
HEARTS = 2 # assignment:2, assignment_lhs_identifier:HEARTS, assignment_rhs_atom:2, literal:2, node:Assign, node:Name, node:Num, single_assignment:HEARTS
DIAMONDS = 3 # assignment:3, assignment_lhs_identifier:DIAMONDS, assignment_rhs_atom:3, literal:3, node:Assign, node:Name, node:Num, single_assignment:DIAMONDS
CLUBS = 4 # assignment:4, assignment_lhs_identifier:CLUBS, assignment_rhs_atom:4, literal:4, node:Assign, node:Name, node:Num, single_assignment:CLUBS
# ----------------------------------------------------------------------------------------
# 123.2146-assert-condition.py
# ----------------------------------------------------------------------------------------
assert isConsistent # flat_style, imperative_style, loaded_variable:isConsistent, node:Assert, node:Name, variety:1, whole_span:1
# ----------------------------------------------------------------------------------------
# 124.2152-binary-search-for-a-value-in-sorted-array.py
# ----------------------------------------------------------------------------------------
import bisect # import:bisect, import_module:bisect, node:Import, procedural_style (-> +3), variety:2 (-> +3), whole_span:4 (-> +3)
def binarySearch(a, x): # function:binarySearch (-> +2), function_line_count:3 (-> +2), function_parameter:a, function_parameter:x, function_parameter_flavor:arg, function_returning_something:binarySearch (-> +2), impure_function:binarySearch (-> +2), local_scope:a (-> +2), local_scope:i (-> +2), local_scope:x (-> +2), node:FunctionDef (-> +2), node:arg, scope:a (-> +2), scope:i (-> +2), scope:x (-> +2)
i = bisect.bisect_left(a, x) # argument:a, argument:x, assignment:bisect_left, assignment_lhs_identifier:i, assignment_rhs_atom:a, assignment_rhs_atom:bisect, assignment_rhs_atom:x, loaded_variable:a, loaded_variable:bisect, loaded_variable:x, member_call_method:bisect_left, node:Assign, node:Attribute, node:Call, node:Name, single_assignment:i
return i if i != len(a) and a[i] == x else -1 # argument:a, boolean_operator:And, comparison_operator:Eq, comparison_operator:NotEq, external_free_call:len, free_call:len, index:i, literal:-1, loaded_variable:a, loaded_variable:i, loaded_variable:x, node:BoolOp, node:Call, node:Compare, node:IfExp, node:Name, node:Num, node:Return, node:Subscript, return
# ----------------------------------------------------------------------------------------
# 125.2167-measure-function-call-duration.py
# ----------------------------------------------------------------------------------------
import time # flat_style (-> +4), global_scope:t1 (-> +4), global_scope:t2 (-> +4), imperative_style (-> +4), import:time, import_module:time, node:Import, scope:t1 (-> +4), scope:t2 (-> +4), variety:2 (-> +4), whole_span:5 (-> +4)
t1 = time.perf_counter() # assignment:perf_counter, assignment_lhs_identifier:t1, assignment_rhs_atom:time, loaded_variable:time, member_call_method:perf_counter, node:Assign, node:Attribute, node:Call, node:Name, single_assignment:t1
foo() # external_free_call:foo, free_call:foo, free_call_no_arguments:foo, free_call_without_result:foo, node:Call, node:Expr, node:Name
t2 = time.perf_counter() # assignment:perf_counter, assignment_lhs_identifier:t2, assignment_rhs_atom:time, loaded_variable:time, member_call_method:perf_counter, node:Assign, node:Attribute, node:Call, node:Name, single_assignment:t2
print("Seconds:", t2 - t1) # argument:, binary_operator:Sub, external_free_call:print, free_call:print, free_call_without_result:print, literal:Str, loaded_variable:t1, loaded_variable:t2, node:BinOp, node:Call, node:Expr, node:Name, node:Str
# ----------------------------------------------------------------------------------------
# 126.2137-multiple-return-values.py
# ----------------------------------------------------------------------------------------
def foo(): # function:foo (-> +1), function_line_count:2 (-> +1), function_returning_something:foo (-> +1), function_without_parameters:foo (-> +1), functional_style (-> +1), node:FunctionDef (-> +1), one_liner_style (-> +1), pure_function:foo (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
return "string", True # literal:Str, literal:True, literal:Tuple, node:NameConstant, node:Return, node:Str, node:Tuple, return
# ----------------------------------------------------------------------------------------
# 127.2274-source-code-inclusion.py
# ----------------------------------------------------------------------------------------
import imp # flat_style (-> +1), global_scope:foo (-> +1), imperative_style (-> +1), import:imp, import_module:imp, node:Import, one_liner_style (-> +1), scope:foo (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
foo = imp.load_module("foobody", "foobody.txt").foo # argument:, assignment, assignment_lhs_identifier:foo, assignment_rhs_atom:imp, literal:Str, loaded_variable:imp, member_call:imp:load_module, member_call_method:load_module, member_call_object:imp, node:Assign, node:Attribute, node:Call, node:Name, node:Str, single_assignment:foo
# ----------------------------------------------------------------------------------------
# 128.2085-breadth-first-traversing-of-a-tree.py
# ----------------------------------------------------------------------------------------
def BFS(f, root): # function:BFS (-> +8), function_line_count:9 (-> +8), function_parameter:f, function_parameter:root, function_parameter_flavor:arg, function_returning_nothing:BFS (-> +8), higher_order_function:f (-> +8), local_scope:Q (-> +8), local_scope:child (-> +8), local_scope:f (-> +8), local_scope:n (-> +8), local_scope:root (-> +8), node:FunctionDef (-> +8), node:arg, procedural_style (-> +8), scope:Q (-> +8), scope:child (-> +8), scope:f (-> +8), scope:n (-> +8), scope:root (-> +8), variety:4 (-> +8), whole_span:9 (-> +8)
Q = [root] # assignment, assignment_lhs_identifier:Q, assignment_rhs_atom:root, literal:List, loaded_variable:root, node:Assign, node:List, node:Name, single_assignment:Q
while Q: # loaded_variable:Q, loop:while (-> +6), loop_with_late_exit:while (-> +6), node:Name, node:While (-> +6)
n = Q.pop(0) # argument:0, assignment:pop, assignment_lhs_identifier:n, assignment_rhs_atom:0, assignment_rhs_atom:Q, literal:0, loaded_variable:Q, member_call_method:pop, node:Assign, node:Attribute, node:Call, node:Name, node:Num, single_assignment:n
f(n) # argument:n, external_free_call:f, free_call:f, free_call_without_result:f, loaded_variable:n, node:Call, node:Expr, node:Name
for child in n: # for:child (-> +3), for_each:child (-> +3), iteration_variable:child, loaded_variable:n, loop:for (-> +3), loop_with_late_exit:for (-> +3), node:For (-> +3), node:Name
if not n.discovered: # if (-> +2), if_test_atom:n, if_without_else (-> +2), loaded_variable:n, node:Attribute, node:If (-> +2), node:Name, node:UnaryOp, unary_operator:Not
n.discovered = True # assignment:True, assignment_lhs_identifier:n, assignment_rhs_atom:True, if_then_branch (-> +1), literal:True, loaded_variable:n, node:Assign, node:Attribute, node:Name, node:NameConstant
Q.append(n) # argument:n, loaded_variable:Q, loaded_variable:n, member_call:Q:append, member_call_method:append, member_call_object:Q, node:Attribute, node:Call, node:Expr, node:Name, update:Q:n, update_by_member_call:Q:n, update_by_member_call_with:append, update_with:append
# ----------------------------------------------------------------------------------------
# 129.2282-breadth-first-traversing-in-a-graph.py
# ----------------------------------------------------------------------------------------
from collections import deque # import:collections:deque, import_module:collections, import_name:deque, node:ImportFrom, procedural_style (-> +8), variety:4 (-> +8), whole_span:9 (-> +8)
def breadth_first(start, f): # function:breadth_first (-> +7), function_line_count:8 (-> +7), function_parameter:f, function_parameter:start, function_parameter_flavor:arg, function_returning_nothing:breadth_first (-> +7), higher_order_function:f (-> +7), local_scope:f (-> +7), local_scope:q (-> +7), local_scope:seen (-> +7), local_scope:start (-> +7), local_scope:vertex (-> +7), node:FunctionDef (-> +7), node:arg, scope:f (-> +7), scope:q (-> +7), scope:seen (-> +7), scope:start (-> +7), scope:vertex (-> +7)
seen = set() # assignment:set, assignment_lhs_identifier:seen, external_free_call:set, free_call:set, free_call_no_arguments:set, node:Assign, node:Call, node:Name, single_assignment:seen
q = deque([start]) # argument:, assignment:deque, assignment_lhs_identifier:q, assignment_rhs_atom:start, external_free_call:deque, free_call:deque, literal:List, loaded_variable:start, node:Assign, node:Call, node:List, node:Name, single_assignment:q
while q: # loaded_variable:q, loop:while (-> +4), loop_with_late_exit:while (-> +4), node:Name, node:While (-> +4)
vertex = q.popleft() # assignment:popleft, assignment_lhs_identifier:vertex, assignment_rhs_atom:q, loaded_variable:q, member_call_method:popleft, node:Assign, node:Attribute, node:Call, node:Name, single_assignment:vertex
f(vertex) # argument:vertex, external_free_call:f, free_call:f, free_call_without_result:f, loaded_variable:vertex, node:Call, node:Expr, node:Name
seen.add(vertex) # argument:vertex, loaded_variable:seen, loaded_variable:vertex, member_call:seen:add, member_call_method:add, member_call_object:seen, node:Attribute, node:Call, node:Expr, node:Name, update:seen:vertex, update_by_member_call:seen:vertex, update_by_member_call_with:add, update_with:add
q.extend(v for v in vertex.adjacent if v not in seen) # argument:, comparison_operator:NotIn, comprehension:Generator, comprehension_for_count:1, filtered_comprehension, iteration_variable:v, loaded_variable:q, loaded_variable:seen, loaded_variable:v, loaded_variable:vertex, local_scope:v, member_call:q:extend, member_call_method:extend, member_call_object:q, node:Attribute, node:Call, node:Compare, node:Expr, node:GeneratorExp, node:Name, scope:v
# ----------------------------------------------------------------------------------------
# 130.2283-depth-first-traversing-in-a-graph.py
# ----------------------------------------------------------------------------------------
def depth_first(start, f): # function:depth_first (-> +7), function_line_count:8 (-> +7), function_parameter:f, function_parameter:start, function_parameter_flavor:arg, function_returning_nothing:depth_first (-> +7), higher_order_function:f (-> +7), local_scope:f (-> +7), local_scope:seen (-> +7), local_scope:stack (-> +7), local_scope:start (-> +7), local_scope:vertex (-> +7), node:FunctionDef (-> +7), node:arg, procedural_style (-> +7), scope:f (-> +7), scope:seen (-> +7), scope:stack (-> +7), scope:start (-> +7), scope:vertex (-> +7), variety:3 (-> +7), whole_span:8 (-> +7)
seen = set() # assignment:set, assignment_lhs_identifier:seen, external_free_call:set, free_call:set, free_call_no_arguments:set, node:Assign, node:Call, node:Name, single_assignment:seen
stack = [start] # assignment, assignment_lhs_identifier:stack, assignment_rhs_atom:start, literal:List, loaded_variable:start, node:Assign, node:List, node:Name, single_assignment:stack
while stack: # loaded_variable:stack, loop:while (-> +4), loop_with_late_exit:while (-> +4), node:Name, node:While (-> +4)
vertex = stack.pop() # assignment:pop, assignment_lhs_identifier:vertex, assignment_rhs_atom:stack, loaded_variable:stack, member_call_method:list:pop, node:Assign, node:Attribute, node:Call, node:Name, single_assignment:vertex
f(vertex) # argument:vertex, external_free_call:f, free_call:f, free_call_without_result:f, loaded_variable:vertex, node:Call, node:Expr, node:Name
seen.add(vertex) # argument:vertex, loaded_variable:seen, loaded_variable:vertex, member_call:seen:add, member_call_method:add, member_call_object:seen, node:Attribute, node:Call, node:Expr, node:Name, update:seen:vertex, update_by_member_call:seen:vertex, update_by_member_call_with:add, update_with:add
stack.extend(v for v in vertex.adjacent if v not in seen) # argument:, comparison_operator:NotIn, comprehension:Generator, comprehension_for_count:1, filtered_comprehension, iteration_variable:v, loaded_variable:seen, loaded_variable:stack, loaded_variable:v, loaded_variable:vertex, local_scope:v, member_call:stack:extend, member_call_method:extend, member_call_object:stack, node:Attribute, node:Call, node:Compare, node:Expr, node:GeneratorExp, node:Name, scope:v
# ----------------------------------------------------------------------------------------
# 131.2083-successive-conditions.py
# ----------------------------------------------------------------------------------------
f1 if c1 else f2 if c2 else f3 if c3 else None # flat_style, imperative_style, literal:None, loaded_variable:c1, loaded_variable:c2, loaded_variable:c3, loaded_variable:f1, loaded_variable:f2, loaded_variable:f3, node:Expr, node:IfExp, node:Name, node:NameConstant, one_liner_style, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 131.2766-successive-conditions.py
# ----------------------------------------------------------------------------------------
if c1: # if (-> +5), imperative_style (-> +5), loaded_variable:c1, node:If (-> +5), node:Name, variety:2 (-> +5), whole_span:6 (-> +5)
f1() # external_free_call:f1, free_call:f1, free_call_no_arguments:f1, free_call_without_result:f1, if_then_branch, node:Call, node:Expr, node:Name
elif c2: # if (-> +3), loaded_variable:c2, node:If (-> +3), node:Name
f2() # external_free_call:f2, free_call:f2, free_call_no_arguments:f2, free_call_without_result:f2, if_elif_branch, node:Call, node:Expr, node:Name
elif c3: # if (-> +1), loaded_variable:c3, node:If (-> +1), node:Name
f3() # external_free_call:f3, free_call:f3, free_call_no_arguments:f3, free_call_without_result:f3, if_elif_branch, node:Call, node:Expr, node:Name
# ----------------------------------------------------------------------------------------
# 132.2040-measure-duration-of-procedure-execution.py
# ----------------------------------------------------------------------------------------
import timeit # flat_style (-> +1), global_scope:duration (-> +1), imperative_style (-> +1), import:timeit, import_module:timeit, node:Import, one_liner_style (-> +1), scope:duration (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
duration = timeit.timeit("f()", setup="from __main__ import f") # argument:, assignment:timeit, assignment_lhs_identifier:duration, assignment_rhs_atom:timeit, keyword_argument:setup, literal:Str, loaded_variable:timeit, member_call_method:timeit, node:Assign, node:Attribute, node:Call, node:Name, node:Str, single_assignment:duration
# ----------------------------------------------------------------------------------------
# 133.2160-case-insensitive-string-contains.py
# ----------------------------------------------------------------------------------------
ok = word.lower() in s.lower() # assignment, assignment_lhs_identifier:ok, assignment_rhs_atom:s, assignment_rhs_atom:word, comparison_operator:In, flat_style, global_scope:ok, imperative_style, loaded_variable:s, loaded_variable:word, member_call_method:lower, node:Assign, node:Attribute, node:Call, node:Compare, node:Name, one_liner_style, scope:ok, single_assignment:ok, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 134.1850-create-a-new-list.py
# ----------------------------------------------------------------------------------------
items = [a, b, c] # assignment, assignment_lhs_identifier:items, assignment_rhs_atom:a, assignment_rhs_atom:b, assignment_rhs_atom:c, flat_style, global_scope:items, imperative_style, literal:List, loaded_variable:a, loaded_variable:b, loaded_variable:c, node:Assign, node:List, node:Name, one_liner_style, scope:items, single_assignment:items, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 135.2158-remove-item-from-list-by-its-value.py
# ----------------------------------------------------------------------------------------
items.remove(x) # argument:x, flat_style, imperative_style, loaded_variable:items, loaded_variable:x, member_call:items:remove, member_call_method:remove, member_call_object:items, node:Attribute, node:Call, node:Expr, node:Name, one_liner_style, update:items:x, update_by_member_call:items:x, update_by_member_call_with:remove, update_with:remove, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 136.2141-remove-all-occurrences-of-a-value-from-a-list.py
# ----------------------------------------------------------------------------------------
newlist = [item for item in items if item != x] # assignment, assignment_lhs_identifier:newlist, assignment_rhs_atom:item, assignment_rhs_atom:items, assignment_rhs_atom:x, comparison_operator:NotEq, comprehension:List, comprehension_for_count:1, filtered_comprehension, flat_style, imperative_style, iteration_variable:item, loaded_variable:item, loaded_variable:items, loaded_variable:x, local_scope:item, local_scope:newlist, node:Assign, node:Compare, node:ListComp, node:Name, one_liner_style, scope:item, scope:newlist, single_assignment:newlist, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 137.1823-check-if-string-contains-only-digits.py
# ----------------------------------------------------------------------------------------
b = s.isdigit() # assignment:isdigit, assignment_lhs_identifier:b, assignment_rhs_atom:s, flat_style, global_scope:b, imperative_style, loaded_variable:s, member_call_method:isdigit, node:Assign, node:Attribute, node:Call, node:Name, one_liner_style, scope:b, single_assignment:b, variety:1, whole_span:1
# ----------------------------------------------------------------------------------------
# 138.2161-create-temp-file.py
# ----------------------------------------------------------------------------------------
import tempfile # flat_style (-> +1), global_scope:file (-> +1), imperative_style (-> +1), import:tempfile, import_module:tempfile, node:Import, one_liner_style (-> +1), scope:file (-> +1), variety:2 (-> +1), whole_span:2 (-> +1)
file = tempfile.TemporaryFile() # assignment:TemporaryFile, assignment_lhs_identifier:file, assignment_rhs_atom:tempfile, loaded_variable:tempfile, member_call_method:TemporaryFile, node:Assign, node:Attribute, node:Call, node:Name, single_assignment:file
# ----------------------------------------------------------------------------------------
# 139.2162-create-temp-directory.py
# ----------------------------------------------------------------------------------------
import tempfile # flat_style (-> +1), global_scope:td (-> +1), imperative_style (-> +1), import:tempfile, import_module:tempfile, node:Import, one_liner_style (-> +1), scope:td (-> +1), variety:2 (-> +1), whole_span:2 (-> +1)
td = tempfile.TemporaryDirectory() # assignment:TemporaryDirectory, assignment_lhs_identifier:td, assignment_rhs_atom:tempfile, loaded_variable:tempfile, member_call_method:TemporaryDirectory, node:Assign, node:Attribute, node:Call, node:Name, single_assignment:td
# ----------------------------------------------------------------------------------------
# 140.2156-delete-map-entry.py
# ----------------------------------------------------------------------------------------
m.pop(k, None) # argument:None, argument:k, flat_style, imperative_style, literal:None, loaded_variable:k, loaded_variable:m, member_call:m:pop, member_call_method:pop, member_call_object:m, node:Attribute, node:Call, node:Expr, node:Name, node:NameConstant, one_liner_style, update:m:None, update:m:k, update_by_member_call:m:None, update_by_member_call:m:k, update_by_member_call_with:pop, update_with:pop, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 141.2159-iterate-in-sequence-over-two-lists.py
# ----------------------------------------------------------------------------------------
for x in items1 + items2: # addition_operator, binary_operator:Add, for:x (-> +1), global_scope:x (-> +1), imperative_style (-> +1), iteration_variable:x, loaded_variable:items1, loaded_variable:items2, loop:for (-> +1), loop_with_late_exit:for (-> +1), node:BinOp, node:For (-> +1), node:Name, scope:x (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
print(x) # argument:x, external_free_call:print, free_call:print, free_call_without_result:print, loaded_variable:x, node:Call, node:Expr, node:Name
# ----------------------------------------------------------------------------------------
# 142.2151-hexadecimal-digits-of-an-integer.py
# ----------------------------------------------------------------------------------------
s = hex(x) # argument:x, assignment:hex, assignment_lhs_identifier:s, assignment_rhs_atom:x, external_free_call:hex, flat_style, free_call:hex, global_scope:s, imperative_style, loaded_variable:x, node:Assign, node:Call, node:Name, one_liner_style, scope:s, single_assignment:s, variety:1, whole_span:1
# ----------------------------------------------------------------------------------------
# 143.2256-iterate-alternatively-over-two-lists.py
# ----------------------------------------------------------------------------------------
for pair in zip(item1, item2): # argument:item1, argument:item2, external_free_call:zip, for:pair (-> +1), free_call:zip, global_scope:pair (-> +1), imperative_style (-> +1), iteration_variable:pair, loaded_variable:item1, loaded_variable:item2, loop:for (-> +1), loop_with_late_exit:for (-> +1), node:Call, node:For (-> +1), node:Name, scope:pair (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
print(pair) # argument:pair, external_free_call:print, free_call:print, free_call_without_result:print, loaded_variable:pair, node:Call, node:Expr, node:Name
# ----------------------------------------------------------------------------------------
# 144.2145-check-if-file-exists.py
# ----------------------------------------------------------------------------------------
import os # flat_style (-> +1), global_scope:b (-> +1), imperative_style (-> +1), import:os, import_module:os, node:Import, one_liner_style (-> +1), scope:b (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
b = os.path.exists(fp) # argument:fp, assignment:exists, assignment_lhs_identifier:b, assignment_rhs_atom:fp, assignment_rhs_atom:os, loaded_variable:fp, loaded_variable:os, member_call_method:exists, node:Assign, node:Attribute, node:Call, node:Name, single_assignment:b, value_attr:path
# ----------------------------------------------------------------------------------------
# 144.2915-check-if-file-exists.py
# ----------------------------------------------------------------------------------------
from pathlib import Path # flat_style (-> +1), global_scope:b (-> +1), imperative_style (-> +1), import:pathlib:Path, import_module:pathlib, import_name:Path, node:ImportFrom, one_liner_style (-> +1), scope:b (-> +1), variety:2 (-> +1), whole_span:2 (-> +1)
b = Path(fp).exists() # argument:fp, assignment:exists, assignment_lhs_identifier:b, assignment_rhs_atom:fp, external_free_call:Path, free_call:Path, loaded_variable:fp, member_call_method:exists, node:Assign, node:Attribute, node:Call, node:Name, single_assignment:b
# ----------------------------------------------------------------------------------------
# 145.1822-print-log-line-with-datetime.py
# ----------------------------------------------------------------------------------------
import sys, logging # flat_style (-> +5), global_scope:logger (-> +5), imperative_style (-> +5), import:logging, import:sys, import_module:logging, import_module:sys, node:Import, scope:logger (-> +5), variety:2 (-> +5), whole_span:6 (-> +5)
logging.basicConfig( # loaded_variable:logging, member_call:logging:basicConfig, member_call_method:basicConfig, member_call_object:logging, node:Attribute, node:Call (-> +1), node:Expr (-> +1), node:Name
stream=sys.stdout, level=logging.DEBUG, format="%(asctime)-15s %(message)s" # argument:, keyword_argument:format, keyword_argument:level, keyword_argument:stream, literal:Str, loaded_variable:logging, loaded_variable:sys, node:Attribute, node:Name, node:Str, value_attr:DEBUG, value_attr:stdout
)
logger = logging.getLogger("NAME OF LOGGER") # argument:, assignment:getLogger, assignment_lhs_identifier:logger, assignment_rhs_atom:logging, literal:Str, loaded_variable:logging, member_call_method:getLogger, node:Assign, node:Attribute, node:Call, node:Name, node:Str, single_assignment:logger
logger.info(msg) # argument:msg, loaded_variable:logger, loaded_variable:msg, member_call:logger:info, member_call_method:info, member_call_object:logger, node:Attribute, node:Call, node:Expr, node:Name
# ----------------------------------------------------------------------------------------
# 146.1825-convert-string-to-floating-point-number.py
# ----------------------------------------------------------------------------------------
import locale # flat_style (-> +3), global_scope:f (-> +3), global_scope:s (-> +3), imperative_style (-> +3), import:locale, import_module:locale, node:Import, scope:f (-> +3), scope:s (-> +3), variety:2 (-> +3), whole_span:4 (-> +3)
s = u"545,2222" # assignment, assignment_lhs_identifier:s, literal:Str, node:Assign, node:Name, node:Str, single_assignment:s
locale.setlocale(locale.LC_ALL, "de") # argument:, literal:Str, loaded_variable:locale, member_call:locale:setlocale, member_call_method:setlocale, member_call_object:locale, node:Attribute, node:Call, node:Expr, node:Name, node:Str
f = locale.atof(s) # argument:s, assignment:atof, assignment_lhs_identifier:f, assignment_rhs_atom:locale, assignment_rhs_atom:s, loaded_variable:locale, loaded_variable:s, member_call_method:atof, node:Assign, node:Attribute, node:Call, node:Name, single_assignment:f
# ----------------------------------------------------------------------------------------
# 146.1826-convert-string-to-floating-point-number.py
# ----------------------------------------------------------------------------------------
f = float(s) # argument:s, assignment:float, assignment_lhs_identifier:f, assignment_rhs_atom:s, external_free_call:float, flat_style, free_call:float, global_scope:f, imperative_style, loaded_variable:s, node:Assign, node:Call, node:Name, one_liner_style, scope:f, single_assignment:f, variety:1, whole_span:1
# ----------------------------------------------------------------------------------------
# 146.2739-convert-string-to-floating-point-number.py
# ----------------------------------------------------------------------------------------
float("1.3") # argument:, external_free_call:float, flat_style, free_call:float, free_call_without_result:float, imperative_style, literal:Str, node:Call, node:Expr, node:Name, node:Str, one_liner_style, variety:1, whole_span:1
# ----------------------------------------------------------------------------------------
# 147.2171-remove-all-non-ascii-characters.py
# ----------------------------------------------------------------------------------------
import re # flat_style (-> +1), global_scope:t (-> +1), imperative_style (-> +1), import:re, import_module:re, node:Import, one_liner_style (-> +1), scope:t (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
t = re.sub("[^\u0000-\u007f]", "", s) # argument:, argument:s, assignment:sub, assignment_lhs_identifier:t, assignment_rhs_atom:re, assignment_rhs_atom:s, empty_literal:Str, literal:Str, loaded_variable:re, loaded_variable:s, member_call_method:sub, node:Assign, node:Attribute, node:Call, node:Name, node:Str, single_assignment:t, special_literal_string:[^\x00-\x7f]
# ----------------------------------------------------------------------------------------
# 148.1829-read-list-of-integer-numbers-from-stdin.py
# ----------------------------------------------------------------------------------------
list(map(int, input().split())) # argument:, argument:int, composition, external_free_call:input, external_free_call:list, external_free_call:map, flat_style, free_call:input, free_call:list, free_call:map, free_call_no_arguments:input, free_call_without_result:list, imperative_style, loaded_variable:int, member_call_method:split, node:Attribute, node:Call, node:Expr, node:Name, one_liner_style, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 150.2154-remove-trailing-slash.py
# ----------------------------------------------------------------------------------------
p = p.rstrip("/") # argument:, assignment:rstrip, assignment_lhs_identifier:p, assignment_rhs_atom:p, flat_style, global_scope:p, imperative_style, literal:Str, loaded_variable:p, member_call_method:rstrip, node:Assign, node:Attribute, node:Call, node:Name, node:Str, one_liner_style, scope:p, single_assignment:p, variety:1, whole_span:1
# ----------------------------------------------------------------------------------------
# 151.2166-remove-string-trailing-path-separator.py
# ----------------------------------------------------------------------------------------
import os # global_scope:p (-> +2), imperative_style (-> +2), import:os, import_module:os, node:Import, scope:p (-> +2), variety:2 (-> +2), whole_span:3 (-> +2)
if p.endswith(os.sep): # argument:, if (-> +1), if_test_atom:os, if_test_atom:p, if_without_else (-> +1), loaded_variable:os, loaded_variable:p, member_call_method:endswith, node:Attribute, node:Call, node:If (-> +1), node:Name
p = p[:-1] # assignment, assignment_lhs_identifier:p, assignment_rhs_atom:-1, assignment_rhs_atom:p, if_then_branch, literal:-1, loaded_variable:p, node:Assign, node:Name, node:Num, node:Subscript, single_assignment:p, slice::-1:, slice_lower:, slice_step:, slice_upper:-1, update:p:-1, update_by_assignment:p:-1, update_by_assignment_with, update_with
# ----------------------------------------------------------------------------------------
# 152.2153-turn-a-character-into-a-string.py
# ----------------------------------------------------------------------------------------
s = c # assignment, assignment_lhs_identifier:s, assignment_rhs_atom:c, flat_style, global_scope:s, imperative_style, loaded_variable:c, node:Assign, node:Name, one_liner_style, scope:s, single_assignment:s, variety:1, whole_span:1
# ----------------------------------------------------------------------------------------
# 153.1980-concatenate-string-with-integer.py
# ----------------------------------------------------------------------------------------
t = "{}{}".format(s, i) # argument:i, argument:s, assignment:format, assignment_lhs_identifier:t, assignment_rhs_atom:i, assignment_rhs_atom:s, flat_style, global_scope:t, imperative_style, literal:Str, loaded_variable:i, loaded_variable:s, member_call_method:format, node:Assign, node:Attribute, node:Call, node:Name, node:Str, one_liner_style, scope:t, single_assignment:t, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 154.2155-halfway-between-two-hex-color-codes.py
# ----------------------------------------------------------------------------------------
r1, g1, b1 = [int(c1[p : p + 2], 16) for p in range(1, 6, 2)] # addition_operator, argument:, argument:1, argument:16, argument:2, argument:6, assignment, assignment_lhs_identifier:b1, assignment_lhs_identifier:g1, assignment_lhs_identifier:r1, assignment_rhs_atom:1, assignment_rhs_atom:16, assignment_rhs_atom:2, assignment_rhs_atom:6, assignment_rhs_atom:c1, assignment_rhs_atom:p, binary_operator:Add, comprehension:List, comprehension_for_count:1, external_free_call:int, external_free_call:range, flat_style (-> +2), free_call:int, free_call:range, global_scope:b1 (-> +2), global_scope:b2 (-> +2), global_scope:c (-> +2), global_scope:g1 (-> +2), global_scope:g2 (-> +2), global_scope:r1 (-> +2), global_scope:r2 (-> +2), imperative_style (-> +2), iteration_variable:p, literal:1, literal:16, literal:2, literal:6, literal:Tuple, loaded_variable:c1, loaded_variable:p, local_scope:p, magic_number:16, magic_number:6, node:Assign, node:BinOp, node:Call, node:ListComp, node:Name, node:Num, node:Subscript, node:Tuple, parallel_assignment:3, range:1:6:2, scope:b1 (-> +2), scope:b2 (-> +2), scope:c (-> +2), scope:g1 (-> +2), scope:g2 (-> +2), scope:p, scope:r1 (-> +2), scope:r2 (-> +2), slice:p:_:, slice_lower:p, slice_step:, slice_upper:_, variety:0 (-> +2), whole_span:3 (-> +2)
r2, g2, b2 = [int(c2[p : p + 2], 16) for p in range(1, 6, 2)] # addition_operator, argument:, argument:1, argument:16, argument:2, argument:6, assignment, assignment_lhs_identifier:b2, assignment_lhs_identifier:g2, assignment_lhs_identifier:r2, assignment_rhs_atom:1, assignment_rhs_atom:16, assignment_rhs_atom:2, assignment_rhs_atom:6, assignment_rhs_atom:c2, assignment_rhs_atom:p, binary_operator:Add, comprehension:List, comprehension_for_count:1, external_free_call:int, external_free_call:range, free_call:int, free_call:range, iteration_variable:p, literal:1, literal:16, literal:2, literal:6, literal:Tuple, loaded_variable:c2, loaded_variable:p, local_scope:p, magic_number:16, magic_number:6, node:Assign, node:BinOp, node:Call, node:ListComp, node:Name, node:Num, node:Subscript, node:Tuple, parallel_assignment:3, range:1:6:2, scope:p, slice:p:_:, slice_lower:p, slice_step:, slice_upper:_
c = "#{:02x}{:02x}{:02x}".format((r1 + r2) // 2, (g1 + g2) // 2, (b1 + b2) // 2) # addition_operator, argument:, assignment:format, assignment_lhs_identifier:c, assignment_rhs_atom:2, assignment_rhs_atom:b1, assignment_rhs_atom:b2, assignment_rhs_atom:g1, assignment_rhs_atom:g2, assignment_rhs_atom:r1, assignment_rhs_atom:r2, binary_operator:Add, binary_operator:FloorDiv, literal:2, literal:Str, loaded_variable:b1, loaded_variable:b2, loaded_variable:g1, loaded_variable:g2, loaded_variable:r1, loaded_variable:r2, member_call_method:format, node:Assign, node:Attribute, node:BinOp, node:Call, node:Name, node:Num, node:Str, single_assignment:c
# ----------------------------------------------------------------------------------------
# 154.2292-halfway-between-two-hex-color-codes.py
# ----------------------------------------------------------------------------------------
import numpy # global_scope:c1 (-> +14), global_scope:c2 (-> +14), import:numpy, import_module:numpy, node:Import, object_oriented_style (-> +14), scope:c1 (-> +14), scope:c2 (-> +14), variety:5 (-> +14), whole_span:15 (-> +14)
class RGB(numpy.ndarray): # class:RGB (-> +8), class_method_count:2 (-> +8), loaded_variable:numpy, node:Attribute, node:ClassDef (-> +8), node:Name
@classmethod # function_decorator:classmethod (-> +4), loaded_variable:classmethod, node:Name
def from_str(cls, rgbstr): # class_method:from_str (-> +3), decorated_function:from_str (-> +3), function:from_str (-> +3), function_line_count:4 (-> +3), function_parameter:cls, function_parameter:rgbstr, function_parameter_flavor:arg, function_returning_something:from_str (-> +3), local_scope:cls (-> +3), local_scope:rgbstr (-> +3), method:from_str (-> +3), node:FunctionDef (-> +3), node:arg, scope:cls (-> +3), scope:rgbstr (-> +3)
return numpy.array( # composition, loaded_variable:numpy, member_call:numpy:array, member_call:numpy:view, member_call_method:array, member_call_method:view, member_call_object:numpy, method_chaining, node:Attribute, node:Attribute (-> +1), node:Call (-> +1), node:Call (-> +2), node:Name, node:Return (-> +2), return (-> +2)
[int(rgbstr[i : i + 2], 16) for i in range(1, len(rgbstr), 2)] # addition_operator, argument:, argument:1, argument:16, argument:2, argument:rgbstr, binary_operator:Add, composition, comprehension:List, comprehension_for_count:1, external_free_call:int, external_free_call:len, external_free_call:range, free_call:int, free_call:len, free_call:range, iteration_variable:i, literal:1, literal:16, literal:2, loaded_variable:i, loaded_variable:rgbstr, local_scope:i, magic_number:16, node:BinOp, node:Call, node:ListComp, node:Name, node:Num, node:Subscript, range:1:_:2, scope:i, slice:i:_:, slice_lower:i, slice_step:, slice_upper:_
).view(cls) # argument:cls, loaded_variable:cls, node:Name
def __str__(self): # function:__str__ (-> +2), function_line_count:3 (-> +2), function_parameter:self, function_parameter_flavor:arg, function_returning_something:__str__ (-> +2), instance_method:__str__ (-> +2), local_scope:self (-> +2), method:__str__ (-> +2), node:FunctionDef (-> +2), node:arg, scope:self (-> +2)
self = self.astype(numpy.uint8) # argument:, assignment:astype, assignment_lhs_identifier:self, assignment_rhs_atom:numpy, assignment_rhs_atom:self, loaded_variable:numpy, loaded_variable:self, member_call_method:astype, node:Assign, node:Attribute, node:Call, node:Name, single_assignment:self, update:self:numpy, update_by_assignment:self:numpy, update_by_assignment_with:astype, update_with:astype
return "#" + "".join(format(n, "x") for n in self) # argument:, argument:n, binary_operator:Add, composition, comprehension:Generator, comprehension_for_count:1, concatenation_operator:Str, empty_literal:Str, external_free_call:format, free_call:format, iteration_variable:n, literal:Str, loaded_variable:n, loaded_variable:self, local_scope:n, member_call_method:join, node:Attribute, node:BinOp, node:Call, node:GeneratorExp, node:Name, node:Return, node:Str, return, scope:n
c1 = RGB.from_str("#a1b1c1") # argument:, assignment:from_str, assignment_lhs_identifier:c1, assignment_rhs_atom:RGB, literal:Str, loaded_variable:RGB, member_call_method:from_str, node:Assign, node:Attribute, node:Call, node:Name, node:Str, single_assignment:c1
print(c1) # argument:c1, external_free_call:print, free_call:print, free_call_without_result:print, loaded_variable:c1, node:Call, node:Expr, node:Name
c2 = RGB.from_str("#1A1B1C") # argument:, assignment:from_str, assignment_lhs_identifier:c2, assignment_rhs_atom:RGB, literal:Str, loaded_variable:RGB, member_call_method:from_str, node:Assign, node:Attribute, node:Call, node:Name, node:Str, single_assignment:c2
print(c2) # argument:c2, external_free_call:print, free_call:print, free_call_without_result:print, loaded_variable:c2, node:Call, node:Expr, node:Name
print((c1 + c2) / 2) # addition_operator, argument:, binary_operator:Add, binary_operator:Div, external_free_call:print, free_call:print, free_call_without_result:print, literal:2, loaded_variable:c1, loaded_variable:c2, node:BinOp, node:Call, node:Expr, node:Name, node:Num
# ----------------------------------------------------------------------------------------
# 155.2147-delete-file.py
# ----------------------------------------------------------------------------------------
import pathlib # flat_style (-> +2), global_scope:path (-> +2), imperative_style (-> +2), import:pathlib, import_module:pathlib, node:Import, scope:path (-> +2), variety:2 (-> +2), whole_span:3 (-> +2)
path = pathlib.Path(_filepath) # argument:_filepath, assignment:Path, assignment_lhs_identifier:path, assignment_rhs_atom:_filepath, assignment_rhs_atom:pathlib, loaded_variable:_filepath, loaded_variable:pathlib, member_call_method:Path, node:Assign, node:Attribute, node:Call, node:Name, single_assignment:path
path.unlink() # loaded_variable:path, member_call:path:unlink, member_call_method:unlink, member_call_object:path, node:Attribute, node:Call, node:Expr, node:Name
# ----------------------------------------------------------------------------------------
# 156.2148-format-integer-with-zero-padding.py
# ----------------------------------------------------------------------------------------
s = format("03d", i) # argument:, argument:i, assignment:format, assignment_lhs_identifier:s, assignment_rhs_atom:i, external_free_call:format, flat_style, free_call:format, global_scope:s, imperative_style, literal:Str, loaded_variable:i, node:Assign, node:Call, node:Name, node:Str, one_liner_style, scope:s, single_assignment:s, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 157.2150-declare-constant-string.py
# ----------------------------------------------------------------------------------------
PLANET = "Earth" # assignment, assignment_lhs_identifier:PLANET, flat_style, global_scope:PLANET, imperative_style, literal:Str, node:Assign, node:Name, node:Str, one_liner_style, scope:PLANET, single_assignment:PLANET, variety:1, whole_span:1
# ----------------------------------------------------------------------------------------
# 158.2163-random-sublist.py
# ----------------------------------------------------------------------------------------
import random # flat_style (-> +1), global_scope:y (-> +1), imperative_style (-> +1), import:random, import_module:random, node:Import, one_liner_style (-> +1), scope:y (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
y = random.sample(x, k) # argument:k, argument:x, assignment:sample, assignment_lhs_identifier:y, assignment_rhs_atom:k, assignment_rhs_atom:random, assignment_rhs_atom:x, loaded_variable:k, loaded_variable:random, loaded_variable:x, member_call_method:sample, node:Assign, node:Attribute, node:Call, node:Name, single_assignment:y
# ----------------------------------------------------------------------------------------
# 159.2281-trie.py
# ----------------------------------------------------------------------------------------
class Trie: # class:Trie (-> +4), class_method_count:1 (-> +4), node:ClassDef (-> +4), object_oriented_style (-> +4), variety:2 (-> +4), whole_span:5 (-> +4)
def __init__(self, prefix, value=None): # function:__init__ (-> +3), function_line_count:4 (-> +3), function_parameter:prefix, function_parameter:self, function_parameter:value, function_parameter_flavor:arg, function_returning_nothing:__init__ (-> +3), instance_method:__init__ (-> +3), literal:None, local_scope:prefix (-> +3), local_scope:self (-> +3), local_scope:value (-> +3), method:__init__ (-> +3), node:FunctionDef (-> +3), node:NameConstant, node:arg, scope:prefix (-> +3), scope:self (-> +3), scope:value (-> +3)
self.prefix = prefix # assignment, assignment_lhs_identifier:self, assignment_rhs_atom:prefix, loaded_variable:prefix, loaded_variable:self, node:Assign, node:Attribute, node:Name
self.children = [] # assignment, assignment_lhs_identifier:self, empty_literal:List, literal:List, loaded_variable:self, node:Assign, node:Attribute, node:List, node:Name
self.value = value # assignment, assignment_lhs_identifier:self, assignment_rhs_atom:value, loaded_variable:self, loaded_variable:value, node:Assign, node:Attribute, node:Name
# ----------------------------------------------------------------------------------------
# 160.2165-detect-if-32-bit-or-64-bit-architecture.py
# ----------------------------------------------------------------------------------------
import sys # imperative_style (-> +4), import:sys, import_module:sys, node:Import, variety:2 (-> +4), whole_span:5 (-> +4)
if sys.maxsize > 2 ** 32: # binary_operator:Pow, comparison_operator:Gt, if (-> +3), if_test_atom:2, if_test_atom:32, if_test_atom:sys, literal:2, literal:32, loaded_variable:sys, magic_number:32, node:Attribute, node:BinOp, node:Compare, node:If (-> +3), node:Name, node:Num
f64() # external_free_call:f64, free_call:f64, free_call_no_arguments:f64, free_call_without_result:f64, if_then_branch, node:Call, node:Expr, node:Name
else:
f32() # external_free_call:f32, free_call:f32, free_call_no_arguments:f32, free_call_without_result:f32, if_else_branch, node:Call, node:Expr, node:Name
# ----------------------------------------------------------------------------------------
# 161.2098-multiply-all-the-elements-of-a-list.py
# ----------------------------------------------------------------------------------------
elements = [c * x for x in elements] # assignment, assignment_lhs_identifier:elements, assignment_rhs_atom:c, assignment_rhs_atom:elements, assignment_rhs_atom:x, binary_operator:Mult, comprehension:List, comprehension_for_count:1, flat_style, imperative_style, iteration_variable:x, loaded_variable:c, loaded_variable:elements, loaded_variable:x, local_scope:elements, local_scope:x, multiplication_operator, node:Assign, node:BinOp, node:ListComp, node:Name, one_liner_style, scope:elements, scope:x, single_assignment:elements, update:elements:c, update:elements:x, update_by_assignment:elements:c, update_by_assignment:elements:x, update_by_assignment_with, update_with, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 162.2164-execute-procedures-depending-on-options.py
# ----------------------------------------------------------------------------------------
import sys # imperative_style (-> +4), import:sys, import_module:sys, node:Import, variety:2 (-> +4), whole_span:5 (-> +4)
if "b" in sys.argv[1:]: # comparison_operator:In, if (-> +1), if_test_atom:1, if_test_atom:sys, if_without_else (-> +1), literal:1, literal:Str, loaded_variable:sys, node:Attribute, node:Compare, node:If (-> +1), node:Name, node:Num, node:Str, node:Subscript, slice:1::, slice_lower:1, slice_step:, slice_upper:, value_attr:argv
bat() # external_free_call:bat, free_call:bat, free_call_no_arguments:bat, free_call_without_result:bat, if_then_branch, node:Call, node:Expr, node:Name
if "f" in sys.argv[1:]: # comparison_operator:In, if (-> +1), if_test_atom:1, if_test_atom:sys, if_without_else (-> +1), literal:1, literal:Str, loaded_variable:sys, node:Attribute, node:Compare, node:If (-> +1), node:Name, node:Num, node:Str, node:Subscript, slice:1::, slice_lower:1, slice_step:, slice_upper:, value_attr:argv
fox() # external_free_call:fox, free_call:fox, free_call_no_arguments:fox, free_call_without_result:fox, if_then_branch, node:Call, node:Expr, node:Name
# ----------------------------------------------------------------------------------------
# 163.2170-print-list-elements-by-group-of-2.py
# ----------------------------------------------------------------------------------------
for x in zip(list[::2], list[1::2]): # argument:, external_free_call:zip, for:x (-> +1), free_call:zip, global_scope:x (-> +1), imperative_style (-> +1), iteration_variable:x, literal:1, literal:2, loaded_variable:list, loop:for (-> +1), loop_with_late_exit:for (-> +1), node:Call, node:For (-> +1), node:Name, node:Num, node:Subscript, scope:x (-> +1), slice:1::2, slice:::2, slice_lower:, slice_lower:1, slice_step:2, slice_upper:, variety:1 (-> +1), whole_span:2 (-> +1)
print(x) # argument:x, external_free_call:print, free_call:print, free_call_without_result:print, loaded_variable:x, node:Call, node:Expr, node:Name
# ----------------------------------------------------------------------------------------
# 163.3177-print-list-elements-by-group-of-2.py
# ----------------------------------------------------------------------------------------
from itertools import tee # global_scope:a (-> +6), global_scope:b (-> +6), import:itertools:tee, import_module:itertools, import_name:tee, node:ImportFrom, procedural_style (-> +6), scope:a (-> +6), scope:b (-> +6), variety:3 (-> +6), whole_span:7 (-> +6)
def pairwise(iterable): # function:pairwise (-> +3), function_line_count:4 (-> +3), function_parameter:iterable, function_parameter_flavor:arg, function_returning_something:pairwise (-> +3), impure_function:pairwise (-> +3), local_scope:a (-> +3), local_scope:b (-> +3), local_scope:iterable (-> +3), node:FunctionDef (-> +3), node:arg, scope:a (-> +3), scope:b (-> +3), scope:iterable (-> +3), shadowing_scope:a (-> +3), shadowing_scope:b (-> +3)
a, b = tee(iterable) # argument:iterable, assignment:tee, assignment_lhs_identifier:a, assignment_lhs_identifier:b, assignment_rhs_atom:iterable, external_free_call:tee, free_call:tee, literal:Tuple, loaded_variable:iterable, node:Assign, node:Call, node:Name, node:Tuple, parallel_assignment:2
next(b, None) # argument:None, argument:b, external_free_call:next, free_call:next, free_call_without_result:next, literal:None, loaded_variable:b, node:Call, node:Expr, node:Name, node:NameConstant
return zip(a, b) # argument:a, argument:b, external_free_call:zip, free_call:zip, free_tail_call:zip, loaded_variable:a, loaded_variable:b, node:Call, node:Name, node:Return, return
for a, b in pairwise(list): # argument:list, for:a (-> +1), for:b (-> +1), free_call:pairwise, internal_free_call:pairwise, iteration_variable:a, iteration_variable:b, literal:Tuple, loaded_variable:list, loop:for (-> +1), loop_with_late_exit:for (-> +1), node:Call, node:For (-> +1), node:Name, node:Tuple
print(a, b) # argument:a, argument:b, external_free_call:print, free_call:print, free_call_without_result:print, loaded_variable:a, loaded_variable:b, node:Call, node:Expr, node:Name
# ----------------------------------------------------------------------------------------
# 164.2169-open-url-in-default-browser.py
# ----------------------------------------------------------------------------------------
import webbrowser # flat_style (-> +1), imperative_style (-> +1), import:webbrowser, import_module:webbrowser, node:Import, one_liner_style (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
webbrowser.open(s) # argument:s, loaded_variable:s, loaded_variable:webbrowser, member_call:webbrowser:open, member_call_method:open, member_call_object:webbrowser, node:Attribute, node:Call, node:Expr, node:Name
# ----------------------------------------------------------------------------------------
# 165.2149-last-element-of-list.py
# ----------------------------------------------------------------------------------------
x = items[-1] # assignment, assignment_lhs_identifier:x, assignment_rhs_atom:-1, assignment_rhs_atom:items, flat_style, global_scope:x, imperative_style, index:-1, literal:-1, loaded_variable:items, negative_index:-1, node:Assign, node:Name, node:Num, node:Subscript, one_liner_style, scope:x, single_assignment:x, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 166.2272-concatenate-two-lists.py
# ----------------------------------------------------------------------------------------
ab = a + b # addition_operator, assignment:Add, assignment_lhs_identifier:ab, assignment_rhs_atom:a, assignment_rhs_atom:b, binary_operator:Add, flat_style, global_scope:ab, imperative_style, loaded_variable:a, loaded_variable:b, node:Assign, node:BinOp, node:Name, one_liner_style, scope:ab, single_assignment:ab, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 167.2611-trim-prefix.py
# ----------------------------------------------------------------------------------------
t = s[s.startswith(p) and len(p) :] # argument:p, assignment, assignment_lhs_identifier:t, assignment_rhs_atom:p, assignment_rhs_atom:s, boolean_operator:And, external_free_call:len, flat_style, free_call:len, global_scope:t, imperative_style, loaded_variable:p, loaded_variable:s, member_call_method:startswith, node:Assign, node:Attribute, node:BoolOp, node:Call, node:Name, node:Subscript, one_liner_style, scope:t, single_assignment:t, slice:_::, slice_lower:_, slice_step:, slice_upper:, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 167.3175-trim-prefix.py
# ----------------------------------------------------------------------------------------
t = s.lstrip(p) # argument:p, assignment:lstrip, assignment_lhs_identifier:t, assignment_rhs_atom:p, assignment_rhs_atom:s, flat_style, global_scope:t, imperative_style, loaded_variable:p, loaded_variable:s, member_call_method:lstrip, node:Assign, node:Attribute, node:Call, node:Name, one_liner_style, scope:t, single_assignment:t, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 168.2277-trim-suffix.py
# ----------------------------------------------------------------------------------------
t = s.rsplit(w, 1)[0] # argument:1, argument:w, assignment, assignment_lhs_identifier:t, assignment_rhs_atom:0, assignment_rhs_atom:1, assignment_rhs_atom:s, assignment_rhs_atom:w, flat_style, global_scope:t, imperative_style, index:0, literal:0, literal:1, loaded_variable:s, loaded_variable:w, member_call:s:rsplit, member_call_method:rsplit, member_call_object:s, node:Assign, node:Attribute, node:Call, node:Name, node:Num, node:Subscript, one_liner_style, scope:t, single_assignment:t, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 168.3174-trim-suffix.py
# ----------------------------------------------------------------------------------------
t = s.rstrip(w) # argument:w, assignment:rstrip, assignment_lhs_identifier:t, assignment_rhs_atom:s, assignment_rhs_atom:w, flat_style, global_scope:t, imperative_style, loaded_variable:s, loaded_variable:w, member_call_method:rstrip, node:Assign, node:Attribute, node:Call, node:Name, one_liner_style, scope:t, single_assignment:t, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 169.2233-string-length.py
# ----------------------------------------------------------------------------------------
n = len(s) # argument:s, assignment:len, assignment_lhs_identifier:n, assignment_rhs_atom:s, external_free_call:len, flat_style, free_call:len, global_scope:n, imperative_style, loaded_variable:s, node:Assign, node:Call, node:Name, one_liner_style, scope:n, single_assignment:n, variety:1, whole_span:1
# ----------------------------------------------------------------------------------------
# 170.2275-get-map-size.py
# ----------------------------------------------------------------------------------------
n = len(mymap) # argument:mymap, assignment:len, assignment_lhs_identifier:n, assignment_rhs_atom:mymap, external_free_call:len, flat_style, free_call:len, global_scope:n, imperative_style, loaded_variable:mymap, node:Assign, node:Call, node:Name, one_liner_style, scope:n, single_assignment:n, variety:1, whole_span:1
# ----------------------------------------------------------------------------------------
# 171.2446-add-an-element-at-the-end-of-a-list.py
# ----------------------------------------------------------------------------------------
s.append(x) # argument:x, flat_style, imperative_style, loaded_variable:s, loaded_variable:x, member_call:s:append, member_call_method:append, member_call_object:s, node:Attribute, node:Call, node:Expr, node:Name, one_liner_style, update:s:x, update_by_member_call:s:x, update_by_member_call_with:append, update_with:append, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 172.2442-insert-entry-in-map.py
# ----------------------------------------------------------------------------------------
m[k] = v # assignment, assignment_lhs_identifier:m, assignment_rhs_atom:v, flat_style, imperative_style, index:k, loaded_variable:k, loaded_variable:m, loaded_variable:v, node:Assign, node:Name, node:Subscript, one_liner_style, subscript_assignment:Name, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 173.2427-format-a-number-with-grouped-thousands.py
# ----------------------------------------------------------------------------------------
print("f'{1000:,}'") # argument:, external_free_call:print, flat_style, free_call:print, free_call_without_result:print, imperative_style, literal:Str, node:Call, node:Expr, node:Name, node:Str, one_liner_style, variety:1, whole_span:1
# ----------------------------------------------------------------------------------------
# 173.2428-format-a-number-with-grouped-thousands.py
# ----------------------------------------------------------------------------------------
print("format(1000, ',')") # argument:, external_free_call:print, flat_style, free_call:print, free_call_without_result:print, imperative_style, literal:Str, node:Call, node:Expr, node:Name, node:Str, one_liner_style, variety:1, whole_span:1
# ----------------------------------------------------------------------------------------
# 173.2429-format-a-number-with-grouped-thousands.py
# ----------------------------------------------------------------------------------------
print("'{:,}'.format(1000)") # argument:, external_free_call:print, flat_style, free_call:print, free_call_without_result:print, imperative_style, literal:Str, node:Call, node:Expr, node:Name, node:Str, one_liner_style, variety:1, whole_span:1
# ----------------------------------------------------------------------------------------
# 174.2687-make-http-post-request.py
# ----------------------------------------------------------------------------------------
from urllib import request, parse # flat_style (-> +3), global_scope:data (-> +3), global_scope:req (-> +3), global_scope:resp (-> +3), imperative_style (-> +3), import:urllib:parse, import:urllib:request, import_module:urllib, import_name:parse, import_name:request, node:ImportFrom, scope:data (-> +3), scope:req (-> +3), scope:resp (-> +3), variety:1 (-> +3), whole_span:4 (-> +3)
data = parse.urlencode("<your data dict>").encode() # argument:, assignment:encode, assignment_lhs_identifier:data, assignment_rhs_atom:parse, literal:Str, loaded_variable:parse, member_call:parse:encode, member_call:parse:urlencode, member_call_method:encode, member_call_method:urlencode, member_call_object:parse, method_chaining, node:Assign, node:Attribute, node:Call, node:Name, node:Str, single_assignment:data
req = request.Request(u, data=data, method="POST") # argument:, argument:data, argument:u, assignment:Request, assignment_lhs_identifier:req, assignment_rhs_atom:data, assignment_rhs_atom:request, assignment_rhs_atom:u, keyword_argument:data, keyword_argument:method, literal:Str, loaded_variable:data, loaded_variable:request, loaded_variable:u, member_call_method:Request, node:Assign, node:Attribute, node:Call, node:Name, node:Str, single_assignment:req
resp = request.urlopen(req) # argument:req, assignment:urlopen, assignment_lhs_identifier:resp, assignment_rhs_atom:req, assignment_rhs_atom:request, loaded_variable:req, loaded_variable:request, member_call_method:urlopen, node:Assign, node:Attribute, node:Call, node:Name, single_assignment:resp
# ----------------------------------------------------------------------------------------
# 175.2613-bytes-to-hex-string.py
# ----------------------------------------------------------------------------------------
s = a.hex() # assignment:hex, assignment_lhs_identifier:s, assignment_rhs_atom:a, flat_style, global_scope:s, imperative_style, loaded_variable:a, member_call_method:hex, node:Assign, node:Attribute, node:Call, node:Name, one_liner_style, scope:s, single_assignment:s, variety:1, whole_span:1
# ----------------------------------------------------------------------------------------
# 176.2614-hex-string-to-byte-array.py
# ----------------------------------------------------------------------------------------
a = bytearray.fromhex(s) # argument:s, assignment:fromhex, assignment_lhs_identifier:a, assignment_rhs_atom:bytearray, assignment_rhs_atom:s, flat_style, global_scope:a, imperative_style, loaded_variable:bytearray, loaded_variable:s, member_call_method:fromhex, node:Assign, node:Attribute, node:Call, node:Name, one_liner_style, scope:a, single_assignment:a, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 177.2709-find-files-with-a-given-list-of-filename-extensions.py
# ----------------------------------------------------------------------------------------
import os # flat_style (-> +2), global_scope:L (-> +2), global_scope:extensions (-> +2), imperative_style (-> +2), import:os, import_module:os, node:Import, scope:L (-> +2), scope:extensions (-> +2), variety:1 (-> +2), whole_span:3 (-> +2)
extensions = [".jpg", ".jpeg", ".png"] # assignment, assignment_lhs_identifier:extensions, literal:List, literal:Str, node:Assign, node:List, node:Name, node:Str, single_assignment:extensions
L = [f for f in os.listdir(D) if os.path.splitext(f)[1] in extensions] # argument:D, argument:f, assignment, assignment_lhs_identifier:L, assignment_rhs_atom:1, assignment_rhs_atom:D, assignment_rhs_atom:extensions, assignment_rhs_atom:f, assignment_rhs_atom:os, comparison_operator:In, comprehension:List, comprehension_for_count:1, filtered_comprehension, index:1, iteration_variable:f, literal:1, loaded_variable:D, loaded_variable:extensions, loaded_variable:f, loaded_variable:os, local_scope:f, member_call_method:listdir, member_call_method:splitext, node:Assign, node:Attribute, node:Call, node:Compare, node:ListComp, node:Name, node:Num, node:Subscript, scope:f, single_assignment:L, value_attr:path
# ----------------------------------------------------------------------------------------
# 177.2725-find-files-with-a-given-list-of-filename-extensions.py
# ----------------------------------------------------------------------------------------
import re # flat_style (-> +6), global_scope:filtered_files (-> +6), imperative_style (-> +6), import:re, import_module:re, node:Import, scope:filtered_files (-> +6), variety:2 (-> +6), whole_span:7 (-> +6)
import os # import:os, import_module:os, node:Import
filtered_files = [ # assignment, assignment_lhs_identifier:filtered_files, comprehension:List, comprehension_for_count:2, local_scope:_, local_scope:dirpath, local_scope:filename, local_scope:filenames, node:Assign (-> +4), node:ListComp (-> +4), node:Name, scope:_, scope:dirpath, scope:filename, scope:filenames, single_assignment:filtered_files
"{}/{}".format(dirpath, filename) # argument:dirpath, argument:filename, assignment_rhs_atom:dirpath, assignment_rhs_atom:filename, literal:Str, loaded_variable:dirpath, loaded_variable:filename, member_call_method:format, node:Attribute, node:Call, node:Name, node:Str
for dirpath, _, filenames in os.walk(D) # argument:D, assignment_rhs_atom:D, assignment_rhs_atom:_, assignment_rhs_atom:dirpath, assignment_rhs_atom:filenames, assignment_rhs_atom:os, iteration_variable:_, iteration_variable:dirpath, iteration_variable:filenames, literal:Tuple, loaded_variable:D, loaded_variable:os, member_call_method:walk, node:Attribute, node:Call, node:Name, node:Tuple
for filename in filenames # assignment_rhs_atom:filename, assignment_rhs_atom:filenames, iteration_variable:filename, loaded_variable:filenames, node:Name
if re.match(r"^.*\.(?:jpg|jpeg|png)$", filename) # argument:, argument:filename, assignment_rhs_atom:filename, assignment_rhs_atom:re, filtered_comprehension, literal:Str, loaded_variable:filename, loaded_variable:re, member_call_method:match, node:Attribute, node:Call, node:Name, node:Str
]
# ----------------------------------------------------------------------------------------
# 177.3241-find-files-with-a-given-list-of-filename-extensions.py
# ----------------------------------------------------------------------------------------
import glob # flat_style (-> +2), imperative_style (-> +2), import:glob, import_module:glob, node:Import, one_liner_style (-> +2), variety:1 (-> +2), whole_span:3 (-> +2)
import itertools # import:itertools, import_module:itertools, node:Import
list(itertools.chain(*(glob.glob("*/**.%s" % ext) for ext in ["jpg", "jpeg", "png"]))) # argument:, binary_operator:Mod, composition, comprehension:Generator, comprehension_for_count:1, external_free_call:list, free_call:list, free_call_without_result:list, iteration_variable:ext, literal:List, literal:Str, loaded_variable:ext, loaded_variable:glob, loaded_variable:itertools, local_scope:ext, member_call_method:chain, member_call_method:glob, node:Attribute, node:BinOp, node:Call, node:Expr, node:GeneratorExp, node:List, node:Name, node:Starred, node:Str, scope:ext, string_formatting_operator
# ----------------------------------------------------------------------------------------
# 178.2615-check-if-point-is-inside-rectangle.py
# ----------------------------------------------------------------------------------------
b = (x1 < x < x2) and (y1 < y < y2) # assignment, assignment_lhs_identifier:b, assignment_rhs_atom:x, assignment_rhs_atom:x1, assignment_rhs_atom:x2, assignment_rhs_atom:y, assignment_rhs_atom:y1, assignment_rhs_atom:y2, boolean_operator:And, chained_comparison:2, chained_inequalities:2, comparison_operator:Lt, flat_style, global_scope:b, imperative_style, loaded_variable:x, loaded_variable:x1, loaded_variable:x2, loaded_variable:y, loaded_variable:y1, loaded_variable:y2, node:Assign, node:BoolOp, node:Compare, node:Name, one_liner_style, scope:b, single_assignment:b, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 179.2688-get-center-of-a-rectangle.py
# ----------------------------------------------------------------------------------------
center = ((x1 + x2) / 2, (y1 + y2) / 2) # addition_operator, assignment, assignment_lhs_identifier:center, assignment_rhs_atom:2, assignment_rhs_atom:x1, assignment_rhs_atom:x2, assignment_rhs_atom:y1, assignment_rhs_atom:y2, binary_operator:Add, binary_operator:Div, flat_style, global_scope:center, imperative_style, literal:2, literal:Tuple, loaded_variable:x1, loaded_variable:x2, loaded_variable:y1, loaded_variable:y2, node:Assign, node:BinOp, node:Name, node:Num, node:Tuple, one_liner_style, scope:center, single_assignment:center, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 179.2689-get-center-of-a-rectangle.py
# ----------------------------------------------------------------------------------------
from collections import namedtuple # flat_style (-> +2), global_scope:Point (-> +2), global_scope:center (-> +2), imperative_style (-> +2), import:collections:namedtuple, import_module:collections, import_name:namedtuple, node:ImportFrom, scope:Point (-> +2), scope:center (-> +2), variety:1 (-> +2), whole_span:3 (-> +2)
Point = namedtuple("Point", "x y") # argument:, assignment:namedtuple, assignment_lhs_identifier:Point, external_free_call:namedtuple, free_call:namedtuple, literal:Str, node:Assign, node:Call, node:Name, node:Str, single_assignment:Point
center = Point((x1 + x2) / 2, (y1 + y2) / 2) # addition_operator, argument:, assignment:Point, assignment_lhs_identifier:center, assignment_rhs_atom:2, assignment_rhs_atom:x1, assignment_rhs_atom:x2, assignment_rhs_atom:y1, assignment_rhs_atom:y2, binary_operator:Add, binary_operator:Div, external_free_call:Point, free_call:Point, literal:2, loaded_variable:x1, loaded_variable:x2, loaded_variable:y1, loaded_variable:y2, node:Assign, node:BinOp, node:Call, node:Name, node:Num, single_assignment:center
# ----------------------------------------------------------------------------------------
# 180.2612-list-files-in-directory.py
# ----------------------------------------------------------------------------------------
import os # flat_style (-> +1), global_scope:x (-> +1), imperative_style (-> +1), import:os, import_module:os, node:Import, one_liner_style (-> +1), scope:x (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
x = os.listdir(d) # argument:d, assignment:listdir, assignment_lhs_identifier:x, assignment_rhs_atom:d, assignment_rhs_atom:os, loaded_variable:d, loaded_variable:os, member_call_method:listdir, node:Assign, node:Attribute, node:Call, node:Name, single_assignment:x
# ----------------------------------------------------------------------------------------
# 182.2658-quine-program.py
# ----------------------------------------------------------------------------------------
s = "s = %r\nprint(s%%s)" # assignment, assignment_lhs_identifier:s, flat_style (-> +1), global_scope:s (-> +1), imperative_style (-> +1), literal:Str, node:Assign, node:Name, node:Str, scope:s (-> +1), single_assignment:s, special_literal_string:s = %r\nprint(s%%s), variety:1 (-> +1), whole_span:2 (-> +1)
print(s % s) # argument:, binary_operator:Mod, external_free_call:print, free_call:print, free_call_without_result:print, loaded_variable:s, modulo_operator, node:BinOp, node:Call, node:Expr, node:Name
# ----------------------------------------------------------------------------------------
# 183.3025-make-http-put-request.py
# ----------------------------------------------------------------------------------------
requests # flat_style (-> +6), global_scope:content (-> +6), global_scope:content_type (-> +6), global_scope:data (-> +6), global_scope:headers (-> +6), global_scope:r (-> +6), global_scope:status_code (-> +6), imperative_style (-> +6), loaded_variable:requests, node:Expr, node:Name, scope:content (-> +6), scope:content_type (-> +6), scope:data (-> +6), scope:headers (-> +6), scope:r (-> +6), scope:status_code (-> +6), variety:2 (-> +6), whole_span:7 (-> +6)
import requests # import:requests, import_module:requests, node:Import
content_type = "text/plain" # assignment, assignment_lhs_identifier:content_type, literal:Str, node:Assign, node:Name, node:Str, single_assignment:content_type
headers = {"Content-Type": content_type} # assignment, assignment_lhs_identifier:headers, assignment_rhs_atom:content_type, literal:Dict, literal:Str, loaded_variable:content_type, node:Assign, node:Dict, node:Name, node:Str, single_assignment:headers
data = {} # assignment, assignment_lhs_identifier:data, empty_literal:Dict, literal:Dict, node:Assign, node:Dict, node:Name, single_assignment:data
r = requests.put(url, headers=headers, data=data) # argument:data, argument:headers, argument:url, assignment:put, assignment_lhs_identifier:r, assignment_rhs_atom:data, assignment_rhs_atom:headers, assignment_rhs_atom:requests, assignment_rhs_atom:url, keyword_argument:data, keyword_argument:headers, loaded_variable:data, loaded_variable:headers, loaded_variable:requests, loaded_variable:url, member_call_method:put, node:Assign, node:Attribute, node:Call, node:Name, single_assignment:r
status_code, content = r.status_code, r.content # assignment, assignment_lhs_identifier:content, assignment_lhs_identifier:status_code, assignment_rhs_atom:r, literal:Tuple, loaded_variable:r, node:Assign, node:Attribute, node:Name, node:Tuple, parallel_assignment:2
# ----------------------------------------------------------------------------------------
# 184.2701-tomorrow.py
# ----------------------------------------------------------------------------------------
from datetime import date, timedelta # flat_style (-> +1), imperative_style (-> +1), import:datetime:date, import:datetime:timedelta, import_module:datetime, import_name:date, import_name:timedelta, node:ImportFrom, one_liner_style (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
date.today() + timedelta(days=1) # addition_operator, argument:1, binary_operator:Add, external_free_call:timedelta, free_call:timedelta, free_call_with_keyword_argument:timedelta:days, keyword_argument:days, literal:1, loaded_variable:date, member_call_method:today, node:Attribute, node:BinOp, node:Call, node:Expr, node:Name, node:Num
# ----------------------------------------------------------------------------------------
# 185.2820-execute-function-in-30-seconds.py
# ----------------------------------------------------------------------------------------
import threading # flat_style (-> +2), global_scope:timer (-> +2), imperative_style (-> +2), import:threading, import_module:threading, node:Import, scope:timer (-> +2), variety:1 (-> +2), whole_span:3 (-> +2)
timer = threading.Timer(30.0, f, args=(42,)) # argument:, argument:30.0, argument:f, assignment:Timer, assignment_lhs_identifier:timer, assignment_rhs_atom:30.0, assignment_rhs_atom:42, assignment_rhs_atom:f, assignment_rhs_atom:threading, keyword_argument:args, literal:30.0, literal:42, literal:Tuple, loaded_variable:f, loaded_variable:threading, magic_number:30.0, magic_number:42, member_call_method:Timer, node:Assign, node:Attribute, node:Call, node:Name, node:Num, node:Tuple, single_assignment:timer
timer.start() # loaded_variable:timer, member_call:timer:start, member_call_method:start, member_call_object:timer, node:Attribute, node:Call, node:Expr, node:Name
# ----------------------------------------------------------------------------------------
# 186.2699-exit-program-cleanly.py
# ----------------------------------------------------------------------------------------
import sys # flat_style (-> +1), imperative_style (-> +1), import:sys, import_module:sys, node:Import, one_liner_style (-> +1), variety:2 (-> +1), whole_span:2 (-> +1)
sys.exit(0) # argument:0, literal:0, loaded_variable:sys, member_call:sys:exit, member_call_method:exit, member_call_object:sys, node:Attribute, node:Call, node:Expr, node:Name, node:Num
# ----------------------------------------------------------------------------------------
# 187.3261-disjoint-set.py
# ----------------------------------------------------------------------------------------
class UnionFind: # class:UnionFind (-> +14), class_method_count:4 (-> +14), node:ClassDef (-> +14), object_oriented_style (-> +14), variety:3 (-> +14), whole_span:15 (-> +14)
def __init__(self, size): # function:__init__ (-> +2), function_line_count:3 (-> +2), function_parameter:self, function_parameter:size, function_parameter_flavor:arg, function_returning_nothing:__init__ (-> +2), instance_method:__init__ (-> +2), local_scope:self (-> +2), local_scope:size (-> +2), method:__init__ (-> +2), node:FunctionDef (-> +2), node:arg, scope:self (-> +2), scope:size (-> +2)
self.rank = [0] * size # assignment:Mult, assignment_lhs_identifier:self, assignment_rhs_atom:0, assignment_rhs_atom:size, binary_operator:Mult, literal:0, literal:List, loaded_variable:self, loaded_variable:size, node:Assign, node:Attribute, node:BinOp, node:List, node:Name, node:Num, replication_operator:List
self.p = [i for i in range(size)] # argument:size, assignment, assignment_lhs_identifier:self, assignment_rhs_atom:i, assignment_rhs_atom:size, comprehension:List, comprehension_for_count:1, external_free_call:range, free_call:range, iteration_variable:i, loaded_variable:i, loaded_variable:self, loaded_variable:size, local_scope:i, node:Assign, node:Attribute, node:Call, node:ListComp, node:Name, range:size, scope:i
def find_set(self, i): # function:find_set (-> +5), function_line_count:6 (-> +5), function_parameter:i, function_parameter:self, function_parameter_flavor:arg, function_returning_something:find_set (-> +5), instance_method:find_set (-> +5), local_scope:i (-> +5), local_scope:self (-> +5), method:find_set (-> +5), node:FunctionDef (-> +5), node:arg, scope:i (-> +5), scope:self (-> +5)
if self.p[i] == i: # comparison_operator:Eq, if (-> +4), if_test_atom:i, if_test_atom:self, index:i, loaded_variable:i, loaded_variable:self, node:Attribute, node:Compare, node:If (-> +4), node:Name, node:Subscript, value_attr:p
return i # if_then_branch, loaded_variable:i, node:Name, node:Return, return:i
else:
self.p[i] = self.find_set(self.p[i]) # argument:, assignment:find_set, assignment_rhs_atom:i, assignment_rhs_atom:self, if_else_branch (-> +1), index:i, loaded_variable:i, loaded_variable:self, member_call_method:find_set, node:Assign, node:Attribute, node:Call, node:Name, node:Subscript, subscript_assignment:Name, value_attr:p
return self.p[i] # index:i, loaded_variable:i, loaded_variable:self, node:Attribute, node:Name, node:Return, node:Subscript, return, value_attr:p
def is_same_set(self, i, j): # function:is_same_set (-> +1), function_line_count:2 (-> +1), function_parameter:i, function_parameter:j, function_parameter:self, function_parameter_flavor:arg, function_returning_something:is_same_set (-> +1), instance_method:is_same_set (-> +1), local_scope:i (-> +1), local_scope:j (-> +1), local_scope:self (-> +1), method:is_same_set (-> +1), node:FunctionDef (-> +1), node:arg, scope:i (-> +1), scope:j (-> +1), scope:self (-> +1)
return self.find_set(i) == self.find_set(j) # argument:i, argument:j, comparison_operator:Eq, loaded_variable:i, loaded_variable:j, loaded_variable:self, member_call_method:find_set, node:Attribute, node:Call, node:Compare, node:Name, node:Return, return
def union_set(self, i, j): # function:union_set (-> +2), function_line_count:3 (-> +2), function_parameter:i, function_parameter:j, function_parameter:self, function_parameter_flavor:arg, function_returning_nothing:union_set (-> +2), instance_method:union_set (-> +2), local_scope:i (-> +2), local_scope:j (-> +2), local_scope:self (-> +2), local_scope:x (-> +2), local_scope:y (-> +2), method:union_set (-> +2), node:FunctionDef (-> +2), node:arg, scope:i (-> +2), scope:j (-> +2), scope:self (-> +2), scope:x (-> +2), scope:y (-> +2)
if not self.is_same_set(i, j): # argument:i, argument:j, if (-> +1), if_test_atom:i, if_test_atom:j, if_test_atom:self, if_without_else (-> +1), loaded_variable:i, loaded_variable:j, loaded_variable:self, member_call_method:is_same_set, node:Attribute, node:Call, node:If (-> +1), node:Name, node:UnaryOp, unary_operator:Not
x, y = self.find_set(i), self.find_set(j) # argument:i, argument:j, assignment, assignment_lhs_identifier:x, assignment_lhs_identifier:y, assignment_rhs_atom:i, assignment_rhs_atom:j, assignment_rhs_atom:self, if_then_branch, literal:Tuple, loaded_variable:i, loaded_variable:j, loaded_variable:self, member_call_method:find_set, node:Assign, node:Attribute, node:Call, node:Name, node:Tuple, parallel_assignment:2
# ----------------------------------------------------------------------------------------
# 188.3171-matrix-multiplication.py
# ----------------------------------------------------------------------------------------
import numpy as np # flat_style (-> +1), global_scope:c (-> +1), imperative_style (-> +1), import:numpy, import_module:numpy, node:Import, one_liner_style (-> +1), scope:c (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
c = a @ b # assignment:MatMult, assignment_lhs_identifier:c, assignment_rhs_atom:a, assignment_rhs_atom:b, binary_operator:MatMult, loaded_variable:a, loaded_variable:b, node:Assign, node:BinOp, node:Name, single_assignment:c
# ----------------------------------------------------------------------------------------
# 188.3284-matrix-multiplication.py
# ----------------------------------------------------------------------------------------
import numpy as np # flat_style (-> +1), global_scope:c (-> +1), imperative_style (-> +1), import:numpy, import_module:numpy, node:Import, one_liner_style (-> +1), scope:c (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
c = np.matmul(a, b) # argument:a, argument:b, assignment:matmul, assignment_lhs_identifier:c, assignment_rhs_atom:a, assignment_rhs_atom:b, assignment_rhs_atom:np, loaded_variable:a, loaded_variable:b, loaded_variable:np, member_call_method:matmul, node:Assign, node:Attribute, node:Call, node:Name, single_assignment:c
# ----------------------------------------------------------------------------------------
# 189.3236-filter-and-transform-list.py
# ----------------------------------------------------------------------------------------
y = [T(e) for e in x if P(e)] # argument:e, assignment, assignment_lhs_identifier:y, assignment_rhs_atom:e, assignment_rhs_atom:x, comprehension:List, comprehension_for_count:1, external_free_call:P, external_free_call:T, filtered_comprehension, flat_style, free_call:P, free_call:T, imperative_style, iteration_variable:e, loaded_variable:e, loaded_variable:x, local_scope:e, local_scope:y, node:Assign, node:Call, node:ListComp, node:Name, one_liner_style, scope:e, scope:y, single_assignment:y, variety:0, whole_span:1
# ----------------------------------------------------------------------------------------
# 191.3403-check-if-any-value-in-a-list-is-larger-than-a-limit.py
# ----------------------------------------------------------------------------------------
if any(v > x for v in a): # argument:, comparison_operator:Gt, comprehension:Generator, comprehension_for_count:1, external_free_call:any, free_call:any, if (-> +1), if_test_atom:a, if_test_atom:v, if_test_atom:x, if_without_else (-> +1), imperative_style (-> +1), iteration_variable:v, loaded_variable:a, loaded_variable:v, loaded_variable:x, local_scope:v, node:Call, node:Compare, node:GeneratorExp, node:If (-> +1), node:Name, scope:v, variety:1 (-> +1), whole_span:2 (-> +1)
f() # external_free_call:f, free_call:f, free_call_no_arguments:f, free_call_without_result:f, if_then_branch, node:Call, node:Expr, node:Name
# ----------------------------------------------------------------------------------------
# 197.3457-get-a-list-of-lines-from-a-file.py
# ----------------------------------------------------------------------------------------
with open(path) as f: # argument:path, external_free_call:open, flat_style (-> +1), free_call:open, global_scope:lines (-> +1), imperative_style (-> +1), loaded_variable:path, node:Call, node:Name, node:With (-> +1), scope:lines (-> +1), variety:1 (-> +1), whole_span:2 (-> +1)
lines = f.readlines() # assignment:readlines, assignment_lhs_identifier:lines, assignment_rhs_atom:f, loaded_variable:f, member_call_method:readlines, node:Assign, node:Attribute, node:Call, node:Name, single_assignment:lines
|
celery_multiprocessing_env.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
This is the billiard assertion error, use EVN to avoid it,
In shell: export PYTHONOPTIMIZE=1
Or in python: os.environ["PYTHONOPTIMIZE"] = "1" # the value is of type string
See: https://github.com/celery/celery/issues/1709 for more infomation.
"""
from __future__ import absolute_import
import os
import multiprocessing
from celery import Celery
app = Celery("multi-process")
def m(arg):
print arg
@app.task
def multi(arg):
os.environ["PYTHONOPTIMIZE"] = "1"
th = multiprocessing.Process(target=m, args=(arg,))
th.start()
th.join()
return None
|
thread_demo.py | #!/usr/bin/python3
# -*- coding: UTF-8 -*-
import threading
import time
def foo(n):
print("args is %s" %(n))
x = 0
while x < 10:
print("child thread running", x)
time.sleep(1)
x += 1
def fun():
print("other child thread is runing")
if __name__ == '__main__':
# ๅฏๅจไธไธช็บฟ็จ,่ฟ้ๅๅๆฐ
t1 = threading.Thread(target=foo, args=(1,), name="thread-0")
t1.start()
t1.join()
print("main thread continue run")
# ๅฏๅจไธไธช็บฟ็จ๏ผ่ฟ้ๆฒกๆๅๆฐ
t2 = threading.Thread(target=fun,name="thread-1")
t2.start()
t2.join()
print("main thread continue run")
|
test_decorators.py | # Copyright 2021 ONDEWO GmbH
#
# 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, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import re
from logging import Logger
from multiprocessing.pool import ThreadPool
from threading import Thread, get_ident
from time import sleep
from typing import Any, Callable, Dict, List, Set, Union
import pytest
from ondewo.logging.constants import CONTEXT
from ondewo.logging.decorators import (
ThreadContextLogger,
Timer,
exception_handling,
exception_silencing,
timing,
)
from ondewo.logging.logger import logger_console
from tests.conftest import MockLoggingHandler
def test_timer(log_store, logger):
@Timer()
def timer_function():
sleep(0.01)
logger.addHandler(log_store)
timer_function()
assert log_store.count_levels("warning") == 3
@timing
def timing_function():
sleep(0.01)
timer_function()
assert log_store.count_levels("warning") == 6
with Timer():
sleep(0.01)
assert log_store.count_levels("warning") == 7
with timing:
sleep(0.01)
assert log_store.count_levels("warning") == 8
def test_timer_messages(log_store, logger):
MAGIC_WORD = "abracadabra"
TIMER_MESSAGE = MAGIC_WORD
@Timer(message=TIMER_MESSAGE)
def timer_function():
sleep(0.01)
logger.addHandler(log_store)
assert log_store.is_empty()
assert not log_store.count_levels("warning")
timer_function()
all_messages = " ".join(log_store.messages["warning"])
assert MAGIC_WORD in all_messages
log_store.reset()
assert log_store.is_empty()
with Timer(message=TIMER_MESSAGE):
sleep(0.01)
all_messages = " ".join(log_store.messages["warning"])
assert MAGIC_WORD in all_messages
MAGIC_WORD = "abracadabra"
TIMER_MESSAGE = MAGIC_WORD + " {}"
@Timer(message=TIMER_MESSAGE)
def timer_function():
sleep(0.01)
log_store.reset()
assert log_store.is_empty()
timer_function()
all_messages = " ".join(log_store.messages["warning"])
assert MAGIC_WORD in all_messages
assert re.findall(r"\d", all_messages)
log_store.reset()
assert log_store.is_empty()
with Timer(message=TIMER_MESSAGE):
sleep(0.01)
all_messages = " ".join(log_store.messages["warning"])
assert MAGIC_WORD in all_messages
assert re.findall(r"\d", all_messages)
MAGIC_WORD = "abracadabra"
TIMER_MESSAGE = MAGIC_WORD + " {}" + " {}"
@Timer(message=TIMER_MESSAGE)
def function_name():
sleep(0.01)
log_store.reset()
assert log_store.is_empty()
function_name()
all_messages = " ".join(log_store.messages["warning"])
assert "function_name" in all_messages
assert re.findall(r"\d", all_messages)
with Timer(message=TIMER_MESSAGE):
sleep(0.01)
all_messages = " ".join(log_store.messages["warning"])
assert CONTEXT in all_messages
assert re.findall(r"\d", all_messages)
def test_timer_level(log_store, logger):
logger.addHandler(log_store)
assert log_store.is_empty()
@Timer(logger=logger.debug)
def timer_function():
sleep(0.01)
assert not log_store.count_levels("debug")
timer_function()
assert log_store.count_levels("debug")
@Timer(logger=logger.info)
def timer_function():
sleep(0.01)
assert not log_store.count_levels("info")
timer_function()
assert log_store.count_levels("info")
log_store.reset()
@Timer(logger=logger.warning)
def timer_function():
sleep(0.01)
assert not log_store.count_levels("warning")
timer_function()
assert log_store.count_levels("warning")
@Timer(logger=logger.error)
def timer_function():
sleep(0.01)
assert not log_store.count_levels("error")
timer_function()
assert log_store.count_levels("error")
@Timer(logger=logger.critical)
def timer_function():
sleep(0.01)
assert not log_store.count_levels("critical")
timer_function()
assert log_store.count_levels("critical")
log_store.reset()
assert log_store.is_empty()
assert not log_store.count_levels("debug")
with Timer(logger=logger.debug):
sleep(0.01)
assert log_store.count_levels("debug")
def test_exception_handling(log_store, logger):
logger.addHandler(log_store)
short_list = [1, 2]
big_index = 3
@exception_handling
def error_function():
short_list[big_index]
assert log_store.is_empty()
error_function()
assert not log_store.is_empty()
@exception_silencing
def error_function():
short_list[big_index]
log_store.reset()
assert log_store.is_empty()
error_function()
assert not log_store.is_empty()
@exception_silencing
def error_function():
raise Exception()
log_store.reset()
assert log_store.is_empty()
error_function()
assert not log_store.is_empty()
@exception_handling
def error_function():
raise Exception()
log_store.reset()
assert log_store.is_empty()
error_function()
assert not log_store.is_empty()
@Timer(suppress_exceptions=True)
def error_function():
short_list[big_index]
log_store.reset()
assert log_store.is_empty()
error_function()
assert not log_store.is_empty()
def test_timer_depth(log_store, logger):
@Timer()
def timer_function(depth=0):
sleep(0.01)
if not depth:
timer_function(depth=depth + 1)
@Timer()
def timer_function_recursive(depth=0):
if not depth > 0:
timer_function_recursive(depth=depth + 1)
sleep(0.01)
logger.addHandler(log_store)
assert log_store.is_empty()
timer_function_recursive()
all_messages = " ".join(log_store.messages["warning"])
assert "Recursing" not in all_messages
log_store.reset()
assert log_store.is_empty()
@Timer(recursive=True)
def timer_function_recursive(depth=0):
if not depth > 0:
timer_function_recursive(depth=depth + 1)
sleep(0.01)
timer_function_recursive()
all_messages = " ".join(log_store.messages["warning"])
assert "Recursing" in all_messages
@Timer(logger=logger_console.info)
def concat_two_strings(a: str, b: str) -> str:
return a + b
@Timer(logger=logger_console.info)
def add_two_integers(a: int, b: int) -> int:
return a + b
@Timer(logger=logger_console.info, argument_max_length=3)
def concat_two_strings_long(a: str, b: str) -> str:
return a + b
@Timer(logger=logger_console.info, argument_max_length=-1)
def concat_two_strings_length_minus_one(a: str, b: str) -> str:
return a + b
@pytest.mark.parametrize(
"function, param_a, param_b, assert_args, assert_kwargs",
[
(
concat_two_strings,
"dog",
"cat",
["'dog'", "'cat'", "'result': 'dogcat'"],
["'a': 'dog'", "'b': 'cat'", "'result': 'dogcat'"],
),
(
add_two_integers,
1,
2,
["'1'", "'2'", "'result': '3'"],
["'a': '1'", "'b': '2'", "'result': '3'"],
),
(
concat_two_strings_long,
"a",
"long",
["'a'", "'lon<TRUNCATED!>'", "'result': 'alo<TRUNCATED!>'"],
["'a': 'a'", "'b': 'lon<TRUNCATED!>'", "'result': 'alo<TRUNCATED!>'"],
),
(
concat_two_strings_length_minus_one,
"doglong",
"catlong",
["'doglong'", "'catlong'", "'result': 'doglongcatlong'"],
["'a': 'doglong'", "'b': 'catlong'", "'result': 'doglongcatlong'"],
),
],
ids=[
"Param is a string",
"Param is not a string",
"String is too long",
"Max length is -1",
],
)
def test_length_filter(
log_store: MockLoggingHandler,
logger: Logger,
function: Callable,
param_a: Union[str, int],
param_b: Union[str, int],
assert_args: List[str],
assert_kwargs: List[str],
) -> None:
logger.addHandler(log_store)
# args
function(param_a, param_b)
all_messages = " ".join(log_store.messages["info"])
for assert_arg in assert_args:
assert assert_arg in all_messages
log_store.reset()
# kwargs
function(a=param_a, b=param_b)
all_messages = " ".join(log_store.messages["info"])
for assert_kwarg in assert_kwargs:
assert assert_kwarg in all_messages
log_store.reset()
@Timer()
def concat_two_strings_warning(a: str, b: str) -> str:
return a + b
def test_length_filter_logger_default_warning(log_store, logger) -> None:
logger.addHandler(log_store)
param_a: str = "dog"
param_b: str = "cat"
assert_args: List[str] = ["'dog'", "'cat'", "'result': 'dogcat'"]
assert_kwargs: List[str] = ["'a': 'dog'", "'b': 'cat'", "'result': 'dogcat'"]
# args
concat_two_strings_warning(param_a, param_b)
all_messages = " ".join(log_store.messages["warning"])
for assert_arg in assert_args:
assert assert_arg in all_messages
log_store.reset()
# kwargs
concat_two_strings_warning(a=param_a, b=param_b)
all_messages = " ".join(log_store.messages["warning"])
for assert_kwarg in assert_kwargs:
assert assert_kwarg in all_messages
log_store.reset()
def test_nested_functions(log_store, logger) -> None:
logger.addHandler(log_store)
@Timer()
def function_a():
sleep(0.01)
@Timer()
def function_b():
function_a()
sleep(0.01)
function_b()
all_messages = " ".join(log_store.messages["warning"])
assert all_messages.count("Elapsed time") == 2
def test_function_repeated(log_store: MockLoggingHandler, logger: Logger) -> None:
logger.addHandler(log_store)
@Timer()
def function():
sleep(0.01)
for _ in range(10):
function()
durations: List[float] = []
for message in log_store.messages["warning"]:
message_dict: Dict[str, Any] = eval(message)
if "duration" in message_dict:
durations.append(message_dict["duration"])
assert all(0.011 == pytest.approx(duration, abs=0.001) for duration in durations)
def test_function_concurrent(log_store: MockLoggingHandler, logger: Logger) -> None:
logger.addHandler(log_store)
@Timer()
def function():
sleep(0.01)
n_threads: int = 10
with ThreadPool(processes=n_threads) as pool:
pool.starmap(function, [[] for _ in range(n_threads)])
durations: List[float] = []
for message in log_store.messages["warning"]:
message_dict: Dict[str, Any] = eval(message)
if "duration" in message_dict:
durations.append(message_dict["duration"])
assert all(0.011 == pytest.approx(duration, abs=0.005) for duration in durations)
def test_timer_as_context_manager(log_store, logger) -> None:
logger.addHandler(log_store)
with Timer(logger=logger_console.warning):
concat_two_strings_warning("a", "b")
all_messages = " ".join(log_store.messages["warning"])
assert "exception" not in all_messages
log_store.reset()
with Timer(logger=logger_console.warning, suppress_exceptions=True):
raise Exception
all_messages = " ".join(log_store.messages["warning"])
assert "exception" in all_messages
log_store.reset()
class TestThreadContextLogger:
@staticmethod
@pytest.mark.parametrize(
"message, expected_message",
[
# nothing happens when the message is a plain string
(
"hello",
"hello",
),
# add a context if the message is a dict
(
{"message": "hello"},
{"message": "hello", "ctx": 123},
),
],
)
@pytest.mark.parametrize(
"thread_context_logger_type", ["context_manager", "decorator"]
)
def test_thread_context_logger(
log_store: MockLoggingHandler,
logger: Logger,
thread_context_logger_type: str,
message: Any,
expected_message: Any,
) -> None:
logger.addHandler(log_store)
thread_context_logger: ThreadContextLogger = ThreadContextLogger(
logger=logger,
context_dict={"ctx": 123},
)
@thread_context_logger
def function(msg: str) -> None:
logger.info(msg)
logger.info(message)
if thread_context_logger_type == "context_manager":
with thread_context_logger:
logger.info(message)
elif thread_context_logger_type == "decorator":
function(msg=message)
logger.info(message)
logged_messages: List[str] = log_store.messages["info"]
assert len(logged_messages) == 3
for i, logged_message in enumerate(logged_messages):
try:
logged_message = eval(logged_message)
except NameError:
pass
if i == 1:
# message affected with the thread context logger
assert logged_message == expected_message
else:
# message before/after the thread context logger
assert logged_message == message
log_store.reset()
@staticmethod
def test_thread_context_logger_in_multiple_threads(
log_store: MockLoggingHandler,
logger: Logger,
) -> None:
logger.addHandler(log_store)
def function(ctx: int) -> None:
with ThreadContextLogger(logger=logger, context_dict={"ctx": ctx}):
logger.info({"message": "start"})
sub_thread: Thread = Thread(
target=lambda: logger.info({"message": "continue"}),
name=f"sub-thread-{get_ident()}",
)
sub_thread.start()
sub_thread.join()
logger.info({"message": "end"})
n_threads: int = 10
with ThreadPool(processes=n_threads) as pool:
pool.map(function, range(n_threads))
messages: List[Dict[str, Any]] = [
eval(message) for message in log_store.messages["info"]
]
for i in range(n_threads):
messages_ctx: Set[str] = {
message["message"] for message in messages if message["ctx"] == i
}
assert messages_ctx == {"start", "continue", "end"}
log_store.reset()
|
marynarz.py | #!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
import threading
import time
class Marynarz(object):
def __init__(self, szer_drogi= 9, czas = 0.1):
self._pozycja = szer_drogi / 2
self._szer_drogi = szer_drogi
self._blokada = threading.Lock()
self._czas = czas
self._uruchomione = False
def pokaz_droge(self):
droga = "|"
for i in range(self._szer_drogi + 1):
if self._pozycja == i:
droga += "*"
else:
droga += "-"
droga += "|"
print droga
def sciagaj(self, delta = 1):
while self._uruchomione and self._blokada.acquire():
self._pozycja += delta
self.pokaz_droge()
if self._pozycja == 0 or self._pozycja == self._szer_drogi:
self._uruchomione = False
self._blokada.release()
# Dla testรณw tendencji "do prawej" i "do lewej"
time.sleep(self._czas - float(delta) / 100)
time.sleep(self._czas)
def run(self):
lewy = threading.Thread(target=self.sciagaj, args=(-1,))
prawy = threading.Thread(target=self.sciagaj, args=(1,))
self._uruchomione = True
lewy.start()
prawy.start()
lewy.join()
prawy.join()
if __name__ == '__main__':
m = Marynarz()
m.run()
|
test_client.py | """Tests for the `client` module."""
import json
import os
import signal
import threading
import time
from base64 import b64encode
from copy import deepcopy
import pytest
import requests
from responses import mock as responses
from aria2p import Client, ClientException
from aria2p.client import JSONRPC_CODES, JSONRPC_PARSER_ERROR, Notification
from . import BUNSENLABS_MAGNET, BUNSENLABS_TORRENT, CONFIGS_DIR, DEBIAN_METALINK, SESSIONS_DIR, XUBUNTU_MIRRORS
from .conftest import Aria2Server
class TestParameters:
# callback that return params of a single call as result
@staticmethod
def call_params_callback(request):
payload = json.loads(request.body)
resp_body = {"result": payload["params"]}
return 200, {}, json.dumps(resp_body)
# callback that return params of a batch call as result
@staticmethod
def batch_call_params_callback(request):
payload = json.loads(request.body)
resp_body = [{"result": method["params"]} for method in payload]
return 200, {}, json.dumps(resp_body)
@responses.activate
def test_insert_secret_with_aria2_method_call(self):
# create client with secret
secret = "hello"
client = Client(secret=secret)
responses.add_callback(responses.POST, client.server, callback=self.call_params_callback)
# create params
params = ["param1", "param2"]
# copy params and insert secret
expected_params = deepcopy(params)
expected_params.insert(0, f"token:{secret}")
# call function and assert result
resp = client.call(client.ADD_URI, params, insert_secret=True)
assert resp == expected_params
@responses.activate
def test_insert_secret_with_system_multicall(self):
# create client with secret
secret = "hello"
client = Client(secret=secret)
responses.add_callback(responses.POST, client.server, callback=self.call_params_callback)
# create params
params = [
[
{"methodName": client.ADD_URI, "params": ["param1", "param2"]},
{"methodName": client.ADD_URI, "params": ["param3", "param4"]},
]
]
# copy params and insert secret
expected_params = deepcopy(params)
for param in expected_params[0]:
param["params"].insert(0, f"token:{secret}")
# call function and assert result
resp = client.call(client.MULTICALL, params, insert_secret=True)
assert resp == expected_params
@responses.activate
def test_does_not_insert_secret_with_unknown_method_call(self):
# create client with secret
secret = "hello"
client = Client(secret=secret)
responses.add_callback(responses.POST, client.server, callback=self.call_params_callback)
# create params
params = ["param1", "param2"]
# call function and assert result
resp = client.call("other.method", params, insert_secret=True)
assert secret not in resp
@responses.activate
def test_does_not_insert_secret_if_told_so(self):
# create client with secret
secret = "hello"
client = Client(secret=secret)
responses.add_callback(responses.POST, client.server, callback=self.call_params_callback)
# create params
params = ["param1", "param2"]
# call function and assert result
resp = client.call("other.method", params, insert_secret=False)
assert secret not in resp
def test_client_str_returns_client_server(self):
host = "https://localhost:8779/"
port = 7100
client = Client(host, port)
assert client.server == f"{host.rstrip('/')}:{port}/jsonrpc" == str(client)
@responses.activate
def test_batch_call(self):
client = Client()
responses.add_callback(responses.POST, client.server, callback=self.batch_call_params_callback)
# create params
params_1 = ["param1", "param2"]
params_2 = ["param3", "param4"]
# copy params and insert secret
expected_params = [params_1, params_2]
# call function and assert result
resp = client.batch_call([(client.ADD_URI, params_1, 0), (client.ADD_METALINK, params_2, 1)])
assert resp == expected_params
@responses.activate
def test_insert_secret_with_batch_call(self):
# create client with secret
secret = "hello"
client = Client(secret=secret)
responses.add_callback(responses.POST, client.server, callback=self.batch_call_params_callback)
# create params
params_1 = ["param1", "param2"]
params_2 = ["param3", "param4"]
# copy params and insert secret
expected_params = [deepcopy(params_1), deepcopy(params_2)]
for p in expected_params:
p.insert(0, f"token:{secret}")
# call function and assert result
resp = client.batch_call(
[(client.ADD_URI, params_1, 0), (client.ADD_METALINK, params_2, 1)], insert_secret=True
)
assert resp == expected_params
@responses.activate
def test_multicall2(self):
client = Client()
responses.add_callback(responses.POST, client.server, callback=self.call_params_callback)
# create params
params_1 = ["0000000000000001"]
params_2 = ["2fa07b6e85c40205"]
calls = [(client.REMOVE, params_1), (client.REMOVE, params_2)]
# copy params and insert secret
expected_params = [
[
{"methodName": client.REMOVE, "params": deepcopy(params_1)},
{"methodName": client.REMOVE, "params": deepcopy(params_2)},
]
]
# call function and assert result
resp = client.multicall2(calls)
assert resp == expected_params
@responses.activate
def test_insert_secret_with_multicall2(self):
# create client with secret
secret = "hello"
client = Client(secret=secret)
responses.add_callback(responses.POST, client.server, callback=self.call_params_callback)
# create params
params_1 = ["0000000000000001"]
params_2 = ["2fa07b6e85c40205"]
calls = [(client.REMOVE, params_1), (client.REMOVE, params_2)]
# copy params and insert secret
expected_params = [
[
{"methodName": client.REMOVE, "params": deepcopy(params_1)},
{"methodName": client.REMOVE, "params": deepcopy(params_2)},
]
]
for param in expected_params[0]:
param["params"].insert(0, f"token:{secret}")
# call function and assert result
resp = client.multicall2(calls, insert_secret=True)
assert resp == expected_params
class TestClientExceptionClass:
@responses.activate
def test_call_raises_custom_error(self):
client = Client()
responses.add(
responses.POST, client.server, json={"error": {"code": 1, "message": "Custom message"}}, status=200
)
with pytest.raises(ClientException, match=r"Custom message") as e:
client.call("aria2.method")
assert e.code == 1
@responses.activate
def test_call_raises_known_error(self):
client = Client()
responses.add(
responses.POST,
client.server,
json={"error": {"code": JSONRPC_PARSER_ERROR, "message": "Custom message"}},
status=200,
)
with pytest.raises(ClientException, match=rf"{JSONRPC_CODES[JSONRPC_PARSER_ERROR]}\nCustom message") as e:
client.call("aria2.method")
assert e.code == JSONRPC_PARSER_ERROR
class TestClientClass:
def test_add_metalink_method(self, server):
# get file contents
with open(DEBIAN_METALINK, "rb") as stream:
metalink_contents = stream.read()
encoded_contents = b64encode(metalink_contents).decode("utf-8")
assert server.client.add_metalink(encoded_contents)
def test_add_torrent_method(self, server):
# get file contents
with open(BUNSENLABS_TORRENT, "rb") as stream:
torrent_contents = stream.read()
encoded_contents = b64encode(torrent_contents).decode("utf-8")
assert server.client.add_torrent(encoded_contents, [])
def test_add_uri_method(self, server):
assert server.client.add_uri([BUNSENLABS_MAGNET])
assert server.client.add_uri(XUBUNTU_MIRRORS)
def test_global_option_methods(self, tmp_path, port):
with Aria2Server(tmp_path, port, config=CONFIGS_DIR / "max-5-dls.conf") as server:
max_concurrent_downloads = server.client.get_global_option()["max-concurrent-downloads"]
assert max_concurrent_downloads == "5"
assert server.client.change_global_option({"max-concurrent-downloads": "10"}) == "OK"
max_concurrent_downloads = server.client.get_global_option()["max-concurrent-downloads"]
assert max_concurrent_downloads == "10"
def test_option_methods(self, tmp_path, port):
with Aria2Server(tmp_path, port, session="max-dl-limit-10000.txt") as server:
time.sleep(0.1)
try:
gid = server.client.tell_active(keys=["gid"])[0]["gid"]
except IndexError:
pytest.xfail("Failed to establish connection (sporadic error)")
max_download_limit = server.client.get_option(gid=gid)["max-download-limit"]
assert max_download_limit == "10000"
assert server.client.change_option(gid, {"max-download-limit": "20000"}) == "OK"
max_download_limit = server.client.get_option(gid)["max-download-limit"]
assert max_download_limit == "20000"
def test_position_method(self, tmp_path, port):
with Aria2Server(tmp_path, port, session="2-dls-paused.txt") as server:
gids = server.client.tell_waiting(0, 5, keys=["gid"])
first, second = [r["gid"] for r in gids]
assert server.client.change_position(second, 0, "POS_SET") == 0
assert server.client.change_position(second, 5, "POS_CUR") == 1
def test_change_uri_method(self, tmp_path, port):
with Aria2Server(tmp_path, port, session="1-dl-2-uris.txt") as server:
gid = server.client.tell_waiting(0, 1, keys=["gid"])[0]["gid"]
assert server.client.change_uri(gid, 1, ["http://localhost:8779/1024"], ["http://localhost:8779/1k"]) == [
1,
1,
]
assert server.client.change_uri(gid, 1, ["http://localhost:8779/1k"], []) == [1, 0]
def test_force_pause_method(self, tmp_path, port):
with Aria2Server(tmp_path, port, session="big-download.txt") as server:
time.sleep(0.1)
try:
gid = server.client.tell_active(keys=["gid"])[0]["gid"]
except IndexError:
pytest.xfail("Failed to establish connection (sporadic error)")
assert server.client.force_pause(gid) == gid
def test_force_pause_all_method(self, tmp_path, port):
with Aria2Server(tmp_path, port, session="2-dls.txt") as server:
assert server.client.force_pause_all() == "OK"
def test_force_remove_method(self, tmp_path, port):
with Aria2Server(tmp_path, port, session="big-download.txt") as server:
try:
gid = server.client.tell_active(keys=["gid"])[0]["gid"]
except IndexError:
pytest.xfail("Failed to establish connection (sporadic error)")
assert server.client.force_remove(gid)
assert server.client.tell_status(gid, keys=["status"])["status"] == "removed"
def test_force_shutdown_method(self, server):
assert server.client.force_shutdown() == "OK"
with pytest.raises(requests.ConnectionError):
for retry in range(10):
server.client.list_methods()
time.sleep(1)
def test_get_files_method(self, tmp_path, port):
with Aria2Server(tmp_path, port, session="1-dl.txt") as server:
gid = server.client.tell_active(keys=["gid"])[0]["gid"]
assert len(server.client.get_files(gid)) == 1
def test_get_global_stat_method(self, server):
assert server.client.get_global_stat()
def test_get_peers_method(self, tmp_path, port):
with Aria2Server(tmp_path, port, session="max-dl-limit-10000.txt") as server:
time.sleep(0.1)
try:
gid = server.client.tell_active(keys=["gid"])[0]["gid"]
except IndexError:
pytest.xfail("Failed to establish connection (sporadic error)")
assert not server.client.get_peers(gid)
def test_get_servers_method(self, tmp_path, port):
with Aria2Server(tmp_path, port, session="max-dl-limit-10000.txt") as server:
time.sleep(0.1)
try:
gid = server.client.tell_active(keys=["gid"])[0]["gid"]
except IndexError:
pytest.xfail("Failed to establish connection (sporadic error)")
assert server.client.get_servers(gid)
def test_get_session_info_method(self, server):
assert server.client.get_session_info()
def test_get_uris_method(self, tmp_path, port):
with Aria2Server(tmp_path, port, session="1-dl-2-uris.txt") as server:
gid = server.client.tell_waiting(0, 1, keys=["gid"])[0]["gid"]
assert server.client.get_uris(gid) == [
{"status": "waiting", "uri": "http://localhost:8779/1024"},
{"status": "waiting", "uri": "http://localhost:8779/1k"},
]
def test_get_version_method(self, server):
assert server.client.get_version()
def test_list_methods_method(self, server):
assert server.client.list_methods()
def test_list_notifications_method(self, server):
assert server.client.list_notifications()
def test_multicall_method(self, server):
assert server.client.multicall(
[[{"methodName": server.client.LIST_METHODS}, {"methodName": server.client.LIST_NOTIFICATIONS}]]
)
def test_multicall2_method(self, server):
assert server.client.multicall2([(server.client.LIST_METHODS, []), (server.client.LIST_NOTIFICATIONS, [])])
def test_pause_method(self, tmp_path, port):
with Aria2Server(tmp_path, port, session="1-dl.txt") as server:
time.sleep(0.1)
try:
gid = server.client.tell_active(keys=["gid"])[0]["gid"]
except IndexError:
pytest.xfail("Failed to establish connection (sporadic error)")
assert server.client.pause(gid) == gid
def test_pause_all_method(self, tmp_path, port):
with Aria2Server(tmp_path, port, session="2-dls.txt") as server:
assert server.client.pause_all() == "OK"
def test_purge_download_result_method(self, server):
assert server.client.purge_download_result() == "OK"
def test_remove_method(self, tmp_path, port):
with Aria2Server(tmp_path, port, session="1-dl.txt") as server:
time.sleep(0.1)
try:
gid = server.client.tell_active(keys=["gid"])[0]["gid"]
except IndexError:
pytest.xfail("Failed to establish connection (sporadic error)")
assert server.client.remove(gid)
assert server.client.tell_status(gid, keys=["status"])["status"] == "removed"
def test_remove_download_result_method(self, tmp_path, port):
with Aria2Server(tmp_path, port, session="1-dl.txt") as server:
time.sleep(0.1)
try:
gid = server.client.tell_active(keys=["gid"])[0]["gid"]
except IndexError:
pytest.xfail("Failed to establish connection (sporadic error)")
server.client.remove(gid)
assert server.client.remove_download_result(gid) == "OK"
assert len(server.client.tell_stopped(0, 1)) == 0
def test_save_session_method(self, tmp_path, port):
session_input = SESSIONS_DIR / "1-dl.txt"
with Aria2Server(tmp_path, port, session=session_input) as server:
session_output = server.tmp_dir / "_session.txt"
server.client.change_global_option({"save-session": str(session_output)})
assert server.client.save_session() == "OK"
with open(session_input) as stream:
input_contents = stream.read()
with open(session_output) as stream:
output_contents = stream.read()
for line in input_contents.split("\n"):
assert line in output_contents
def test_shutdown_method(self, server):
assert server.client.shutdown() == "OK"
with pytest.raises(requests.ConnectionError):
for retry in range(10):
server.client.list_methods()
time.sleep(1)
def test_tell_active_method(self, tmp_path, port):
with Aria2Server(tmp_path, port, session="big-download.txt") as server:
time.sleep(0.1)
if server.api.get_download("0000000000000001").has_failed:
pytest.xfail("Failed to establish connection (sporadic error)")
assert len(server.client.tell_active(keys=["gid"])) > 0
def test_tell_status_method(self, tmp_path, port):
with Aria2Server(tmp_path, port, session="1-dl-paused.txt") as server:
gid = server.client.tell_waiting(0, 1, keys=["gid"])[0]["gid"]
assert server.client.tell_status(gid)
def test_tell_stopped_method(self, tmp_path, port):
with Aria2Server(tmp_path, port, session="very-small-download.txt") as server:
download = server.api.get_download("0000000000000001")
while not download.live.is_complete:
if download.has_failed:
pytest.xfail("Failed to establish connection (sporadic error)")
time.sleep(0.1)
assert len(server.client.tell_stopped(0, 1, keys=["gid"])) > 0
def test_tell_waiting_method(self, tmp_path, port):
with Aria2Server(tmp_path, port, session="2-dls-paused.txt") as server:
assert server.client.tell_waiting(0, 5, keys=["gid"]) == [
{"gid": "0000000000000001"},
{"gid": "0000000000000002"},
]
def test_unpause_method(self, tmp_path, port):
with Aria2Server(tmp_path, port, session="1-dl-paused.txt") as server:
gid = server.client.tell_waiting(0, 1, keys=["gid"])[0]["gid"]
assert server.client.unpause(gid) == gid
def test_unpause_all_method(self, tmp_path, port):
with Aria2Server(tmp_path, port, session="2-dls-paused.txt") as server:
assert server.client.unpause_all() == "OK"
def test_listen_to_notifications_no_server(self):
client = Client(port=7035)
client.listen_to_notifications(timeout=1)
def test_listen_to_notifications_no_callbacks(self, tmp_path, port):
with Aria2Server(tmp_path, port, session="2-dls-paused.txt") as server:
def thread_target():
server.client.listen_to_notifications(timeout=1, handle_signals=False)
thread = threading.Thread(target=thread_target)
thread.start()
server.client.unpause("0000000000000001")
time.sleep(3)
thread.join()
def test_listen_to_notifications_callbacks(self, tmp_path, port, capsys):
with Aria2Server(tmp_path, port, session="2-dls-paused.txt") as server:
def thread_target():
server.client.listen_to_notifications(
on_download_start=lambda gid: print("started " + gid), timeout=1, handle_signals=False
)
thread = threading.Thread(target=thread_target)
thread.start()
time.sleep(1)
server.client.unpause("0000000000000001")
time.sleep(3)
thread.join()
assert capsys.readouterr().out == "started 0000000000000001\n"
def test_listen_to_notifications_then_stop(self, tmp_path, port):
with Aria2Server(tmp_path, port, session="2-dls-paused.txt") as server:
def thread_target():
server.client.listen_to_notifications(timeout=1, handle_signals=False)
thread = threading.Thread(target=thread_target)
thread.start()
server.client.stop_listening()
thread.join()
def test_listen_to_notifications_then_stop_with_signal(self, tmp_path, port):
with Aria2Server(tmp_path, port, session="2-dls-paused.txt") as server:
def thread_target():
time.sleep(2)
os.kill(os.getpid(), signal.SIGTERM)
thread = threading.Thread(target=thread_target)
thread.start()
server.client.listen_to_notifications(timeout=1, handle_signals=True)
thread.join()
class TestNotificationClass:
def test_init(self):
notification = Notification("random", "random")
assert notification
def test_get(self):
message = {"method": "random_event", "params": [{"gid": "random_gid"}]}
assert Notification.get_or_raise(message)
def test_raise(self):
message = {"error": {"code": 9000, "message": "it's over 9000"}}
with pytest.raises(ClientException):
Notification.get_or_raise(message)
class TestSecretToken:
def test_works_correctly_with_secret_set(self, tmp_path, port):
with Aria2Server(tmp_path, port, secret="this secret token") as server:
assert server.client.get_version()
def test_does_not_authorize_with_invalid_secret(self, tmp_path, port):
with Aria2Server(tmp_path, port, secret="this secret token") as server:
server.client.secret = "invalid secret token"
with pytest.raises(ClientException):
server.client.get_version()
|
power_monitoring.py | import random
import threading
import time
from statistics import mean
from cereal import log
from common.params import Params, put_nonblocking
from common.realtime import sec_since_boot
from selfdrive.hardware import HARDWARE
from selfdrive.swaglog import cloudlog
CAR_VOLTAGE_LOW_PASS_K = 0.091 # LPF gain for 5s tau (dt/tau / (dt/tau + 1))
# A C2 uses about 1W while idling, and 30h seens like a good shutoff for most cars
# While driving, a battery charges completely in about 30-60 minutes
CAR_BATTERY_CAPACITY_uWh = 30e6
CAR_CHARGING_RATE_W = 45
VBATT_PAUSE_CHARGING = 11.0 # Lower limit on the LPF car battery voltage
VBATT_INSTANT_PAUSE_CHARGING = 7.0 # Lower limit on the instant car battery voltage measurements to avoid triggering on instant power loss
MAX_TIME_OFFROAD_S = 30*3600
MIN_ON_TIME_S = 3600
class PowerMonitoring:
def __init__(self):
self.params = Params()
self.last_measurement_time = None # Used for integration delta
self.last_save_time = 0 # Used for saving current value in a param
self.power_used_uWh = 0 # Integrated power usage in uWh since going into offroad
self.next_pulsed_measurement_time = None
self.car_voltage_mV = 12e3 # Low-passed version of pandaState voltage
self.car_voltage_instant_mV = 12e3 # Last value of pandaState voltage
self.integration_lock = threading.Lock()
car_battery_capacity_uWh = self.params.get("CarBatteryCapacity")
if car_battery_capacity_uWh is None:
car_battery_capacity_uWh = 0
# Reset capacity if it's low
self.car_battery_capacity_uWh = max((CAR_BATTERY_CAPACITY_uWh / 10), int(car_battery_capacity_uWh))
# Calculation tick
def calculate(self, pandaState):
try:
now = sec_since_boot()
# If pandaState is None, we're probably not in a car, so we don't care
if pandaState is None or pandaState.pandaState.pandaType == log.PandaState.PandaType.unknown:
with self.integration_lock:
self.last_measurement_time = None
self.next_pulsed_measurement_time = None
self.power_used_uWh = 0
return
# Low-pass battery voltage
self.car_voltage_instant_mV = pandaState.pandaState.voltage
self.car_voltage_mV = ((pandaState.pandaState.voltage * CAR_VOLTAGE_LOW_PASS_K) + (self.car_voltage_mV * (1 - CAR_VOLTAGE_LOW_PASS_K)))
# Cap the car battery power and save it in a param every 10-ish seconds
self.car_battery_capacity_uWh = max(self.car_battery_capacity_uWh, 0)
self.car_battery_capacity_uWh = min(self.car_battery_capacity_uWh, CAR_BATTERY_CAPACITY_uWh)
if now - self.last_save_time >= 10:
put_nonblocking("CarBatteryCapacity", str(int(self.car_battery_capacity_uWh)))
self.last_save_time = now
# First measurement, set integration time
with self.integration_lock:
if self.last_measurement_time is None:
self.last_measurement_time = now
return
if (pandaState.pandaState.ignitionLine or pandaState.pandaState.ignitionCan):
# If there is ignition, we integrate the charging rate of the car
with self.integration_lock:
self.power_used_uWh = 0
integration_time_h = (now - self.last_measurement_time) / 3600
if integration_time_h < 0:
raise ValueError(f"Negative integration time: {integration_time_h}h")
self.car_battery_capacity_uWh += (CAR_CHARGING_RATE_W * 1e6 * integration_time_h)
self.last_measurement_time = now
else:
# No ignition, we integrate the offroad power used by the device
is_uno = pandaState.pandaState.pandaType == log.PandaState.PandaType.uno
# Get current power draw somehow
current_power = HARDWARE.get_current_power_draw() # pylint: disable=assignment-from-none
if current_power is not None:
pass
elif HARDWARE.get_battery_status() == 'Discharging':
# If the battery is discharging, we can use this measurement
# On C2: this is low by about 10-15%, probably mostly due to UNO draw not being factored in
current_power = ((HARDWARE.get_battery_voltage() / 1000000) * (HARDWARE.get_battery_current() / 1000000))
elif (self.next_pulsed_measurement_time is not None) and (self.next_pulsed_measurement_time <= now):
# TODO: Figure out why this is off by a factor of 3/4???
FUDGE_FACTOR = 1.33
# Turn off charging for about 10 sec in a thread that does not get killed on SIGINT, and perform measurement here to avoid blocking thermal
def perform_pulse_measurement(now):
try:
HARDWARE.set_battery_charging(False)
time.sleep(5)
# Measure for a few sec to get a good average
voltages = []
currents = []
for _ in range(6):
voltages.append(HARDWARE.get_battery_voltage())
currents.append(HARDWARE.get_battery_current())
time.sleep(1)
current_power = ((mean(voltages) / 1000000) * (mean(currents) / 1000000))
self._perform_integration(now, current_power * FUDGE_FACTOR)
# Enable charging again
HARDWARE.set_battery_charging(True)
except Exception:
cloudlog.exception("Pulsed power measurement failed")
# Start pulsed measurement and return
threading.Thread(target=perform_pulse_measurement, args=(now,)).start()
self.next_pulsed_measurement_time = None
return
elif self.next_pulsed_measurement_time is None and not is_uno:
# On a charging EON with black panda, or drawing more than 400mA out of a white/grey one
# Only way to get the power draw is to turn off charging for a few sec and check what the discharging rate is
# We shouldn't do this very often, so make sure it has been some long-ish random time interval
self.next_pulsed_measurement_time = now + random.randint(120, 180)
return
else:
# Do nothing
return
# Do the integration
self._perform_integration(now, current_power)
except Exception:
cloudlog.exception("Power monitoring calculation failed")
def _perform_integration(self, t, current_power):
with self.integration_lock:
try:
if self.last_measurement_time:
integration_time_h = (t - self.last_measurement_time) / 3600
power_used = (current_power * 1000000) * integration_time_h
if power_used < 0:
raise ValueError(f"Negative power used! Integration time: {integration_time_h} h Current Power: {power_used} uWh")
self.power_used_uWh += power_used
self.car_battery_capacity_uWh -= power_used
self.last_measurement_time = t
except Exception:
cloudlog.exception("Integration failed")
# Get the power usage
def get_power_used(self):
return int(self.power_used_uWh)
def get_car_battery_capacity(self):
return int(self.car_battery_capacity_uWh)
# See if we need to disable charging
def should_disable_charging(self, pandaState, offroad_timestamp):
if pandaState is None or offroad_timestamp is None:
return False
now = sec_since_boot()
disable_charging = False
disable_charging |= (now - offroad_timestamp) > MAX_TIME_OFFROAD_S
disable_charging |= (self.car_voltage_mV < (VBATT_PAUSE_CHARGING * 1e3)) and (self.car_voltage_instant_mV > (VBATT_INSTANT_PAUSE_CHARGING * 1e3))
disable_charging |= (self.car_battery_capacity_uWh <= 0)
disable_charging &= (not pandaState.pandaState.ignitionLine and not pandaState.pandaState.ignitionCan)
disable_charging &= (not self.params.get_bool("DisablePowerDown"))
disable_charging |= self.params.get_bool("ForcePowerDown")
return disable_charging
# See if we need to shutdown
def should_shutdown(self, pandaState, offroad_timestamp, started_seen):
if pandaState is None or offroad_timestamp is None:
return False
now = sec_since_boot()
panda_charging = (pandaState.pandaState.usbPowerMode != log.PandaState.UsbPowerMode.client)
BATT_PERC_OFF = 10
should_shutdown = False
# Wait until we have shut down charging before powering down
should_shutdown |= (not panda_charging and self.should_disable_charging(pandaState, offroad_timestamp))
should_shutdown |= ((HARDWARE.get_battery_capacity() < BATT_PERC_OFF) and (not HARDWARE.get_battery_charging()) and ((now - offroad_timestamp) > 60))
should_shutdown &= started_seen or (now > MIN_ON_TIME_S)
return should_shutdown
|
monitornator.py | #!/usr/bin/env python3
agent_version="___AGENT_VERSION___"
from urllib.parse import urlencode
from urllib.request import Request, urlopen
from pathlib import Path
import argparse, sys
import datetime
import psutil
import time, threading
import configparser
config_file_path="/etc/monitornator/monitornator.config"
# Check if config file is present
config_file = Path(config_file_path)
if not config_file.is_file():
print('Config file missing!')
sys.exit(1)
config = configparser.ConfigParser()
config.read(config_file_path)
host=''
token=''
server_id=''
if config.has_option('monitornator', 'server_id'):
server_id = config.get('monitornator', 'server_id')
if config.has_option('monitornator', 'token'):
token = config.get('monitornator', 'token')
if config.has_option('monitornator', 'host'):
host = config.get('monitornator', 'host')
StartTime=time.time()
if not host:
host = 'https://collector.monitornator.io'
if not token:
print('token is required in monitornator.config, see -h for more info')
sys.exit(1)
if not server_id:
print('server_id is required in monitornator.config, see -h for more info')
sys.exit(1)
url = host + '/measurements'
headers = {'authorization': token }
def action() :
post_fields = {
'time': datetime.datetime.utcnow().replace(microsecond=0).isoformat() + 'Z',
'load': psutil.cpu_percent(interval=1, percpu=False),
'memory': psutil.virtual_memory().percent,
'disk': psutil.disk_usage('/').percent,
'agentVersion': agent_version,
'serverId': server_id
}
request = Request(url, urlencode(post_fields).encode(), headers=headers)
# TODO Handle errors
json = urlopen(request).read().decode()
print('update ! -> time : {:.1f}s'.format(time.time()-StartTime))
class setInterval :
def __init__(self,interval,action) :
self.interval=interval
self.action=action
self.stopEvent=threading.Event()
thread=threading.Thread(target=self.__setInterval)
thread.start()
def __setInterval(self) :
nextTime=time.time()+self.interval
while not self.stopEvent.wait(nextTime-time.time()) :
nextTime+=self.interval
self.action()
def cancel(self) :
self.stopEvent.set()
inter=setInterval(10.0, action)
print('just after setInterval -> time : {:.1f}s'.format(time.time()-StartTime))
|
celery_command.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 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,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""Celery command"""
import sys
from multiprocessing import Process
from typing import Optional
import daemon
import psutil
import sqlalchemy.exc
from celery import maybe_patch_concurrency
from celery.bin import worker as worker_bin
from daemon.pidfile import TimeoutPIDLockFile
from flower.command import FlowerCommand
from lockfile.pidlockfile import read_pid_from_pidfile, remove_existing_pidfile
from airflow import settings
from airflow.configuration import conf
from airflow.executors.celery_executor import app as celery_app
from airflow.utils import cli as cli_utils
from airflow.utils.cli import setup_locations, setup_logging
from airflow.utils.serve_logs import serve_logs
WORKER_PROCESS_NAME = "worker"
@cli_utils.action_logging
def flower(args):
"""Starts Flower, Celery monitoring tool"""
options = [
conf.get('celery', 'BROKER_URL'),
f"--address={args.hostname}",
f"--port={args.port}",
]
if args.broker_api:
options.append(f"--broker-api={args.broker_api}")
if args.url_prefix:
options.append(f"--url-prefix={args.url_prefix}")
if args.basic_auth:
options.append(f"--basic-auth={args.basic_auth}")
if args.flower_conf:
options.append(f"--conf={args.flower_conf}")
flower_cmd = FlowerCommand()
if args.daemon:
pidfile, stdout, stderr, _ = setup_locations(
process="flower",
pid=args.pid,
stdout=args.stdout,
stderr=args.stderr,
log=args.log_file,
)
with open(stdout, "w+") as stdout, open(stderr, "w+") as stderr:
ctx = daemon.DaemonContext(
pidfile=TimeoutPIDLockFile(pidfile, -1),
stdout=stdout,
stderr=stderr,
)
with ctx:
flower_cmd.execute_from_commandline(argv=options)
else:
flower_cmd.execute_from_commandline(argv=options)
def _serve_logs(skip_serve_logs: bool = False) -> Optional[Process]:
"""Starts serve_logs sub-process"""
if skip_serve_logs is False:
sub_proc = Process(target=serve_logs)
sub_proc.start()
return sub_proc
return None
@cli_utils.action_logging
def worker(args):
"""Starts Airflow Celery worker"""
if not settings.validate_session():
print("Worker exiting... database connection precheck failed! ")
sys.exit(1)
autoscale = args.autoscale
skip_serve_logs = args.skip_serve_logs
if autoscale is None and conf.has_option("celery", "worker_autoscale"):
autoscale = conf.get("celery", "worker_autoscale")
# Setup locations
pid_file_path, stdout, stderr, log_file = setup_locations(
process=WORKER_PROCESS_NAME,
pid=args.pid,
stdout=args.stdout,
stderr=args.stderr,
log=args.log_file,
)
if hasattr(celery_app.backend, 'ResultSession'):
# Pre-create the database tables now, otherwise SQLA via Celery has a
# race condition where one of the subprocesses can die with "Table
# already exists" error, because SQLA checks for which tables exist,
# then issues a CREATE TABLE, rather than doing CREATE TABLE IF NOT
# EXISTS
try:
session = celery_app.backend.ResultSession()
session.close()
except sqlalchemy.exc.IntegrityError:
# At least on postgres, trying to create a table that already exist
# gives a unique constraint violation or the
# "pg_type_typname_nsp_index" table. If this happens we can ignore
# it, we raced to create the tables and lost.
pass
# Setup Celery worker
worker_instance = worker_bin.worker(app=celery_app)
options = {
'optimization': 'fair',
'O': 'fair',
'queues': args.queues,
'concurrency': args.concurrency,
'autoscale': autoscale,
'hostname': args.celery_hostname,
'loglevel': conf.get('logging', 'LOGGING_LEVEL'),
'pidfile': pid_file_path,
}
if conf.has_option("celery", "pool"):
pool = conf.get("celery", "pool")
options["pool"] = pool
# Celery pools of type eventlet and gevent use greenlets, which
# requires monkey patching the app:
# https://eventlet.net/doc/patching.html#monkey-patch
# Otherwise task instances hang on the workers and are never
# executed.
maybe_patch_concurrency(['-P', pool])
if args.daemon:
# Run Celery worker as daemon
handle = setup_logging(log_file)
stdout = open(stdout, 'w+')
stderr = open(stderr, 'w+')
if args.umask:
umask = args.umask
ctx = daemon.DaemonContext(
files_preserve=[handle],
umask=int(umask, 8),
stdout=stdout,
stderr=stderr,
)
with ctx:
sub_proc = _serve_logs(skip_serve_logs)
worker_instance.run(**options)
stdout.close()
stderr.close()
else:
# Run Celery worker in the same process
sub_proc = _serve_logs(skip_serve_logs)
worker_instance.run(**options)
if sub_proc:
sub_proc.terminate()
@cli_utils.action_logging
def stop_worker(args): # pylint: disable=unused-argument
"""Sends SIGTERM to Celery worker"""
# Read PID from file
pid_file_path, _, _, _ = setup_locations(process=WORKER_PROCESS_NAME)
pid = read_pid_from_pidfile(pid_file_path)
# Send SIGTERM
if pid:
worker_process = psutil.Process(pid)
worker_process.terminate()
# Remove pid file
remove_existing_pidfile(pid_file_path)
|
demo3.py | # -*- coding: utf-8 -*-
import threading
import time
import schedule
def job():
print("runing on thread {}".format(threading.current_thread()))
def run_threaded(job_func):
job_thread = threading.Thread(target=job_func)
job_thread.start()
schedule.every(5).seconds.do(run_threaded, job)
schedule.every(5).seconds.do(run_threaded, job)
schedule.every(5).seconds.do(run_threaded, job)
schedule.every(5).seconds.do(run_threaded, job)
schedule.every(5).seconds.do(run_threaded, job)
while 1:
schedule.run_pending()
time.sleep(1)
|
_test_multiprocessing.py | #
# Unit tests for the multiprocessing package
#
import unittest
import unittest.mock
import queue as pyqueue
import time
import io
import itertools
import sys
import os
import gc
import errno
import signal
import array
import socket
import random
import logging
import struct
import operator
import weakref
import warnings
import test.support
import test.support.script_helper
from test import support
# Skip tests if _multiprocessing wasn't built.
_multiprocessing = test.support.import_module('_multiprocessing')
# Skip tests if sem_open implementation is broken.
test.support.import_module('multiprocessing.synchronize')
import threading
import multiprocessing.connection
import multiprocessing.dummy
import multiprocessing.heap
import multiprocessing.managers
import multiprocessing.pool
import multiprocessing.queues
from multiprocessing import util
try:
from multiprocessing import reduction
HAS_REDUCTION = reduction.HAVE_SEND_HANDLE
except ImportError:
HAS_REDUCTION = False
try:
from multiprocessing.sharedctypes import Value, copy
HAS_SHAREDCTYPES = True
except ImportError:
HAS_SHAREDCTYPES = False
try:
import msvcrt
except ImportError:
msvcrt = None
#
#
#
# Timeout to wait until a process completes
TIMEOUT = 30.0 # seconds
def latin(s):
return s.encode('latin')
def close_queue(queue):
if isinstance(queue, multiprocessing.queues.Queue):
queue.close()
queue.join_thread()
def join_process(process):
# Since multiprocessing.Process has the same API than threading.Thread
# (join() and is_alive(), the support function can be reused
support.join_thread(process, timeout=TIMEOUT)
#
# Constants
#
LOG_LEVEL = util.SUBWARNING
#LOG_LEVEL = logging.DEBUG
DELTA = 0.1
CHECK_TIMINGS = False # making true makes tests take a lot longer
# and can sometimes cause some non-serious
# failures because some calls block a bit
# longer than expected
if CHECK_TIMINGS:
TIMEOUT1, TIMEOUT2, TIMEOUT3 = 0.82, 0.35, 1.4
else:
TIMEOUT1, TIMEOUT2, TIMEOUT3 = 0.1, 0.1, 0.1
HAVE_GETVALUE = not getattr(_multiprocessing,
'HAVE_BROKEN_SEM_GETVALUE', False)
WIN32 = (sys.platform == "win32")
from multiprocessing.connection import wait
def wait_for_handle(handle, timeout):
if timeout is not None and timeout < 0.0:
timeout = None
return wait([handle], timeout)
try:
MAXFD = os.sysconf("SC_OPEN_MAX")
except:
MAXFD = 256
# To speed up tests when using the forkserver, we can preload these:
PRELOAD = ['__main__', 'test.test_multiprocessing_forkserver']
#
# Some tests require ctypes
#
try:
from ctypes import Structure, c_int, c_double, c_longlong
except ImportError:
Structure = object
c_int = c_double = c_longlong = None
def check_enough_semaphores():
"""Check that the system supports enough semaphores to run the test."""
# minimum number of semaphores available according to POSIX
nsems_min = 256
try:
nsems = os.sysconf("SC_SEM_NSEMS_MAX")
except (AttributeError, ValueError):
# sysconf not available or setting not available
return
if nsems == -1 or nsems >= nsems_min:
return
raise unittest.SkipTest("The OS doesn't support enough semaphores "
"to run the test (required: %d)." % nsems_min)
#
# Creates a wrapper for a function which records the time it takes to finish
#
class TimingWrapper(object):
def __init__(self, func):
self.func = func
self.elapsed = None
def __call__(self, *args, **kwds):
t = time.monotonic()
try:
return self.func(*args, **kwds)
finally:
self.elapsed = time.monotonic() - t
#
# Base class for test cases
#
class BaseTestCase(object):
ALLOWED_TYPES = ('processes', 'manager', 'threads')
def assertTimingAlmostEqual(self, a, b):
if CHECK_TIMINGS:
self.assertAlmostEqual(a, b, 1)
def assertReturnsIfImplemented(self, value, func, *args):
try:
res = func(*args)
except NotImplementedError:
pass
else:
return self.assertEqual(value, res)
# For the sanity of Windows users, rather than crashing or freezing in
# multiple ways.
def __reduce__(self, *args):
raise NotImplementedError("shouldn't try to pickle a test case")
__reduce_ex__ = __reduce__
#
# Return the value of a semaphore
#
def get_value(self):
try:
return self.get_value()
except AttributeError:
try:
return self._Semaphore__value
except AttributeError:
try:
return self._value
except AttributeError:
raise NotImplementedError
#
# Testcases
#
class DummyCallable:
def __call__(self, q, c):
assert isinstance(c, DummyCallable)
q.put(5)
class _TestProcess(BaseTestCase):
ALLOWED_TYPES = ('processes', 'threads')
def test_current(self):
if self.TYPE == 'threads':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
current = self.current_process()
authkey = current.authkey
self.assertTrue(current.is_alive())
self.assertTrue(not current.daemon)
self.assertIsInstance(authkey, bytes)
self.assertTrue(len(authkey) > 0)
self.assertEqual(current.ident, os.getpid())
self.assertEqual(current.exitcode, None)
def test_daemon_argument(self):
if self.TYPE == "threads":
self.skipTest('test not appropriate for {}'.format(self.TYPE))
# By default uses the current process's daemon flag.
proc0 = self.Process(target=self._test)
self.assertEqual(proc0.daemon, self.current_process().daemon)
proc1 = self.Process(target=self._test, daemon=True)
self.assertTrue(proc1.daemon)
proc2 = self.Process(target=self._test, daemon=False)
self.assertFalse(proc2.daemon)
@classmethod
def _test(cls, q, *args, **kwds):
current = cls.current_process()
q.put(args)
q.put(kwds)
q.put(current.name)
if cls.TYPE != 'threads':
q.put(bytes(current.authkey))
q.put(current.pid)
def test_process(self):
q = self.Queue(1)
e = self.Event()
args = (q, 1, 2)
kwargs = {'hello':23, 'bye':2.54}
name = 'SomeProcess'
p = self.Process(
target=self._test, args=args, kwargs=kwargs, name=name
)
p.daemon = True
current = self.current_process()
if self.TYPE != 'threads':
self.assertEqual(p.authkey, current.authkey)
self.assertEqual(p.is_alive(), False)
self.assertEqual(p.daemon, True)
self.assertNotIn(p, self.active_children())
self.assertTrue(type(self.active_children()) is list)
self.assertEqual(p.exitcode, None)
p.start()
self.assertEqual(p.exitcode, None)
self.assertEqual(p.is_alive(), True)
self.assertIn(p, self.active_children())
self.assertEqual(q.get(), args[1:])
self.assertEqual(q.get(), kwargs)
self.assertEqual(q.get(), p.name)
if self.TYPE != 'threads':
self.assertEqual(q.get(), current.authkey)
self.assertEqual(q.get(), p.pid)
p.join()
self.assertEqual(p.exitcode, 0)
self.assertEqual(p.is_alive(), False)
self.assertNotIn(p, self.active_children())
close_queue(q)
@classmethod
def _sleep_some(cls):
time.sleep(100)
@classmethod
def _test_sleep(cls, delay):
time.sleep(delay)
def _kill_process(self, meth):
if self.TYPE == 'threads':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
p = self.Process(target=self._sleep_some)
p.daemon = True
p.start()
self.assertEqual(p.is_alive(), True)
self.assertIn(p, self.active_children())
self.assertEqual(p.exitcode, None)
join = TimingWrapper(p.join)
self.assertEqual(join(0), None)
self.assertTimingAlmostEqual(join.elapsed, 0.0)
self.assertEqual(p.is_alive(), True)
self.assertEqual(join(-1), None)
self.assertTimingAlmostEqual(join.elapsed, 0.0)
self.assertEqual(p.is_alive(), True)
# XXX maybe terminating too soon causes the problems on Gentoo...
time.sleep(1)
meth(p)
if hasattr(signal, 'alarm'):
# On the Gentoo buildbot waitpid() often seems to block forever.
# We use alarm() to interrupt it if it blocks for too long.
def handler(*args):
raise RuntimeError('join took too long: %s' % p)
old_handler = signal.signal(signal.SIGALRM, handler)
try:
signal.alarm(10)
self.assertEqual(join(), None)
finally:
signal.alarm(0)
signal.signal(signal.SIGALRM, old_handler)
else:
self.assertEqual(join(), None)
self.assertTimingAlmostEqual(join.elapsed, 0.0)
self.assertEqual(p.is_alive(), False)
self.assertNotIn(p, self.active_children())
p.join()
return p.exitcode
def test_terminate(self):
exitcode = self._kill_process(multiprocessing.Process.terminate)
if os.name != 'nt':
self.assertEqual(exitcode, -signal.SIGTERM)
def test_kill(self):
exitcode = self._kill_process(multiprocessing.Process.kill)
if os.name != 'nt':
self.assertEqual(exitcode, -signal.SIGKILL)
def test_cpu_count(self):
try:
cpus = multiprocessing.cpu_count()
except NotImplementedError:
cpus = 1
self.assertTrue(type(cpus) is int)
self.assertTrue(cpus >= 1)
def test_active_children(self):
self.assertEqual(type(self.active_children()), list)
p = self.Process(target=time.sleep, args=(DELTA,))
self.assertNotIn(p, self.active_children())
p.daemon = True
p.start()
self.assertIn(p, self.active_children())
p.join()
self.assertNotIn(p, self.active_children())
@classmethod
def _test_recursion(cls, wconn, id):
wconn.send(id)
if len(id) < 2:
for i in range(2):
p = cls.Process(
target=cls._test_recursion, args=(wconn, id+[i])
)
p.start()
p.join()
def test_recursion(self):
rconn, wconn = self.Pipe(duplex=False)
self._test_recursion(wconn, [])
time.sleep(DELTA)
result = []
while rconn.poll():
result.append(rconn.recv())
expected = [
[],
[0],
[0, 0],
[0, 1],
[1],
[1, 0],
[1, 1]
]
self.assertEqual(result, expected)
@classmethod
def _test_sentinel(cls, event):
event.wait(10.0)
def test_sentinel(self):
if self.TYPE == "threads":
self.skipTest('test not appropriate for {}'.format(self.TYPE))
event = self.Event()
p = self.Process(target=self._test_sentinel, args=(event,))
with self.assertRaises(ValueError):
p.sentinel
p.start()
self.addCleanup(p.join)
sentinel = p.sentinel
self.assertIsInstance(sentinel, int)
self.assertFalse(wait_for_handle(sentinel, timeout=0.0))
event.set()
p.join()
self.assertTrue(wait_for_handle(sentinel, timeout=1))
@classmethod
def _test_close(cls, rc=0, q=None):
if q is not None:
q.get()
sys.exit(rc)
def test_close(self):
if self.TYPE == "threads":
self.skipTest('test not appropriate for {}'.format(self.TYPE))
q = self.Queue()
p = self.Process(target=self._test_close, kwargs={'q': q})
p.daemon = True
p.start()
self.assertEqual(p.is_alive(), True)
# Child is still alive, cannot close
with self.assertRaises(ValueError):
p.close()
q.put(None)
p.join()
self.assertEqual(p.is_alive(), False)
self.assertEqual(p.exitcode, 0)
p.close()
with self.assertRaises(ValueError):
p.is_alive()
with self.assertRaises(ValueError):
p.join()
with self.assertRaises(ValueError):
p.terminate()
p.close()
wr = weakref.ref(p)
del p
gc.collect()
self.assertIs(wr(), None)
close_queue(q)
def test_many_processes(self):
if self.TYPE == 'threads':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
sm = multiprocessing.get_start_method()
N = 5 if sm == 'spawn' else 100
# Try to overwhelm the forkserver loop with events
procs = [self.Process(target=self._test_sleep, args=(0.01,))
for i in range(N)]
for p in procs:
p.start()
for p in procs:
join_process(p)
for p in procs:
self.assertEqual(p.exitcode, 0)
procs = [self.Process(target=self._sleep_some)
for i in range(N)]
for p in procs:
p.start()
time.sleep(0.001) # let the children start...
for p in procs:
p.terminate()
for p in procs:
join_process(p)
if os.name != 'nt':
exitcodes = [-signal.SIGTERM]
if sys.platform == 'darwin':
# bpo-31510: On macOS, killing a freshly started process with
# SIGTERM sometimes kills the process with SIGKILL.
exitcodes.append(-signal.SIGKILL)
for p in procs:
self.assertIn(p.exitcode, exitcodes)
def test_lose_target_ref(self):
c = DummyCallable()
wr = weakref.ref(c)
q = self.Queue()
p = self.Process(target=c, args=(q, c))
del c
p.start()
p.join()
self.assertIs(wr(), None)
self.assertEqual(q.get(), 5)
close_queue(q)
@classmethod
def _test_child_fd_inflation(self, evt, q):
q.put(test.support.fd_count())
evt.wait()
def test_child_fd_inflation(self):
# Number of fds in child processes should not grow with the
# number of running children.
if self.TYPE == 'threads':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
sm = multiprocessing.get_start_method()
if sm == 'fork':
# The fork method by design inherits all fds from the parent,
# trying to go against it is a lost battle
self.skipTest('test not appropriate for {}'.format(sm))
N = 5
evt = self.Event()
q = self.Queue()
procs = [self.Process(target=self._test_child_fd_inflation, args=(evt, q))
for i in range(N)]
for p in procs:
p.start()
try:
fd_counts = [q.get() for i in range(N)]
self.assertEqual(len(set(fd_counts)), 1, fd_counts)
finally:
evt.set()
for p in procs:
p.join()
close_queue(q)
@classmethod
def _test_wait_for_threads(self, evt):
def func1():
time.sleep(0.5)
evt.set()
def func2():
time.sleep(20)
evt.clear()
threading.Thread(target=func1).start()
threading.Thread(target=func2, daemon=True).start()
def test_wait_for_threads(self):
# A child process should wait for non-daemonic threads to end
# before exiting
if self.TYPE == 'threads':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
evt = self.Event()
proc = self.Process(target=self._test_wait_for_threads, args=(evt,))
proc.start()
proc.join()
self.assertTrue(evt.is_set())
@classmethod
def _test_error_on_stdio_flush(self, evt, break_std_streams={}):
for stream_name, action in break_std_streams.items():
if action == 'close':
stream = io.StringIO()
stream.close()
else:
assert action == 'remove'
stream = None
setattr(sys, stream_name, None)
evt.set()
def test_error_on_stdio_flush_1(self):
# Check that Process works with broken standard streams
streams = [io.StringIO(), None]
streams[0].close()
for stream_name in ('stdout', 'stderr'):
for stream in streams:
old_stream = getattr(sys, stream_name)
setattr(sys, stream_name, stream)
try:
evt = self.Event()
proc = self.Process(target=self._test_error_on_stdio_flush,
args=(evt,))
proc.start()
proc.join()
self.assertTrue(evt.is_set())
self.assertEqual(proc.exitcode, 0)
finally:
setattr(sys, stream_name, old_stream)
def test_error_on_stdio_flush_2(self):
# Same as test_error_on_stdio_flush_1(), but standard streams are
# broken by the child process
for stream_name in ('stdout', 'stderr'):
for action in ('close', 'remove'):
old_stream = getattr(sys, stream_name)
try:
evt = self.Event()
proc = self.Process(target=self._test_error_on_stdio_flush,
args=(evt, {stream_name: action}))
proc.start()
proc.join()
self.assertTrue(evt.is_set())
self.assertEqual(proc.exitcode, 0)
finally:
setattr(sys, stream_name, old_stream)
@classmethod
def _sleep_and_set_event(self, evt, delay=0.0):
time.sleep(delay)
evt.set()
def check_forkserver_death(self, signum):
# bpo-31308: if the forkserver process has died, we should still
# be able to create and run new Process instances (the forkserver
# is implicitly restarted).
if self.TYPE == 'threads':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
sm = multiprocessing.get_start_method()
if sm != 'forkserver':
# The fork method by design inherits all fds from the parent,
# trying to go against it is a lost battle
self.skipTest('test not appropriate for {}'.format(sm))
from multiprocessing.forkserver import _forkserver
_forkserver.ensure_running()
# First process sleeps 500 ms
delay = 0.5
evt = self.Event()
proc = self.Process(target=self._sleep_and_set_event, args=(evt, delay))
proc.start()
pid = _forkserver._forkserver_pid
os.kill(pid, signum)
# give time to the fork server to die and time to proc to complete
time.sleep(delay * 2.0)
evt2 = self.Event()
proc2 = self.Process(target=self._sleep_and_set_event, args=(evt2,))
proc2.start()
proc2.join()
self.assertTrue(evt2.is_set())
self.assertEqual(proc2.exitcode, 0)
proc.join()
self.assertTrue(evt.is_set())
self.assertIn(proc.exitcode, (0, 255))
def test_forkserver_sigint(self):
# Catchable signal
self.check_forkserver_death(signal.SIGINT)
def test_forkserver_sigkill(self):
# Uncatchable signal
if os.name != 'nt':
self.check_forkserver_death(signal.SIGKILL)
#
#
#
class _UpperCaser(multiprocessing.Process):
def __init__(self):
multiprocessing.Process.__init__(self)
self.child_conn, self.parent_conn = multiprocessing.Pipe()
def run(self):
self.parent_conn.close()
for s in iter(self.child_conn.recv, None):
self.child_conn.send(s.upper())
self.child_conn.close()
def submit(self, s):
assert type(s) is str
self.parent_conn.send(s)
return self.parent_conn.recv()
def stop(self):
self.parent_conn.send(None)
self.parent_conn.close()
self.child_conn.close()
class _TestSubclassingProcess(BaseTestCase):
ALLOWED_TYPES = ('processes',)
def test_subclassing(self):
uppercaser = _UpperCaser()
uppercaser.daemon = True
uppercaser.start()
self.assertEqual(uppercaser.submit('hello'), 'HELLO')
self.assertEqual(uppercaser.submit('world'), 'WORLD')
uppercaser.stop()
uppercaser.join()
def test_stderr_flush(self):
# sys.stderr is flushed at process shutdown (issue #13812)
if self.TYPE == "threads":
self.skipTest('test not appropriate for {}'.format(self.TYPE))
testfn = test.support.TESTFN
self.addCleanup(test.support.unlink, testfn)
proc = self.Process(target=self._test_stderr_flush, args=(testfn,))
proc.start()
proc.join()
with open(testfn, 'r') as f:
err = f.read()
# The whole traceback was printed
self.assertIn("ZeroDivisionError", err)
self.assertIn("test_multiprocessing.py", err)
self.assertIn("1/0 # MARKER", err)
@classmethod
def _test_stderr_flush(cls, testfn):
fd = os.open(testfn, os.O_WRONLY | os.O_CREAT | os.O_EXCL)
sys.stderr = open(fd, 'w', closefd=False)
1/0 # MARKER
@classmethod
def _test_sys_exit(cls, reason, testfn):
fd = os.open(testfn, os.O_WRONLY | os.O_CREAT | os.O_EXCL)
sys.stderr = open(fd, 'w', closefd=False)
sys.exit(reason)
def test_sys_exit(self):
# See Issue 13854
if self.TYPE == 'threads':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
testfn = test.support.TESTFN
self.addCleanup(test.support.unlink, testfn)
for reason in (
[1, 2, 3],
'ignore this',
):
p = self.Process(target=self._test_sys_exit, args=(reason, testfn))
p.daemon = True
p.start()
join_process(p)
self.assertEqual(p.exitcode, 1)
with open(testfn, 'r') as f:
content = f.read()
self.assertEqual(content.rstrip(), str(reason))
os.unlink(testfn)
for reason in (True, False, 8):
p = self.Process(target=sys.exit, args=(reason,))
p.daemon = True
p.start()
join_process(p)
self.assertEqual(p.exitcode, reason)
#
#
#
def queue_empty(q):
if hasattr(q, 'empty'):
return q.empty()
else:
return q.qsize() == 0
def queue_full(q, maxsize):
if hasattr(q, 'full'):
return q.full()
else:
return q.qsize() == maxsize
class _TestQueue(BaseTestCase):
@classmethod
def _test_put(cls, queue, child_can_start, parent_can_continue):
child_can_start.wait()
for i in range(6):
queue.get()
parent_can_continue.set()
def test_put(self):
MAXSIZE = 6
queue = self.Queue(maxsize=MAXSIZE)
child_can_start = self.Event()
parent_can_continue = self.Event()
proc = self.Process(
target=self._test_put,
args=(queue, child_can_start, parent_can_continue)
)
proc.daemon = True
proc.start()
self.assertEqual(queue_empty(queue), True)
self.assertEqual(queue_full(queue, MAXSIZE), False)
queue.put(1)
queue.put(2, True)
queue.put(3, True, None)
queue.put(4, False)
queue.put(5, False, None)
queue.put_nowait(6)
# the values may be in buffer but not yet in pipe so sleep a bit
time.sleep(DELTA)
self.assertEqual(queue_empty(queue), False)
self.assertEqual(queue_full(queue, MAXSIZE), True)
put = TimingWrapper(queue.put)
put_nowait = TimingWrapper(queue.put_nowait)
self.assertRaises(pyqueue.Full, put, 7, False)
self.assertTimingAlmostEqual(put.elapsed, 0)
self.assertRaises(pyqueue.Full, put, 7, False, None)
self.assertTimingAlmostEqual(put.elapsed, 0)
self.assertRaises(pyqueue.Full, put_nowait, 7)
self.assertTimingAlmostEqual(put_nowait.elapsed, 0)
self.assertRaises(pyqueue.Full, put, 7, True, TIMEOUT1)
self.assertTimingAlmostEqual(put.elapsed, TIMEOUT1)
self.assertRaises(pyqueue.Full, put, 7, False, TIMEOUT2)
self.assertTimingAlmostEqual(put.elapsed, 0)
self.assertRaises(pyqueue.Full, put, 7, True, timeout=TIMEOUT3)
self.assertTimingAlmostEqual(put.elapsed, TIMEOUT3)
child_can_start.set()
parent_can_continue.wait()
self.assertEqual(queue_empty(queue), True)
self.assertEqual(queue_full(queue, MAXSIZE), False)
proc.join()
close_queue(queue)
@classmethod
def _test_get(cls, queue, child_can_start, parent_can_continue):
child_can_start.wait()
#queue.put(1)
queue.put(2)
queue.put(3)
queue.put(4)
queue.put(5)
parent_can_continue.set()
def test_get(self):
queue = self.Queue()
child_can_start = self.Event()
parent_can_continue = self.Event()
proc = self.Process(
target=self._test_get,
args=(queue, child_can_start, parent_can_continue)
)
proc.daemon = True
proc.start()
self.assertEqual(queue_empty(queue), True)
child_can_start.set()
parent_can_continue.wait()
time.sleep(DELTA)
self.assertEqual(queue_empty(queue), False)
# Hangs unexpectedly, remove for now
#self.assertEqual(queue.get(), 1)
self.assertEqual(queue.get(True, None), 2)
self.assertEqual(queue.get(True), 3)
self.assertEqual(queue.get(timeout=1), 4)
self.assertEqual(queue.get_nowait(), 5)
self.assertEqual(queue_empty(queue), True)
get = TimingWrapper(queue.get)
get_nowait = TimingWrapper(queue.get_nowait)
self.assertRaises(pyqueue.Empty, get, False)
self.assertTimingAlmostEqual(get.elapsed, 0)
self.assertRaises(pyqueue.Empty, get, False, None)
self.assertTimingAlmostEqual(get.elapsed, 0)
self.assertRaises(pyqueue.Empty, get_nowait)
self.assertTimingAlmostEqual(get_nowait.elapsed, 0)
self.assertRaises(pyqueue.Empty, get, True, TIMEOUT1)
self.assertTimingAlmostEqual(get.elapsed, TIMEOUT1)
self.assertRaises(pyqueue.Empty, get, False, TIMEOUT2)
self.assertTimingAlmostEqual(get.elapsed, 0)
self.assertRaises(pyqueue.Empty, get, timeout=TIMEOUT3)
self.assertTimingAlmostEqual(get.elapsed, TIMEOUT3)
proc.join()
close_queue(queue)
@classmethod
def _test_fork(cls, queue):
for i in range(10, 20):
queue.put(i)
# note that at this point the items may only be buffered, so the
# process cannot shutdown until the feeder thread has finished
# pushing items onto the pipe.
def test_fork(self):
# Old versions of Queue would fail to create a new feeder
# thread for a forked process if the original process had its
# own feeder thread. This test checks that this no longer
# happens.
queue = self.Queue()
# put items on queue so that main process starts a feeder thread
for i in range(10):
queue.put(i)
# wait to make sure thread starts before we fork a new process
time.sleep(DELTA)
# fork process
p = self.Process(target=self._test_fork, args=(queue,))
p.daemon = True
p.start()
# check that all expected items are in the queue
for i in range(20):
self.assertEqual(queue.get(), i)
self.assertRaises(pyqueue.Empty, queue.get, False)
p.join()
close_queue(queue)
def test_qsize(self):
q = self.Queue()
try:
self.assertEqual(q.qsize(), 0)
except NotImplementedError:
self.skipTest('qsize method not implemented')
q.put(1)
self.assertEqual(q.qsize(), 1)
q.put(5)
self.assertEqual(q.qsize(), 2)
q.get()
self.assertEqual(q.qsize(), 1)
q.get()
self.assertEqual(q.qsize(), 0)
close_queue(q)
@classmethod
def _test_task_done(cls, q):
for obj in iter(q.get, None):
time.sleep(DELTA)
q.task_done()
def test_task_done(self):
queue = self.JoinableQueue()
workers = [self.Process(target=self._test_task_done, args=(queue,))
for i in range(4)]
for p in workers:
p.daemon = True
p.start()
for i in range(10):
queue.put(i)
queue.join()
for p in workers:
queue.put(None)
for p in workers:
p.join()
close_queue(queue)
def test_no_import_lock_contention(self):
with test.support.temp_cwd():
module_name = 'imported_by_an_imported_module'
with open(module_name + '.py', 'w') as f:
f.write("""if 1:
import multiprocessing
q = multiprocessing.Queue()
q.put('knock knock')
q.get(timeout=3)
q.close()
del q
""")
with test.support.DirsOnSysPath(os.getcwd()):
try:
__import__(module_name)
except pyqueue.Empty:
self.fail("Probable regression on import lock contention;"
" see Issue #22853")
def test_timeout(self):
q = multiprocessing.Queue()
start = time.monotonic()
self.assertRaises(pyqueue.Empty, q.get, True, 0.200)
delta = time.monotonic() - start
# bpo-30317: Tolerate a delta of 100 ms because of the bad clock
# resolution on Windows (usually 15.6 ms). x86 Windows7 3.x once
# failed because the delta was only 135.8 ms.
self.assertGreaterEqual(delta, 0.100)
close_queue(q)
def test_queue_feeder_donot_stop_onexc(self):
# bpo-30414: verify feeder handles exceptions correctly
if self.TYPE != 'processes':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
class NotSerializable(object):
def __reduce__(self):
raise AttributeError
with test.support.captured_stderr():
q = self.Queue()
q.put(NotSerializable())
q.put(True)
# bpo-30595: use a timeout of 1 second for slow buildbots
self.assertTrue(q.get(timeout=1.0))
close_queue(q)
with test.support.captured_stderr():
# bpo-33078: verify that the queue size is correctly handled
# on errors.
q = self.Queue(maxsize=1)
q.put(NotSerializable())
q.put(True)
try:
self.assertEqual(q.qsize(), 1)
except NotImplementedError:
# qsize is not available on all platform as it
# relies on sem_getvalue
pass
# bpo-30595: use a timeout of 1 second for slow buildbots
self.assertTrue(q.get(timeout=1.0))
# Check that the size of the queue is correct
self.assertTrue(q.empty())
close_queue(q)
def test_queue_feeder_on_queue_feeder_error(self):
# bpo-30006: verify feeder handles exceptions using the
# _on_queue_feeder_error hook.
if self.TYPE != 'processes':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
class NotSerializable(object):
"""Mock unserializable object"""
def __init__(self):
self.reduce_was_called = False
self.on_queue_feeder_error_was_called = False
def __reduce__(self):
self.reduce_was_called = True
raise AttributeError
class SafeQueue(multiprocessing.queues.Queue):
"""Queue with overloaded _on_queue_feeder_error hook"""
@staticmethod
def _on_queue_feeder_error(e, obj):
if (isinstance(e, AttributeError) and
isinstance(obj, NotSerializable)):
obj.on_queue_feeder_error_was_called = True
not_serializable_obj = NotSerializable()
# The captured_stderr reduces the noise in the test report
with test.support.captured_stderr():
q = SafeQueue(ctx=multiprocessing.get_context())
q.put(not_serializable_obj)
# Verify that q is still functioning correctly
q.put(True)
self.assertTrue(q.get(timeout=1.0))
# Assert that the serialization and the hook have been called correctly
self.assertTrue(not_serializable_obj.reduce_was_called)
self.assertTrue(not_serializable_obj.on_queue_feeder_error_was_called)
def test_closed_queue_put_get_exceptions(self):
for q in multiprocessing.Queue(), multiprocessing.JoinableQueue():
q.close()
with self.assertRaisesRegex(ValueError, 'is closed'):
q.put('foo')
with self.assertRaisesRegex(ValueError, 'is closed'):
q.get()
#
#
#
class _TestLock(BaseTestCase):
def test_lock(self):
lock = self.Lock()
self.assertEqual(lock.acquire(), True)
self.assertEqual(lock.acquire(False), False)
self.assertEqual(lock.release(), None)
self.assertRaises((ValueError, threading.ThreadError), lock.release)
def test_rlock(self):
lock = self.RLock()
self.assertEqual(lock.acquire(), True)
self.assertEqual(lock.acquire(), True)
self.assertEqual(lock.acquire(), True)
self.assertEqual(lock.release(), None)
self.assertEqual(lock.release(), None)
self.assertEqual(lock.release(), None)
self.assertRaises((AssertionError, RuntimeError), lock.release)
def test_lock_context(self):
with self.Lock():
pass
class _TestSemaphore(BaseTestCase):
def _test_semaphore(self, sem):
self.assertReturnsIfImplemented(2, get_value, sem)
self.assertEqual(sem.acquire(), True)
self.assertReturnsIfImplemented(1, get_value, sem)
self.assertEqual(sem.acquire(), True)
self.assertReturnsIfImplemented(0, get_value, sem)
self.assertEqual(sem.acquire(False), False)
self.assertReturnsIfImplemented(0, get_value, sem)
self.assertEqual(sem.release(), None)
self.assertReturnsIfImplemented(1, get_value, sem)
self.assertEqual(sem.release(), None)
self.assertReturnsIfImplemented(2, get_value, sem)
def test_semaphore(self):
sem = self.Semaphore(2)
self._test_semaphore(sem)
self.assertEqual(sem.release(), None)
self.assertReturnsIfImplemented(3, get_value, sem)
self.assertEqual(sem.release(), None)
self.assertReturnsIfImplemented(4, get_value, sem)
def test_bounded_semaphore(self):
sem = self.BoundedSemaphore(2)
self._test_semaphore(sem)
# Currently fails on OS/X
#if HAVE_GETVALUE:
# self.assertRaises(ValueError, sem.release)
# self.assertReturnsIfImplemented(2, get_value, sem)
def test_timeout(self):
if self.TYPE != 'processes':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
sem = self.Semaphore(0)
acquire = TimingWrapper(sem.acquire)
self.assertEqual(acquire(False), False)
self.assertTimingAlmostEqual(acquire.elapsed, 0.0)
self.assertEqual(acquire(False, None), False)
self.assertTimingAlmostEqual(acquire.elapsed, 0.0)
self.assertEqual(acquire(False, TIMEOUT1), False)
self.assertTimingAlmostEqual(acquire.elapsed, 0)
self.assertEqual(acquire(True, TIMEOUT2), False)
self.assertTimingAlmostEqual(acquire.elapsed, TIMEOUT2)
self.assertEqual(acquire(timeout=TIMEOUT3), False)
self.assertTimingAlmostEqual(acquire.elapsed, TIMEOUT3)
class _TestCondition(BaseTestCase):
@classmethod
def f(cls, cond, sleeping, woken, timeout=None):
cond.acquire()
sleeping.release()
cond.wait(timeout)
woken.release()
cond.release()
def assertReachesEventually(self, func, value):
for i in range(10):
try:
if func() == value:
break
except NotImplementedError:
break
time.sleep(DELTA)
time.sleep(DELTA)
self.assertReturnsIfImplemented(value, func)
def check_invariant(self, cond):
# this is only supposed to succeed when there are no sleepers
if self.TYPE == 'processes':
try:
sleepers = (cond._sleeping_count.get_value() -
cond._woken_count.get_value())
self.assertEqual(sleepers, 0)
self.assertEqual(cond._wait_semaphore.get_value(), 0)
except NotImplementedError:
pass
def test_notify(self):
cond = self.Condition()
sleeping = self.Semaphore(0)
woken = self.Semaphore(0)
p = self.Process(target=self.f, args=(cond, sleeping, woken))
p.daemon = True
p.start()
self.addCleanup(p.join)
p = threading.Thread(target=self.f, args=(cond, sleeping, woken))
p.daemon = True
p.start()
self.addCleanup(p.join)
# wait for both children to start sleeping
sleeping.acquire()
sleeping.acquire()
# check no process/thread has woken up
time.sleep(DELTA)
self.assertReturnsIfImplemented(0, get_value, woken)
# wake up one process/thread
cond.acquire()
cond.notify()
cond.release()
# check one process/thread has woken up
time.sleep(DELTA)
self.assertReturnsIfImplemented(1, get_value, woken)
# wake up another
cond.acquire()
cond.notify()
cond.release()
# check other has woken up
time.sleep(DELTA)
self.assertReturnsIfImplemented(2, get_value, woken)
# check state is not mucked up
self.check_invariant(cond)
p.join()
def test_notify_all(self):
cond = self.Condition()
sleeping = self.Semaphore(0)
woken = self.Semaphore(0)
# start some threads/processes which will timeout
for i in range(3):
p = self.Process(target=self.f,
args=(cond, sleeping, woken, TIMEOUT1))
p.daemon = True
p.start()
self.addCleanup(p.join)
t = threading.Thread(target=self.f,
args=(cond, sleeping, woken, TIMEOUT1))
t.daemon = True
t.start()
self.addCleanup(t.join)
# wait for them all to sleep
for i in range(6):
sleeping.acquire()
# check they have all timed out
for i in range(6):
woken.acquire()
self.assertReturnsIfImplemented(0, get_value, woken)
# check state is not mucked up
self.check_invariant(cond)
# start some more threads/processes
for i in range(3):
p = self.Process(target=self.f, args=(cond, sleeping, woken))
p.daemon = True
p.start()
self.addCleanup(p.join)
t = threading.Thread(target=self.f, args=(cond, sleeping, woken))
t.daemon = True
t.start()
self.addCleanup(t.join)
# wait for them to all sleep
for i in range(6):
sleeping.acquire()
# check no process/thread has woken up
time.sleep(DELTA)
self.assertReturnsIfImplemented(0, get_value, woken)
# wake them all up
cond.acquire()
cond.notify_all()
cond.release()
# check they have all woken
self.assertReachesEventually(lambda: get_value(woken), 6)
# check state is not mucked up
self.check_invariant(cond)
def test_notify_n(self):
cond = self.Condition()
sleeping = self.Semaphore(0)
woken = self.Semaphore(0)
# start some threads/processes
for i in range(3):
p = self.Process(target=self.f, args=(cond, sleeping, woken))
p.daemon = True
p.start()
self.addCleanup(p.join)
t = threading.Thread(target=self.f, args=(cond, sleeping, woken))
t.daemon = True
t.start()
self.addCleanup(t.join)
# wait for them to all sleep
for i in range(6):
sleeping.acquire()
# check no process/thread has woken up
time.sleep(DELTA)
self.assertReturnsIfImplemented(0, get_value, woken)
# wake some of them up
cond.acquire()
cond.notify(n=2)
cond.release()
# check 2 have woken
self.assertReachesEventually(lambda: get_value(woken), 2)
# wake the rest of them
cond.acquire()
cond.notify(n=4)
cond.release()
self.assertReachesEventually(lambda: get_value(woken), 6)
# doesn't do anything more
cond.acquire()
cond.notify(n=3)
cond.release()
self.assertReturnsIfImplemented(6, get_value, woken)
# check state is not mucked up
self.check_invariant(cond)
def test_timeout(self):
cond = self.Condition()
wait = TimingWrapper(cond.wait)
cond.acquire()
res = wait(TIMEOUT1)
cond.release()
self.assertEqual(res, False)
self.assertTimingAlmostEqual(wait.elapsed, TIMEOUT1)
@classmethod
def _test_waitfor_f(cls, cond, state):
with cond:
state.value = 0
cond.notify()
result = cond.wait_for(lambda : state.value==4)
if not result or state.value != 4:
sys.exit(1)
@unittest.skipUnless(HAS_SHAREDCTYPES, 'needs sharedctypes')
def test_waitfor(self):
# based on test in test/lock_tests.py
cond = self.Condition()
state = self.Value('i', -1)
p = self.Process(target=self._test_waitfor_f, args=(cond, state))
p.daemon = True
p.start()
with cond:
result = cond.wait_for(lambda : state.value==0)
self.assertTrue(result)
self.assertEqual(state.value, 0)
for i in range(4):
time.sleep(0.01)
with cond:
state.value += 1
cond.notify()
join_process(p)
self.assertEqual(p.exitcode, 0)
@classmethod
def _test_waitfor_timeout_f(cls, cond, state, success, sem):
sem.release()
with cond:
expected = 0.1
dt = time.monotonic()
result = cond.wait_for(lambda : state.value==4, timeout=expected)
dt = time.monotonic() - dt
# borrow logic in assertTimeout() from test/lock_tests.py
if not result and expected * 0.6 < dt < expected * 10.0:
success.value = True
@unittest.skipUnless(HAS_SHAREDCTYPES, 'needs sharedctypes')
def test_waitfor_timeout(self):
# based on test in test/lock_tests.py
cond = self.Condition()
state = self.Value('i', 0)
success = self.Value('i', False)
sem = self.Semaphore(0)
p = self.Process(target=self._test_waitfor_timeout_f,
args=(cond, state, success, sem))
p.daemon = True
p.start()
self.assertTrue(sem.acquire(timeout=TIMEOUT))
# Only increment 3 times, so state == 4 is never reached.
for i in range(3):
time.sleep(0.01)
with cond:
state.value += 1
cond.notify()
join_process(p)
self.assertTrue(success.value)
@classmethod
def _test_wait_result(cls, c, pid):
with c:
c.notify()
time.sleep(1)
if pid is not None:
os.kill(pid, signal.SIGINT)
def test_wait_result(self):
if isinstance(self, ProcessesMixin) and sys.platform != 'win32':
pid = os.getpid()
else:
pid = None
c = self.Condition()
with c:
self.assertFalse(c.wait(0))
self.assertFalse(c.wait(0.1))
p = self.Process(target=self._test_wait_result, args=(c, pid))
p.start()
self.assertTrue(c.wait(60))
if pid is not None:
self.assertRaises(KeyboardInterrupt, c.wait, 60)
p.join()
class _TestEvent(BaseTestCase):
@classmethod
def _test_event(cls, event):
time.sleep(TIMEOUT2)
event.set()
def test_event(self):
event = self.Event()
wait = TimingWrapper(event.wait)
# Removed temporarily, due to API shear, this does not
# work with threading._Event objects. is_set == isSet
self.assertEqual(event.is_set(), False)
# Removed, threading.Event.wait() will return the value of the __flag
# instead of None. API Shear with the semaphore backed mp.Event
self.assertEqual(wait(0.0), False)
self.assertTimingAlmostEqual(wait.elapsed, 0.0)
self.assertEqual(wait(TIMEOUT1), False)
self.assertTimingAlmostEqual(wait.elapsed, TIMEOUT1)
event.set()
# See note above on the API differences
self.assertEqual(event.is_set(), True)
self.assertEqual(wait(), True)
self.assertTimingAlmostEqual(wait.elapsed, 0.0)
self.assertEqual(wait(TIMEOUT1), True)
self.assertTimingAlmostEqual(wait.elapsed, 0.0)
# self.assertEqual(event.is_set(), True)
event.clear()
#self.assertEqual(event.is_set(), False)
p = self.Process(target=self._test_event, args=(event,))
p.daemon = True
p.start()
self.assertEqual(wait(), True)
p.join()
#
# Tests for Barrier - adapted from tests in test/lock_tests.py
#
# Many of the tests for threading.Barrier use a list as an atomic
# counter: a value is appended to increment the counter, and the
# length of the list gives the value. We use the class DummyList
# for the same purpose.
class _DummyList(object):
def __init__(self):
wrapper = multiprocessing.heap.BufferWrapper(struct.calcsize('i'))
lock = multiprocessing.Lock()
self.__setstate__((wrapper, lock))
self._lengthbuf[0] = 0
def __setstate__(self, state):
(self._wrapper, self._lock) = state
self._lengthbuf = self._wrapper.create_memoryview().cast('i')
def __getstate__(self):
return (self._wrapper, self._lock)
def append(self, _):
with self._lock:
self._lengthbuf[0] += 1
def __len__(self):
with self._lock:
return self._lengthbuf[0]
def _wait():
# A crude wait/yield function not relying on synchronization primitives.
time.sleep(0.01)
class Bunch(object):
"""
A bunch of threads.
"""
def __init__(self, namespace, f, args, n, wait_before_exit=False):
"""
Construct a bunch of `n` threads running the same function `f`.
If `wait_before_exit` is True, the threads won't terminate until
do_finish() is called.
"""
self.f = f
self.args = args
self.n = n
self.started = namespace.DummyList()
self.finished = namespace.DummyList()
self._can_exit = namespace.Event()
if not wait_before_exit:
self._can_exit.set()
threads = []
for i in range(n):
p = namespace.Process(target=self.task)
p.daemon = True
p.start()
threads.append(p)
def finalize(threads):
for p in threads:
p.join()
self._finalizer = weakref.finalize(self, finalize, threads)
def task(self):
pid = os.getpid()
self.started.append(pid)
try:
self.f(*self.args)
finally:
self.finished.append(pid)
self._can_exit.wait(30)
assert self._can_exit.is_set()
def wait_for_started(self):
while len(self.started) < self.n:
_wait()
def wait_for_finished(self):
while len(self.finished) < self.n:
_wait()
def do_finish(self):
self._can_exit.set()
def close(self):
self._finalizer()
class AppendTrue(object):
def __init__(self, obj):
self.obj = obj
def __call__(self):
self.obj.append(True)
class _TestBarrier(BaseTestCase):
"""
Tests for Barrier objects.
"""
N = 5
defaultTimeout = 30.0 # XXX Slow Windows buildbots need generous timeout
def setUp(self):
self.barrier = self.Barrier(self.N, timeout=self.defaultTimeout)
def tearDown(self):
self.barrier.abort()
self.barrier = None
def DummyList(self):
if self.TYPE == 'threads':
return []
elif self.TYPE == 'manager':
return self.manager.list()
else:
return _DummyList()
def run_threads(self, f, args):
b = Bunch(self, f, args, self.N-1)
try:
f(*args)
b.wait_for_finished()
finally:
b.close()
@classmethod
def multipass(cls, barrier, results, n):
m = barrier.parties
assert m == cls.N
for i in range(n):
results[0].append(True)
assert len(results[1]) == i * m
barrier.wait()
results[1].append(True)
assert len(results[0]) == (i + 1) * m
barrier.wait()
try:
assert barrier.n_waiting == 0
except NotImplementedError:
pass
assert not barrier.broken
def test_barrier(self, passes=1):
"""
Test that a barrier is passed in lockstep
"""
results = [self.DummyList(), self.DummyList()]
self.run_threads(self.multipass, (self.barrier, results, passes))
def test_barrier_10(self):
"""
Test that a barrier works for 10 consecutive runs
"""
return self.test_barrier(10)
@classmethod
def _test_wait_return_f(cls, barrier, queue):
res = barrier.wait()
queue.put(res)
def test_wait_return(self):
"""
test the return value from barrier.wait
"""
queue = self.Queue()
self.run_threads(self._test_wait_return_f, (self.barrier, queue))
results = [queue.get() for i in range(self.N)]
self.assertEqual(results.count(0), 1)
close_queue(queue)
@classmethod
def _test_action_f(cls, barrier, results):
barrier.wait()
if len(results) != 1:
raise RuntimeError
def test_action(self):
"""
Test the 'action' callback
"""
results = self.DummyList()
barrier = self.Barrier(self.N, action=AppendTrue(results))
self.run_threads(self._test_action_f, (barrier, results))
self.assertEqual(len(results), 1)
@classmethod
def _test_abort_f(cls, barrier, results1, results2):
try:
i = barrier.wait()
if i == cls.N//2:
raise RuntimeError
barrier.wait()
results1.append(True)
except threading.BrokenBarrierError:
results2.append(True)
except RuntimeError:
barrier.abort()
def test_abort(self):
"""
Test that an abort will put the barrier in a broken state
"""
results1 = self.DummyList()
results2 = self.DummyList()
self.run_threads(self._test_abort_f,
(self.barrier, results1, results2))
self.assertEqual(len(results1), 0)
self.assertEqual(len(results2), self.N-1)
self.assertTrue(self.barrier.broken)
@classmethod
def _test_reset_f(cls, barrier, results1, results2, results3):
i = barrier.wait()
if i == cls.N//2:
# Wait until the other threads are all in the barrier.
while barrier.n_waiting < cls.N-1:
time.sleep(0.001)
barrier.reset()
else:
try:
barrier.wait()
results1.append(True)
except threading.BrokenBarrierError:
results2.append(True)
# Now, pass the barrier again
barrier.wait()
results3.append(True)
def test_reset(self):
"""
Test that a 'reset' on a barrier frees the waiting threads
"""
results1 = self.DummyList()
results2 = self.DummyList()
results3 = self.DummyList()
self.run_threads(self._test_reset_f,
(self.barrier, results1, results2, results3))
self.assertEqual(len(results1), 0)
self.assertEqual(len(results2), self.N-1)
self.assertEqual(len(results3), self.N)
@classmethod
def _test_abort_and_reset_f(cls, barrier, barrier2,
results1, results2, results3):
try:
i = barrier.wait()
if i == cls.N//2:
raise RuntimeError
barrier.wait()
results1.append(True)
except threading.BrokenBarrierError:
results2.append(True)
except RuntimeError:
barrier.abort()
# Synchronize and reset the barrier. Must synchronize first so
# that everyone has left it when we reset, and after so that no
# one enters it before the reset.
if barrier2.wait() == cls.N//2:
barrier.reset()
barrier2.wait()
barrier.wait()
results3.append(True)
def test_abort_and_reset(self):
"""
Test that a barrier can be reset after being broken.
"""
results1 = self.DummyList()
results2 = self.DummyList()
results3 = self.DummyList()
barrier2 = self.Barrier(self.N)
self.run_threads(self._test_abort_and_reset_f,
(self.barrier, barrier2, results1, results2, results3))
self.assertEqual(len(results1), 0)
self.assertEqual(len(results2), self.N-1)
self.assertEqual(len(results3), self.N)
@classmethod
def _test_timeout_f(cls, barrier, results):
i = barrier.wait()
if i == cls.N//2:
# One thread is late!
time.sleep(1.0)
try:
barrier.wait(0.5)
except threading.BrokenBarrierError:
results.append(True)
def test_timeout(self):
"""
Test wait(timeout)
"""
results = self.DummyList()
self.run_threads(self._test_timeout_f, (self.barrier, results))
self.assertEqual(len(results), self.barrier.parties)
@classmethod
def _test_default_timeout_f(cls, barrier, results):
i = barrier.wait(cls.defaultTimeout)
if i == cls.N//2:
# One thread is later than the default timeout
time.sleep(1.0)
try:
barrier.wait()
except threading.BrokenBarrierError:
results.append(True)
def test_default_timeout(self):
"""
Test the barrier's default timeout
"""
barrier = self.Barrier(self.N, timeout=0.5)
results = self.DummyList()
self.run_threads(self._test_default_timeout_f, (barrier, results))
self.assertEqual(len(results), barrier.parties)
def test_single_thread(self):
b = self.Barrier(1)
b.wait()
b.wait()
@classmethod
def _test_thousand_f(cls, barrier, passes, conn, lock):
for i in range(passes):
barrier.wait()
with lock:
conn.send(i)
def test_thousand(self):
if self.TYPE == 'manager':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
passes = 1000
lock = self.Lock()
conn, child_conn = self.Pipe(False)
for j in range(self.N):
p = self.Process(target=self._test_thousand_f,
args=(self.barrier, passes, child_conn, lock))
p.start()
self.addCleanup(p.join)
for i in range(passes):
for j in range(self.N):
self.assertEqual(conn.recv(), i)
#
#
#
class _TestValue(BaseTestCase):
ALLOWED_TYPES = ('processes',)
codes_values = [
('i', 4343, 24234),
('d', 3.625, -4.25),
('h', -232, 234),
('q', 2 ** 33, 2 ** 34),
('c', latin('x'), latin('y'))
]
def setUp(self):
if not HAS_SHAREDCTYPES:
self.skipTest("requires multiprocessing.sharedctypes")
@classmethod
def _test(cls, values):
for sv, cv in zip(values, cls.codes_values):
sv.value = cv[2]
def test_value(self, raw=False):
if raw:
values = [self.RawValue(code, value)
for code, value, _ in self.codes_values]
else:
values = [self.Value(code, value)
for code, value, _ in self.codes_values]
for sv, cv in zip(values, self.codes_values):
self.assertEqual(sv.value, cv[1])
proc = self.Process(target=self._test, args=(values,))
proc.daemon = True
proc.start()
proc.join()
for sv, cv in zip(values, self.codes_values):
self.assertEqual(sv.value, cv[2])
def test_rawvalue(self):
self.test_value(raw=True)
def test_getobj_getlock(self):
val1 = self.Value('i', 5)
lock1 = val1.get_lock()
obj1 = val1.get_obj()
val2 = self.Value('i', 5, lock=None)
lock2 = val2.get_lock()
obj2 = val2.get_obj()
lock = self.Lock()
val3 = self.Value('i', 5, lock=lock)
lock3 = val3.get_lock()
obj3 = val3.get_obj()
self.assertEqual(lock, lock3)
arr4 = self.Value('i', 5, lock=False)
self.assertFalse(hasattr(arr4, 'get_lock'))
self.assertFalse(hasattr(arr4, 'get_obj'))
self.assertRaises(AttributeError, self.Value, 'i', 5, lock='navalue')
arr5 = self.RawValue('i', 5)
self.assertFalse(hasattr(arr5, 'get_lock'))
self.assertFalse(hasattr(arr5, 'get_obj'))
class _TestArray(BaseTestCase):
ALLOWED_TYPES = ('processes',)
@classmethod
def f(cls, seq):
for i in range(1, len(seq)):
seq[i] += seq[i-1]
@unittest.skipIf(c_int is None, "requires _ctypes")
def test_array(self, raw=False):
seq = [680, 626, 934, 821, 150, 233, 548, 982, 714, 831]
if raw:
arr = self.RawArray('i', seq)
else:
arr = self.Array('i', seq)
self.assertEqual(len(arr), len(seq))
self.assertEqual(arr[3], seq[3])
self.assertEqual(list(arr[2:7]), list(seq[2:7]))
arr[4:8] = seq[4:8] = array.array('i', [1, 2, 3, 4])
self.assertEqual(list(arr[:]), seq)
self.f(seq)
p = self.Process(target=self.f, args=(arr,))
p.daemon = True
p.start()
p.join()
self.assertEqual(list(arr[:]), seq)
@unittest.skipIf(c_int is None, "requires _ctypes")
def test_array_from_size(self):
size = 10
# Test for zeroing (see issue #11675).
# The repetition below strengthens the test by increasing the chances
# of previously allocated non-zero memory being used for the new array
# on the 2nd and 3rd loops.
for _ in range(3):
arr = self.Array('i', size)
self.assertEqual(len(arr), size)
self.assertEqual(list(arr), [0] * size)
arr[:] = range(10)
self.assertEqual(list(arr), list(range(10)))
del arr
@unittest.skipIf(c_int is None, "requires _ctypes")
def test_rawarray(self):
self.test_array(raw=True)
@unittest.skipIf(c_int is None, "requires _ctypes")
def test_getobj_getlock_obj(self):
arr1 = self.Array('i', list(range(10)))
lock1 = arr1.get_lock()
obj1 = arr1.get_obj()
arr2 = self.Array('i', list(range(10)), lock=None)
lock2 = arr2.get_lock()
obj2 = arr2.get_obj()
lock = self.Lock()
arr3 = self.Array('i', list(range(10)), lock=lock)
lock3 = arr3.get_lock()
obj3 = arr3.get_obj()
self.assertEqual(lock, lock3)
arr4 = self.Array('i', range(10), lock=False)
self.assertFalse(hasattr(arr4, 'get_lock'))
self.assertFalse(hasattr(arr4, 'get_obj'))
self.assertRaises(AttributeError,
self.Array, 'i', range(10), lock='notalock')
arr5 = self.RawArray('i', range(10))
self.assertFalse(hasattr(arr5, 'get_lock'))
self.assertFalse(hasattr(arr5, 'get_obj'))
#
#
#
class _TestContainers(BaseTestCase):
ALLOWED_TYPES = ('manager',)
def test_list(self):
a = self.list(list(range(10)))
self.assertEqual(a[:], list(range(10)))
b = self.list()
self.assertEqual(b[:], [])
b.extend(list(range(5)))
self.assertEqual(b[:], list(range(5)))
self.assertEqual(b[2], 2)
self.assertEqual(b[2:10], [2,3,4])
b *= 2
self.assertEqual(b[:], [0, 1, 2, 3, 4, 0, 1, 2, 3, 4])
self.assertEqual(b + [5, 6], [0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 5, 6])
self.assertEqual(a[:], list(range(10)))
d = [a, b]
e = self.list(d)
self.assertEqual(
[element[:] for element in e],
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 0, 1, 2, 3, 4]]
)
f = self.list([a])
a.append('hello')
self.assertEqual(f[0][:], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'hello'])
def test_list_iter(self):
a = self.list(list(range(10)))
it = iter(a)
self.assertEqual(list(it), list(range(10)))
self.assertEqual(list(it), []) # exhausted
# list modified during iteration
it = iter(a)
a[0] = 100
self.assertEqual(next(it), 100)
def test_list_proxy_in_list(self):
a = self.list([self.list(range(3)) for _i in range(3)])
self.assertEqual([inner[:] for inner in a], [[0, 1, 2]] * 3)
a[0][-1] = 55
self.assertEqual(a[0][:], [0, 1, 55])
for i in range(1, 3):
self.assertEqual(a[i][:], [0, 1, 2])
self.assertEqual(a[1].pop(), 2)
self.assertEqual(len(a[1]), 2)
for i in range(0, 3, 2):
self.assertEqual(len(a[i]), 3)
del a
b = self.list()
b.append(b)
del b
def test_dict(self):
d = self.dict()
indices = list(range(65, 70))
for i in indices:
d[i] = chr(i)
self.assertEqual(d.copy(), dict((i, chr(i)) for i in indices))
self.assertEqual(sorted(d.keys()), indices)
self.assertEqual(sorted(d.values()), [chr(i) for i in indices])
self.assertEqual(sorted(d.items()), [(i, chr(i)) for i in indices])
def test_dict_iter(self):
d = self.dict()
indices = list(range(65, 70))
for i in indices:
d[i] = chr(i)
it = iter(d)
self.assertEqual(list(it), indices)
self.assertEqual(list(it), []) # exhausted
# dictionary changed size during iteration
it = iter(d)
d.clear()
self.assertRaises(RuntimeError, next, it)
def test_dict_proxy_nested(self):
pets = self.dict(ferrets=2, hamsters=4)
supplies = self.dict(water=10, feed=3)
d = self.dict(pets=pets, supplies=supplies)
self.assertEqual(supplies['water'], 10)
self.assertEqual(d['supplies']['water'], 10)
d['supplies']['blankets'] = 5
self.assertEqual(supplies['blankets'], 5)
self.assertEqual(d['supplies']['blankets'], 5)
d['supplies']['water'] = 7
self.assertEqual(supplies['water'], 7)
self.assertEqual(d['supplies']['water'], 7)
del pets
del supplies
self.assertEqual(d['pets']['ferrets'], 2)
d['supplies']['blankets'] = 11
self.assertEqual(d['supplies']['blankets'], 11)
pets = d['pets']
supplies = d['supplies']
supplies['water'] = 7
self.assertEqual(supplies['water'], 7)
self.assertEqual(d['supplies']['water'], 7)
d.clear()
self.assertEqual(len(d), 0)
self.assertEqual(supplies['water'], 7)
self.assertEqual(pets['hamsters'], 4)
l = self.list([pets, supplies])
l[0]['marmots'] = 1
self.assertEqual(pets['marmots'], 1)
self.assertEqual(l[0]['marmots'], 1)
del pets
del supplies
self.assertEqual(l[0]['marmots'], 1)
outer = self.list([[88, 99], l])
self.assertIsInstance(outer[0], list) # Not a ListProxy
self.assertEqual(outer[-1][-1]['feed'], 3)
def test_namespace(self):
n = self.Namespace()
n.name = 'Bob'
n.job = 'Builder'
n._hidden = 'hidden'
self.assertEqual((n.name, n.job), ('Bob', 'Builder'))
del n.job
self.assertEqual(str(n), "Namespace(name='Bob')")
self.assertTrue(hasattr(n, 'name'))
self.assertTrue(not hasattr(n, 'job'))
#
#
#
def sqr(x, wait=0.0):
time.sleep(wait)
return x*x
def mul(x, y):
return x*y
def raise_large_valuerror(wait):
time.sleep(wait)
raise ValueError("x" * 1024**2)
def identity(x):
return x
class CountedObject(object):
n_instances = 0
def __new__(cls):
cls.n_instances += 1
return object.__new__(cls)
def __del__(self):
type(self).n_instances -= 1
class SayWhenError(ValueError): pass
def exception_throwing_generator(total, when):
if when == -1:
raise SayWhenError("Somebody said when")
for i in range(total):
if i == when:
raise SayWhenError("Somebody said when")
yield i
class _TestPool(BaseTestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.pool = cls.Pool(4)
@classmethod
def tearDownClass(cls):
cls.pool.terminate()
cls.pool.join()
cls.pool = None
super().tearDownClass()
def test_apply(self):
papply = self.pool.apply
self.assertEqual(papply(sqr, (5,)), sqr(5))
self.assertEqual(papply(sqr, (), {'x':3}), sqr(x=3))
def test_map(self):
pmap = self.pool.map
self.assertEqual(pmap(sqr, list(range(10))), list(map(sqr, list(range(10)))))
self.assertEqual(pmap(sqr, list(range(100)), chunksize=20),
list(map(sqr, list(range(100)))))
def test_starmap(self):
psmap = self.pool.starmap
tuples = list(zip(range(10), range(9,-1, -1)))
self.assertEqual(psmap(mul, tuples),
list(itertools.starmap(mul, tuples)))
tuples = list(zip(range(100), range(99,-1, -1)))
self.assertEqual(psmap(mul, tuples, chunksize=20),
list(itertools.starmap(mul, tuples)))
def test_starmap_async(self):
tuples = list(zip(range(100), range(99,-1, -1)))
self.assertEqual(self.pool.starmap_async(mul, tuples).get(),
list(itertools.starmap(mul, tuples)))
def test_map_async(self):
self.assertEqual(self.pool.map_async(sqr, list(range(10))).get(),
list(map(sqr, list(range(10)))))
def test_map_async_callbacks(self):
call_args = self.manager.list() if self.TYPE == 'manager' else []
self.pool.map_async(int, ['1'],
callback=call_args.append,
error_callback=call_args.append).wait()
self.assertEqual(1, len(call_args))
self.assertEqual([1], call_args[0])
self.pool.map_async(int, ['a'],
callback=call_args.append,
error_callback=call_args.append).wait()
self.assertEqual(2, len(call_args))
self.assertIsInstance(call_args[1], ValueError)
def test_map_unplicklable(self):
# Issue #19425 -- failure to pickle should not cause a hang
if self.TYPE == 'threads':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
class A(object):
def __reduce__(self):
raise RuntimeError('cannot pickle')
with self.assertRaises(RuntimeError):
self.pool.map(sqr, [A()]*10)
def test_map_chunksize(self):
try:
self.pool.map_async(sqr, [], chunksize=1).get(timeout=TIMEOUT1)
except multiprocessing.TimeoutError:
self.fail("pool.map_async with chunksize stalled on null list")
def test_map_handle_iterable_exception(self):
if self.TYPE == 'manager':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
# SayWhenError seen at the very first of the iterable
with self.assertRaises(SayWhenError):
self.pool.map(sqr, exception_throwing_generator(1, -1), 1)
# again, make sure it's reentrant
with self.assertRaises(SayWhenError):
self.pool.map(sqr, exception_throwing_generator(1, -1), 1)
with self.assertRaises(SayWhenError):
self.pool.map(sqr, exception_throwing_generator(10, 3), 1)
class SpecialIterable:
def __iter__(self):
return self
def __next__(self):
raise SayWhenError
def __len__(self):
return 1
with self.assertRaises(SayWhenError):
self.pool.map(sqr, SpecialIterable(), 1)
with self.assertRaises(SayWhenError):
self.pool.map(sqr, SpecialIterable(), 1)
def test_async(self):
res = self.pool.apply_async(sqr, (7, TIMEOUT1,))
get = TimingWrapper(res.get)
self.assertEqual(get(), 49)
self.assertTimingAlmostEqual(get.elapsed, TIMEOUT1)
def test_async_timeout(self):
res = self.pool.apply_async(sqr, (6, TIMEOUT2 + 1.0))
get = TimingWrapper(res.get)
self.assertRaises(multiprocessing.TimeoutError, get, timeout=TIMEOUT2)
self.assertTimingAlmostEqual(get.elapsed, TIMEOUT2)
def test_imap(self):
it = self.pool.imap(sqr, list(range(10)))
self.assertEqual(list(it), list(map(sqr, list(range(10)))))
it = self.pool.imap(sqr, list(range(10)))
for i in range(10):
self.assertEqual(next(it), i*i)
self.assertRaises(StopIteration, it.__next__)
it = self.pool.imap(sqr, list(range(1000)), chunksize=100)
for i in range(1000):
self.assertEqual(next(it), i*i)
self.assertRaises(StopIteration, it.__next__)
def test_imap_handle_iterable_exception(self):
if self.TYPE == 'manager':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
# SayWhenError seen at the very first of the iterable
it = self.pool.imap(sqr, exception_throwing_generator(1, -1), 1)
self.assertRaises(SayWhenError, it.__next__)
# again, make sure it's reentrant
it = self.pool.imap(sqr, exception_throwing_generator(1, -1), 1)
self.assertRaises(SayWhenError, it.__next__)
it = self.pool.imap(sqr, exception_throwing_generator(10, 3), 1)
for i in range(3):
self.assertEqual(next(it), i*i)
self.assertRaises(SayWhenError, it.__next__)
# SayWhenError seen at start of problematic chunk's results
it = self.pool.imap(sqr, exception_throwing_generator(20, 7), 2)
for i in range(6):
self.assertEqual(next(it), i*i)
self.assertRaises(SayWhenError, it.__next__)
it = self.pool.imap(sqr, exception_throwing_generator(20, 7), 4)
for i in range(4):
self.assertEqual(next(it), i*i)
self.assertRaises(SayWhenError, it.__next__)
def test_imap_unordered(self):
it = self.pool.imap_unordered(sqr, list(range(10)))
self.assertEqual(sorted(it), list(map(sqr, list(range(10)))))
it = self.pool.imap_unordered(sqr, list(range(1000)), chunksize=100)
self.assertEqual(sorted(it), list(map(sqr, list(range(1000)))))
def test_imap_unordered_handle_iterable_exception(self):
if self.TYPE == 'manager':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
# SayWhenError seen at the very first of the iterable
it = self.pool.imap_unordered(sqr,
exception_throwing_generator(1, -1),
1)
self.assertRaises(SayWhenError, it.__next__)
# again, make sure it's reentrant
it = self.pool.imap_unordered(sqr,
exception_throwing_generator(1, -1),
1)
self.assertRaises(SayWhenError, it.__next__)
it = self.pool.imap_unordered(sqr,
exception_throwing_generator(10, 3),
1)
expected_values = list(map(sqr, list(range(10))))
with self.assertRaises(SayWhenError):
# imap_unordered makes it difficult to anticipate the SayWhenError
for i in range(10):
value = next(it)
self.assertIn(value, expected_values)
expected_values.remove(value)
it = self.pool.imap_unordered(sqr,
exception_throwing_generator(20, 7),
2)
expected_values = list(map(sqr, list(range(20))))
with self.assertRaises(SayWhenError):
for i in range(20):
value = next(it)
self.assertIn(value, expected_values)
expected_values.remove(value)
def test_make_pool(self):
expected_error = (RemoteError if self.TYPE == 'manager'
else ValueError)
self.assertRaises(expected_error, self.Pool, -1)
self.assertRaises(expected_error, self.Pool, 0)
if self.TYPE != 'manager':
p = self.Pool(3)
try:
self.assertEqual(3, len(p._pool))
finally:
p.close()
p.join()
def test_terminate(self):
result = self.pool.map_async(
time.sleep, [0.1 for i in range(10000)], chunksize=1
)
self.pool.terminate()
join = TimingWrapper(self.pool.join)
join()
# Sanity check the pool didn't wait for all tasks to finish
self.assertLess(join.elapsed, 2.0)
def test_empty_iterable(self):
# See Issue 12157
p = self.Pool(1)
self.assertEqual(p.map(sqr, []), [])
self.assertEqual(list(p.imap(sqr, [])), [])
self.assertEqual(list(p.imap_unordered(sqr, [])), [])
self.assertEqual(p.map_async(sqr, []).get(), [])
p.close()
p.join()
def test_context(self):
if self.TYPE == 'processes':
L = list(range(10))
expected = [sqr(i) for i in L]
with self.Pool(2) as p:
r = p.map_async(sqr, L)
self.assertEqual(r.get(), expected)
p.join()
self.assertRaises(ValueError, p.map_async, sqr, L)
@classmethod
def _test_traceback(cls):
raise RuntimeError(123) # some comment
def test_traceback(self):
# We want ensure that the traceback from the child process is
# contained in the traceback raised in the main process.
if self.TYPE == 'processes':
with self.Pool(1) as p:
try:
p.apply(self._test_traceback)
except Exception as e:
exc = e
else:
self.fail('expected RuntimeError')
p.join()
self.assertIs(type(exc), RuntimeError)
self.assertEqual(exc.args, (123,))
cause = exc.__cause__
self.assertIs(type(cause), multiprocessing.pool.RemoteTraceback)
self.assertIn('raise RuntimeError(123) # some comment', cause.tb)
with test.support.captured_stderr() as f1:
try:
raise exc
except RuntimeError:
sys.excepthook(*sys.exc_info())
self.assertIn('raise RuntimeError(123) # some comment',
f1.getvalue())
# _helper_reraises_exception should not make the error
# a remote exception
with self.Pool(1) as p:
try:
p.map(sqr, exception_throwing_generator(1, -1), 1)
except Exception as e:
exc = e
else:
self.fail('expected SayWhenError')
self.assertIs(type(exc), SayWhenError)
self.assertIs(exc.__cause__, None)
p.join()
@classmethod
def _test_wrapped_exception(cls):
raise RuntimeError('foo')
def test_wrapped_exception(self):
# Issue #20980: Should not wrap exception when using thread pool
with self.Pool(1) as p:
with self.assertRaises(RuntimeError):
p.apply(self._test_wrapped_exception)
p.join()
def test_map_no_failfast(self):
# Issue #23992: the fail-fast behaviour when an exception is raised
# during map() would make Pool.join() deadlock, because a worker
# process would fill the result queue (after the result handler thread
# terminated, hence not draining it anymore).
t_start = time.monotonic()
with self.assertRaises(ValueError):
with self.Pool(2) as p:
try:
p.map(raise_large_valuerror, [0, 1])
finally:
time.sleep(0.5)
p.close()
p.join()
# check that we indeed waited for all jobs
self.assertGreater(time.monotonic() - t_start, 0.9)
def test_release_task_refs(self):
# Issue #29861: task arguments and results should not be kept
# alive after we are done with them.
objs = [CountedObject() for i in range(10)]
refs = [weakref.ref(o) for o in objs]
self.pool.map(identity, objs)
del objs
time.sleep(DELTA) # let threaded cleanup code run
self.assertEqual(set(wr() for wr in refs), {None})
# With a process pool, copies of the objects are returned, check
# they were released too.
self.assertEqual(CountedObject.n_instances, 0)
def test_enter(self):
if self.TYPE == 'manager':
self.skipTest("test not applicable to manager")
pool = self.Pool(1)
with pool:
pass
# call pool.terminate()
# pool is no longer running
with self.assertRaises(ValueError):
# bpo-35477: pool.__enter__() fails if the pool is not running
with pool:
pass
pool.join()
def test_resource_warning(self):
if self.TYPE == 'manager':
self.skipTest("test not applicable to manager")
pool = self.Pool(1)
pool.terminate()
pool.join()
# force state to RUN to emit ResourceWarning in __del__()
pool._state = multiprocessing.pool.RUN
with support.check_warnings(('unclosed running multiprocessing pool',
ResourceWarning)):
pool = None
support.gc_collect()
def raising():
raise KeyError("key")
def unpickleable_result():
return lambda: 42
class _TestPoolWorkerErrors(BaseTestCase):
ALLOWED_TYPES = ('processes', )
def test_async_error_callback(self):
p = multiprocessing.Pool(2)
scratchpad = [None]
def errback(exc):
scratchpad[0] = exc
res = p.apply_async(raising, error_callback=errback)
self.assertRaises(KeyError, res.get)
self.assertTrue(scratchpad[0])
self.assertIsInstance(scratchpad[0], KeyError)
p.close()
p.join()
def test_unpickleable_result(self):
from multiprocessing.pool import MaybeEncodingError
p = multiprocessing.Pool(2)
# Make sure we don't lose pool processes because of encoding errors.
for iteration in range(20):
scratchpad = [None]
def errback(exc):
scratchpad[0] = exc
res = p.apply_async(unpickleable_result, error_callback=errback)
self.assertRaises(MaybeEncodingError, res.get)
wrapped = scratchpad[0]
self.assertTrue(wrapped)
self.assertIsInstance(scratchpad[0], MaybeEncodingError)
self.assertIsNotNone(wrapped.exc)
self.assertIsNotNone(wrapped.value)
p.close()
p.join()
class _TestPoolWorkerLifetime(BaseTestCase):
ALLOWED_TYPES = ('processes', )
def test_pool_worker_lifetime(self):
p = multiprocessing.Pool(3, maxtasksperchild=10)
self.assertEqual(3, len(p._pool))
origworkerpids = [w.pid for w in p._pool]
# Run many tasks so each worker gets replaced (hopefully)
results = []
for i in range(100):
results.append(p.apply_async(sqr, (i, )))
# Fetch the results and verify we got the right answers,
# also ensuring all the tasks have completed.
for (j, res) in enumerate(results):
self.assertEqual(res.get(), sqr(j))
# Refill the pool
p._repopulate_pool()
# Wait until all workers are alive
# (countdown * DELTA = 5 seconds max startup process time)
countdown = 50
while countdown and not all(w.is_alive() for w in p._pool):
countdown -= 1
time.sleep(DELTA)
finalworkerpids = [w.pid for w in p._pool]
# All pids should be assigned. See issue #7805.
self.assertNotIn(None, origworkerpids)
self.assertNotIn(None, finalworkerpids)
# Finally, check that the worker pids have changed
self.assertNotEqual(sorted(origworkerpids), sorted(finalworkerpids))
p.close()
p.join()
def test_pool_worker_lifetime_early_close(self):
# Issue #10332: closing a pool whose workers have limited lifetimes
# before all the tasks completed would make join() hang.
p = multiprocessing.Pool(3, maxtasksperchild=1)
results = []
for i in range(6):
results.append(p.apply_async(sqr, (i, 0.3)))
p.close()
p.join()
# check the results
for (j, res) in enumerate(results):
self.assertEqual(res.get(), sqr(j))
#
# Test of creating a customized manager class
#
from multiprocessing.managers import BaseManager, BaseProxy, RemoteError
class FooBar(object):
def f(self):
return 'f()'
def g(self):
raise ValueError
def _h(self):
return '_h()'
def baz():
for i in range(10):
yield i*i
class IteratorProxy(BaseProxy):
_exposed_ = ('__next__',)
def __iter__(self):
return self
def __next__(self):
return self._callmethod('__next__')
class MyManager(BaseManager):
pass
MyManager.register('Foo', callable=FooBar)
MyManager.register('Bar', callable=FooBar, exposed=('f', '_h'))
MyManager.register('baz', callable=baz, proxytype=IteratorProxy)
class _TestMyManager(BaseTestCase):
ALLOWED_TYPES = ('manager',)
def test_mymanager(self):
manager = MyManager()
manager.start()
self.common(manager)
manager.shutdown()
# If the manager process exited cleanly then the exitcode
# will be zero. Otherwise (after a short timeout)
# terminate() is used, resulting in an exitcode of -SIGTERM.
self.assertEqual(manager._process.exitcode, 0)
def test_mymanager_context(self):
with MyManager() as manager:
self.common(manager)
# bpo-30356: BaseManager._finalize_manager() sends SIGTERM
# to the manager process if it takes longer than 1 second to stop.
self.assertIn(manager._process.exitcode, (0, -signal.SIGTERM))
def test_mymanager_context_prestarted(self):
manager = MyManager()
manager.start()
with manager:
self.common(manager)
self.assertEqual(manager._process.exitcode, 0)
def common(self, manager):
foo = manager.Foo()
bar = manager.Bar()
baz = manager.baz()
foo_methods = [name for name in ('f', 'g', '_h') if hasattr(foo, name)]
bar_methods = [name for name in ('f', 'g', '_h') if hasattr(bar, name)]
self.assertEqual(foo_methods, ['f', 'g'])
self.assertEqual(bar_methods, ['f', '_h'])
self.assertEqual(foo.f(), 'f()')
self.assertRaises(ValueError, foo.g)
self.assertEqual(foo._callmethod('f'), 'f()')
self.assertRaises(RemoteError, foo._callmethod, '_h')
self.assertEqual(bar.f(), 'f()')
self.assertEqual(bar._h(), '_h()')
self.assertEqual(bar._callmethod('f'), 'f()')
self.assertEqual(bar._callmethod('_h'), '_h()')
self.assertEqual(list(baz), [i*i for i in range(10)])
#
# Test of connecting to a remote server and using xmlrpclib for serialization
#
_queue = pyqueue.Queue()
def get_queue():
return _queue
class QueueManager(BaseManager):
'''manager class used by server process'''
QueueManager.register('get_queue', callable=get_queue)
class QueueManager2(BaseManager):
'''manager class which specifies the same interface as QueueManager'''
QueueManager2.register('get_queue')
SERIALIZER = 'xmlrpclib'
class _TestRemoteManager(BaseTestCase):
ALLOWED_TYPES = ('manager',)
values = ['hello world', None, True, 2.25,
'hall\xe5 v\xe4rlden',
'\u043f\u0440\u0438\u0432\u0456\u0442 \u0441\u0432\u0456\u0442',
b'hall\xe5 v\xe4rlden',
]
result = values[:]
@classmethod
def _putter(cls, address, authkey):
manager = QueueManager2(
address=address, authkey=authkey, serializer=SERIALIZER
)
manager.connect()
queue = manager.get_queue()
# Note that xmlrpclib will deserialize object as a list not a tuple
queue.put(tuple(cls.values))
def test_remote(self):
authkey = os.urandom(32)
manager = QueueManager(
address=(test.support.HOST, 0), authkey=authkey, serializer=SERIALIZER
)
manager.start()
p = self.Process(target=self._putter, args=(manager.address, authkey))
p.daemon = True
p.start()
manager2 = QueueManager2(
address=manager.address, authkey=authkey, serializer=SERIALIZER
)
manager2.connect()
queue = manager2.get_queue()
self.assertEqual(queue.get(), self.result)
# Because we are using xmlrpclib for serialization instead of
# pickle this will cause a serialization error.
self.assertRaises(Exception, queue.put, time.sleep)
# Make queue finalizer run before the server is stopped
del queue
manager.shutdown()
class _TestManagerRestart(BaseTestCase):
@classmethod
def _putter(cls, address, authkey):
manager = QueueManager(
address=address, authkey=authkey, serializer=SERIALIZER)
manager.connect()
queue = manager.get_queue()
queue.put('hello world')
def test_rapid_restart(self):
authkey = os.urandom(32)
manager = QueueManager(
address=(test.support.HOST, 0), authkey=authkey, serializer=SERIALIZER)
srvr = manager.get_server()
addr = srvr.address
# Close the connection.Listener socket which gets opened as a part
# of manager.get_server(). It's not needed for the test.
srvr.listener.close()
manager.start()
p = self.Process(target=self._putter, args=(manager.address, authkey))
p.start()
p.join()
queue = manager.get_queue()
self.assertEqual(queue.get(), 'hello world')
del queue
manager.shutdown()
manager = QueueManager(
address=addr, authkey=authkey, serializer=SERIALIZER)
try:
manager.start()
except OSError as e:
if e.errno != errno.EADDRINUSE:
raise
# Retry after some time, in case the old socket was lingering
# (sporadic failure on buildbots)
time.sleep(1.0)
manager = QueueManager(
address=addr, authkey=authkey, serializer=SERIALIZER)
manager.shutdown()
#
#
#
SENTINEL = latin('')
class _TestConnection(BaseTestCase):
ALLOWED_TYPES = ('processes', 'threads')
@classmethod
def _echo(cls, conn):
for msg in iter(conn.recv_bytes, SENTINEL):
conn.send_bytes(msg)
conn.close()
def test_connection(self):
conn, child_conn = self.Pipe()
p = self.Process(target=self._echo, args=(child_conn,))
p.daemon = True
p.start()
seq = [1, 2.25, None]
msg = latin('hello world')
longmsg = msg * 10
arr = array.array('i', list(range(4)))
if self.TYPE == 'processes':
self.assertEqual(type(conn.fileno()), int)
self.assertEqual(conn.send(seq), None)
self.assertEqual(conn.recv(), seq)
self.assertEqual(conn.send_bytes(msg), None)
self.assertEqual(conn.recv_bytes(), msg)
if self.TYPE == 'processes':
buffer = array.array('i', [0]*10)
expected = list(arr) + [0] * (10 - len(arr))
self.assertEqual(conn.send_bytes(arr), None)
self.assertEqual(conn.recv_bytes_into(buffer),
len(arr) * buffer.itemsize)
self.assertEqual(list(buffer), expected)
buffer = array.array('i', [0]*10)
expected = [0] * 3 + list(arr) + [0] * (10 - 3 - len(arr))
self.assertEqual(conn.send_bytes(arr), None)
self.assertEqual(conn.recv_bytes_into(buffer, 3 * buffer.itemsize),
len(arr) * buffer.itemsize)
self.assertEqual(list(buffer), expected)
buffer = bytearray(latin(' ' * 40))
self.assertEqual(conn.send_bytes(longmsg), None)
try:
res = conn.recv_bytes_into(buffer)
except multiprocessing.BufferTooShort as e:
self.assertEqual(e.args, (longmsg,))
else:
self.fail('expected BufferTooShort, got %s' % res)
poll = TimingWrapper(conn.poll)
self.assertEqual(poll(), False)
self.assertTimingAlmostEqual(poll.elapsed, 0)
self.assertEqual(poll(-1), False)
self.assertTimingAlmostEqual(poll.elapsed, 0)
self.assertEqual(poll(TIMEOUT1), False)
self.assertTimingAlmostEqual(poll.elapsed, TIMEOUT1)
conn.send(None)
time.sleep(.1)
self.assertEqual(poll(TIMEOUT1), True)
self.assertTimingAlmostEqual(poll.elapsed, 0)
self.assertEqual(conn.recv(), None)
really_big_msg = latin('X') * (1024 * 1024 * 16) # 16Mb
conn.send_bytes(really_big_msg)
self.assertEqual(conn.recv_bytes(), really_big_msg)
conn.send_bytes(SENTINEL) # tell child to quit
child_conn.close()
if self.TYPE == 'processes':
self.assertEqual(conn.readable, True)
self.assertEqual(conn.writable, True)
self.assertRaises(EOFError, conn.recv)
self.assertRaises(EOFError, conn.recv_bytes)
p.join()
def test_duplex_false(self):
reader, writer = self.Pipe(duplex=False)
self.assertEqual(writer.send(1), None)
self.assertEqual(reader.recv(), 1)
if self.TYPE == 'processes':
self.assertEqual(reader.readable, True)
self.assertEqual(reader.writable, False)
self.assertEqual(writer.readable, False)
self.assertEqual(writer.writable, True)
self.assertRaises(OSError, reader.send, 2)
self.assertRaises(OSError, writer.recv)
self.assertRaises(OSError, writer.poll)
def test_spawn_close(self):
# We test that a pipe connection can be closed by parent
# process immediately after child is spawned. On Windows this
# would have sometimes failed on old versions because
# child_conn would be closed before the child got a chance to
# duplicate it.
conn, child_conn = self.Pipe()
p = self.Process(target=self._echo, args=(child_conn,))
p.daemon = True
p.start()
child_conn.close() # this might complete before child initializes
msg = latin('hello')
conn.send_bytes(msg)
self.assertEqual(conn.recv_bytes(), msg)
conn.send_bytes(SENTINEL)
conn.close()
p.join()
def test_sendbytes(self):
if self.TYPE != 'processes':
self.skipTest('test not appropriate for {}'.format(self.TYPE))
msg = latin('abcdefghijklmnopqrstuvwxyz')
a, b = self.Pipe()
a.send_bytes(msg)
self.assertEqual(b.recv_bytes(), msg)
a.send_bytes(msg, 5)
self.assertEqual(b.recv_bytes(), msg[5:])
a.send_bytes(msg, 7, 8)
self.assertEqual(b.recv_bytes(), msg[7:7+8])
a.send_bytes(msg, 26)
self.assertEqual(b.recv_bytes(), latin(''))
a.send_bytes(msg, 26, 0)
self.assertEqual(b.recv_bytes(), latin(''))
self.assertRaises(ValueError, a.send_bytes, msg, 27)
self.assertRaises(ValueError, a.send_bytes, msg, 22, 5)
self.assertRaises(ValueError, a.send_bytes, msg, 26, 1)
self.assertRaises(ValueError, a.send_bytes, msg, -1)
self.assertRaises(ValueError, a.send_bytes, msg, 4, -1)
@classmethod
def _is_fd_assigned(cls, fd):
try:
os.fstat(fd)
except OSError as e:
if e.errno == errno.EBADF:
return False
raise
else:
return True
@classmethod
def _writefd(cls, conn, data, create_dummy_fds=False):
if create_dummy_fds:
for i in range(0, 256):
if not cls._is_fd_assigned(i):
os.dup2(conn.fileno(), i)
fd = reduction.recv_handle(conn)
if msvcrt:
fd = msvcrt.open_osfhandle(fd, os.O_WRONLY)
os.write(fd, data)
os.close(fd)
@unittest.skipUnless(HAS_REDUCTION, "test needs multiprocessing.reduction")
def test_fd_transfer(self):
if self.TYPE != 'processes':
self.skipTest("only makes sense with processes")
conn, child_conn = self.Pipe(duplex=True)
p = self.Process(target=self._writefd, args=(child_conn, b"foo"))
p.daemon = True
p.start()
self.addCleanup(test.support.unlink, test.support.TESTFN)
with open(test.support.TESTFN, "wb") as f:
fd = f.fileno()
if msvcrt:
fd = msvcrt.get_osfhandle(fd)
reduction.send_handle(conn, fd, p.pid)
p.join()
with open(test.support.TESTFN, "rb") as f:
self.assertEqual(f.read(), b"foo")
@unittest.skipUnless(HAS_REDUCTION, "test needs multiprocessing.reduction")
@unittest.skipIf(sys.platform == "win32",
"test semantics don't make sense on Windows")
@unittest.skipIf(MAXFD <= 256,
"largest assignable fd number is too small")
@unittest.skipUnless(hasattr(os, "dup2"),
"test needs os.dup2()")
def test_large_fd_transfer(self):
# With fd > 256 (issue #11657)
if self.TYPE != 'processes':
self.skipTest("only makes sense with processes")
conn, child_conn = self.Pipe(duplex=True)
p = self.Process(target=self._writefd, args=(child_conn, b"bar", True))
p.daemon = True
p.start()
self.addCleanup(test.support.unlink, test.support.TESTFN)
with open(test.support.TESTFN, "wb") as f:
fd = f.fileno()
for newfd in range(256, MAXFD):
if not self._is_fd_assigned(newfd):
break
else:
self.fail("could not find an unassigned large file descriptor")
os.dup2(fd, newfd)
try:
reduction.send_handle(conn, newfd, p.pid)
finally:
os.close(newfd)
p.join()
with open(test.support.TESTFN, "rb") as f:
self.assertEqual(f.read(), b"bar")
@classmethod
def _send_data_without_fd(self, conn):
os.write(conn.fileno(), b"\0")
@unittest.skipUnless(HAS_REDUCTION, "test needs multiprocessing.reduction")
@unittest.skipIf(sys.platform == "win32", "doesn't make sense on Windows")
def test_missing_fd_transfer(self):
# Check that exception is raised when received data is not
# accompanied by a file descriptor in ancillary data.
if self.TYPE != 'processes':
self.skipTest("only makes sense with processes")
conn, child_conn = self.Pipe(duplex=True)
p = self.Process(target=self._send_data_without_fd, args=(child_conn,))
p.daemon = True
p.start()
self.assertRaises(RuntimeError, reduction.recv_handle, conn)
p.join()
def test_context(self):
a, b = self.Pipe()
with a, b:
a.send(1729)
self.assertEqual(b.recv(), 1729)
if self.TYPE == 'processes':
self.assertFalse(a.closed)
self.assertFalse(b.closed)
if self.TYPE == 'processes':
self.assertTrue(a.closed)
self.assertTrue(b.closed)
self.assertRaises(OSError, a.recv)
self.assertRaises(OSError, b.recv)
class _TestListener(BaseTestCase):
ALLOWED_TYPES = ('processes',)
def test_multiple_bind(self):
for family in self.connection.families:
l = self.connection.Listener(family=family)
self.addCleanup(l.close)
self.assertRaises(OSError, self.connection.Listener,
l.address, family)
def test_context(self):
with self.connection.Listener() as l:
with self.connection.Client(l.address) as c:
with l.accept() as d:
c.send(1729)
self.assertEqual(d.recv(), 1729)
if self.TYPE == 'processes':
self.assertRaises(OSError, l.accept)
class _TestListenerClient(BaseTestCase):
ALLOWED_TYPES = ('processes', 'threads')
@classmethod
def _test(cls, address):
conn = cls.connection.Client(address)
conn.send('hello')
conn.close()
def test_listener_client(self):
for family in self.connection.families:
l = self.connection.Listener(family=family)
p = self.Process(target=self._test, args=(l.address,))
p.daemon = True
p.start()
conn = l.accept()
self.assertEqual(conn.recv(), 'hello')
p.join()
l.close()
def test_issue14725(self):
l = self.connection.Listener()
p = self.Process(target=self._test, args=(l.address,))
p.daemon = True
p.start()
time.sleep(1)
# On Windows the client process should by now have connected,
# written data and closed the pipe handle by now. This causes
# ConnectNamdedPipe() to fail with ERROR_NO_DATA. See Issue
# 14725.
conn = l.accept()
self.assertEqual(conn.recv(), 'hello')
conn.close()
p.join()
l.close()
def test_issue16955(self):
for fam in self.connection.families:
l = self.connection.Listener(family=fam)
c = self.connection.Client(l.address)
a = l.accept()
a.send_bytes(b"hello")
self.assertTrue(c.poll(1))
a.close()
c.close()
l.close()
class _TestPoll(BaseTestCase):
ALLOWED_TYPES = ('processes', 'threads')
def test_empty_string(self):
a, b = self.Pipe()
self.assertEqual(a.poll(), False)
b.send_bytes(b'')
self.assertEqual(a.poll(), True)
self.assertEqual(a.poll(), True)
@classmethod
def _child_strings(cls, conn, strings):
for s in strings:
time.sleep(0.1)
conn.send_bytes(s)
conn.close()
def test_strings(self):
strings = (b'hello', b'', b'a', b'b', b'', b'bye', b'', b'lop')
a, b = self.Pipe()
p = self.Process(target=self._child_strings, args=(b, strings))
p.start()
for s in strings:
for i in range(200):
if a.poll(0.01):
break
x = a.recv_bytes()
self.assertEqual(s, x)
p.join()
@classmethod
def _child_boundaries(cls, r):
# Polling may "pull" a message in to the child process, but we
# don't want it to pull only part of a message, as that would
# corrupt the pipe for any other processes which might later
# read from it.
r.poll(5)
def test_boundaries(self):
r, w = self.Pipe(False)
p = self.Process(target=self._child_boundaries, args=(r,))
p.start()
time.sleep(2)
L = [b"first", b"second"]
for obj in L:
w.send_bytes(obj)
w.close()
p.join()
self.assertIn(r.recv_bytes(), L)
@classmethod
def _child_dont_merge(cls, b):
b.send_bytes(b'a')
b.send_bytes(b'b')
b.send_bytes(b'cd')
def test_dont_merge(self):
a, b = self.Pipe()
self.assertEqual(a.poll(0.0), False)
self.assertEqual(a.poll(0.1), False)
p = self.Process(target=self._child_dont_merge, args=(b,))
p.start()
self.assertEqual(a.recv_bytes(), b'a')
self.assertEqual(a.poll(1.0), True)
self.assertEqual(a.poll(1.0), True)
self.assertEqual(a.recv_bytes(), b'b')
self.assertEqual(a.poll(1.0), True)
self.assertEqual(a.poll(1.0), True)
self.assertEqual(a.poll(0.0), True)
self.assertEqual(a.recv_bytes(), b'cd')
p.join()
#
# Test of sending connection and socket objects between processes
#
@unittest.skipUnless(HAS_REDUCTION, "test needs multiprocessing.reduction")
class _TestPicklingConnections(BaseTestCase):
ALLOWED_TYPES = ('processes',)
@classmethod
def tearDownClass(cls):
from multiprocessing import resource_sharer
resource_sharer.stop(timeout=TIMEOUT)
@classmethod
def _listener(cls, conn, families):
for fam in families:
l = cls.connection.Listener(family=fam)
conn.send(l.address)
new_conn = l.accept()
conn.send(new_conn)
new_conn.close()
l.close()
l = socket.socket()
l.bind((test.support.HOST, 0))
l.listen()
conn.send(l.getsockname())
new_conn, addr = l.accept()
conn.send(new_conn)
new_conn.close()
l.close()
conn.recv()
@classmethod
def _remote(cls, conn):
for (address, msg) in iter(conn.recv, None):
client = cls.connection.Client(address)
client.send(msg.upper())
client.close()
address, msg = conn.recv()
client = socket.socket()
client.connect(address)
client.sendall(msg.upper())
client.close()
conn.close()
def test_pickling(self):
families = self.connection.families
lconn, lconn0 = self.Pipe()
lp = self.Process(target=self._listener, args=(lconn0, families))
lp.daemon = True
lp.start()
lconn0.close()
rconn, rconn0 = self.Pipe()
rp = self.Process(target=self._remote, args=(rconn0,))
rp.daemon = True
rp.start()
rconn0.close()
for fam in families:
msg = ('This connection uses family %s' % fam).encode('ascii')
address = lconn.recv()
rconn.send((address, msg))
new_conn = lconn.recv()
self.assertEqual(new_conn.recv(), msg.upper())
rconn.send(None)
msg = latin('This connection uses a normal socket')
address = lconn.recv()
rconn.send((address, msg))
new_conn = lconn.recv()
buf = []
while True:
s = new_conn.recv(100)
if not s:
break
buf.append(s)
buf = b''.join(buf)
self.assertEqual(buf, msg.upper())
new_conn.close()
lconn.send(None)
rconn.close()
lconn.close()
lp.join()
rp.join()
@classmethod
def child_access(cls, conn):
w = conn.recv()
w.send('all is well')
w.close()
r = conn.recv()
msg = r.recv()
conn.send(msg*2)
conn.close()
def test_access(self):
# On Windows, if we do not specify a destination pid when
# using DupHandle then we need to be careful to use the
# correct access flags for DuplicateHandle(), or else
# DupHandle.detach() will raise PermissionError. For example,
# for a read only pipe handle we should use
# access=FILE_GENERIC_READ. (Unfortunately
# DUPLICATE_SAME_ACCESS does not work.)
conn, child_conn = self.Pipe()
p = self.Process(target=self.child_access, args=(child_conn,))
p.daemon = True
p.start()
child_conn.close()
r, w = self.Pipe(duplex=False)
conn.send(w)
w.close()
self.assertEqual(r.recv(), 'all is well')
r.close()
r, w = self.Pipe(duplex=False)
conn.send(r)
r.close()
w.send('foobar')
w.close()
self.assertEqual(conn.recv(), 'foobar'*2)
p.join()
#
#
#
class _TestHeap(BaseTestCase):
ALLOWED_TYPES = ('processes',)
def setUp(self):
super().setUp()
# Make pristine heap for these tests
self.old_heap = multiprocessing.heap.BufferWrapper._heap
multiprocessing.heap.BufferWrapper._heap = multiprocessing.heap.Heap()
def tearDown(self):
multiprocessing.heap.BufferWrapper._heap = self.old_heap
super().tearDown()
def test_heap(self):
iterations = 5000
maxblocks = 50
blocks = []
# get the heap object
heap = multiprocessing.heap.BufferWrapper._heap
heap._DISCARD_FREE_SPACE_LARGER_THAN = 0
# create and destroy lots of blocks of different sizes
for i in range(iterations):
size = int(random.lognormvariate(0, 1) * 1000)
b = multiprocessing.heap.BufferWrapper(size)
blocks.append(b)
if len(blocks) > maxblocks:
i = random.randrange(maxblocks)
del blocks[i]
del b
# verify the state of the heap
with heap._lock:
all = []
free = 0
occupied = 0
for L in list(heap._len_to_seq.values()):
# count all free blocks in arenas
for arena, start, stop in L:
all.append((heap._arenas.index(arena), start, stop,
stop-start, 'free'))
free += (stop-start)
for arena, arena_blocks in heap._allocated_blocks.items():
# count all allocated blocks in arenas
for start, stop in arena_blocks:
all.append((heap._arenas.index(arena), start, stop,
stop-start, 'occupied'))
occupied += (stop-start)
self.assertEqual(free + occupied,
sum(arena.size for arena in heap._arenas))
all.sort()
for i in range(len(all)-1):
(arena, start, stop) = all[i][:3]
(narena, nstart, nstop) = all[i+1][:3]
if arena != narena:
# Two different arenas
self.assertEqual(stop, heap._arenas[arena].size) # last block
self.assertEqual(nstart, 0) # first block
else:
# Same arena: two adjacent blocks
self.assertEqual(stop, nstart)
# test free'ing all blocks
random.shuffle(blocks)
while blocks:
blocks.pop()
self.assertEqual(heap._n_frees, heap._n_mallocs)
self.assertEqual(len(heap._pending_free_blocks), 0)
self.assertEqual(len(heap._arenas), 0)
self.assertEqual(len(heap._allocated_blocks), 0, heap._allocated_blocks)
self.assertEqual(len(heap._len_to_seq), 0)
def test_free_from_gc(self):
# Check that freeing of blocks by the garbage collector doesn't deadlock
# (issue #12352).
# Make sure the GC is enabled, and set lower collection thresholds to
# make collections more frequent (and increase the probability of
# deadlock).
if not gc.isenabled():
gc.enable()
self.addCleanup(gc.disable)
thresholds = gc.get_threshold()
self.addCleanup(gc.set_threshold, *thresholds)
gc.set_threshold(10)
# perform numerous block allocations, with cyclic references to make
# sure objects are collected asynchronously by the gc
for i in range(5000):
a = multiprocessing.heap.BufferWrapper(1)
b = multiprocessing.heap.BufferWrapper(1)
# circular references
a.buddy = b
b.buddy = a
#
#
#
class _Foo(Structure):
_fields_ = [
('x', c_int),
('y', c_double),
('z', c_longlong,)
]
class _TestSharedCTypes(BaseTestCase):
ALLOWED_TYPES = ('processes',)
def setUp(self):
if not HAS_SHAREDCTYPES:
self.skipTest("requires multiprocessing.sharedctypes")
@classmethod
def _double(cls, x, y, z, foo, arr, string):
x.value *= 2
y.value *= 2
z.value *= 2
foo.x *= 2
foo.y *= 2
string.value *= 2
for i in range(len(arr)):
arr[i] *= 2
def test_sharedctypes(self, lock=False):
x = Value('i', 7, lock=lock)
y = Value(c_double, 1.0/3.0, lock=lock)
z = Value(c_longlong, 2 ** 33, lock=lock)
foo = Value(_Foo, 3, 2, lock=lock)
arr = self.Array('d', list(range(10)), lock=lock)
string = self.Array('c', 20, lock=lock)
string.value = latin('hello')
p = self.Process(target=self._double, args=(x, y, z, foo, arr, string))
p.daemon = True
p.start()
p.join()
self.assertEqual(x.value, 14)
self.assertAlmostEqual(y.value, 2.0/3.0)
self.assertEqual(z.value, 2 ** 34)
self.assertEqual(foo.x, 6)
self.assertAlmostEqual(foo.y, 4.0)
for i in range(10):
self.assertAlmostEqual(arr[i], i*2)
self.assertEqual(string.value, latin('hellohello'))
def test_synchronize(self):
self.test_sharedctypes(lock=True)
def test_copy(self):
foo = _Foo(2, 5.0, 2 ** 33)
bar = copy(foo)
foo.x = 0
foo.y = 0
foo.z = 0
self.assertEqual(bar.x, 2)
self.assertAlmostEqual(bar.y, 5.0)
self.assertEqual(bar.z, 2 ** 33)
#
#
#
class _TestFinalize(BaseTestCase):
ALLOWED_TYPES = ('processes',)
def setUp(self):
self.registry_backup = util._finalizer_registry.copy()
util._finalizer_registry.clear()
def tearDown(self):
self.assertFalse(util._finalizer_registry)
util._finalizer_registry.update(self.registry_backup)
@classmethod
def _test_finalize(cls, conn):
class Foo(object):
pass
a = Foo()
util.Finalize(a, conn.send, args=('a',))
del a # triggers callback for a
b = Foo()
close_b = util.Finalize(b, conn.send, args=('b',))
close_b() # triggers callback for b
close_b() # does nothing because callback has already been called
del b # does nothing because callback has already been called
c = Foo()
util.Finalize(c, conn.send, args=('c',))
d10 = Foo()
util.Finalize(d10, conn.send, args=('d10',), exitpriority=1)
d01 = Foo()
util.Finalize(d01, conn.send, args=('d01',), exitpriority=0)
d02 = Foo()
util.Finalize(d02, conn.send, args=('d02',), exitpriority=0)
d03 = Foo()
util.Finalize(d03, conn.send, args=('d03',), exitpriority=0)
util.Finalize(None, conn.send, args=('e',), exitpriority=-10)
util.Finalize(None, conn.send, args=('STOP',), exitpriority=-100)
# call multiprocessing's cleanup function then exit process without
# garbage collecting locals
util._exit_function()
conn.close()
os._exit(0)
def test_finalize(self):
conn, child_conn = self.Pipe()
p = self.Process(target=self._test_finalize, args=(child_conn,))
p.daemon = True
p.start()
p.join()
result = [obj for obj in iter(conn.recv, 'STOP')]
self.assertEqual(result, ['a', 'b', 'd10', 'd03', 'd02', 'd01', 'e'])
def test_thread_safety(self):
# bpo-24484: _run_finalizers() should be thread-safe
def cb():
pass
class Foo(object):
def __init__(self):
self.ref = self # create reference cycle
# insert finalizer at random key
util.Finalize(self, cb, exitpriority=random.randint(1, 100))
finish = False
exc = None
def run_finalizers():
nonlocal exc
while not finish:
time.sleep(random.random() * 1e-1)
try:
# A GC run will eventually happen during this,
# collecting stale Foo's and mutating the registry
util._run_finalizers()
except Exception as e:
exc = e
def make_finalizers():
nonlocal exc
d = {}
while not finish:
try:
# Old Foo's get gradually replaced and later
# collected by the GC (because of the cyclic ref)
d[random.getrandbits(5)] = {Foo() for i in range(10)}
except Exception as e:
exc = e
d.clear()
old_interval = sys.getswitchinterval()
old_threshold = gc.get_threshold()
try:
sys.setswitchinterval(1e-6)
gc.set_threshold(5, 5, 5)
threads = [threading.Thread(target=run_finalizers),
threading.Thread(target=make_finalizers)]
with test.support.start_threads(threads):
time.sleep(4.0) # Wait a bit to trigger race condition
finish = True
if exc is not None:
raise exc
finally:
sys.setswitchinterval(old_interval)
gc.set_threshold(*old_threshold)
gc.collect() # Collect remaining Foo's
#
# Test that from ... import * works for each module
#
class _TestImportStar(unittest.TestCase):
def get_module_names(self):
import glob
folder = os.path.dirname(multiprocessing.__file__)
pattern = os.path.join(folder, '*.py')
files = glob.glob(pattern)
modules = [os.path.splitext(os.path.split(f)[1])[0] for f in files]
modules = ['multiprocessing.' + m for m in modules]
modules.remove('multiprocessing.__init__')
modules.append('multiprocessing')
return modules
def test_import(self):
modules = self.get_module_names()
if sys.platform == 'win32':
modules.remove('multiprocessing.popen_fork')
modules.remove('multiprocessing.popen_forkserver')
modules.remove('multiprocessing.popen_spawn_posix')
else:
modules.remove('multiprocessing.popen_spawn_win32')
if not HAS_REDUCTION:
modules.remove('multiprocessing.popen_forkserver')
if c_int is None:
# This module requires _ctypes
modules.remove('multiprocessing.sharedctypes')
for name in modules:
__import__(name)
mod = sys.modules[name]
self.assertTrue(hasattr(mod, '__all__'), name)
for attr in mod.__all__:
self.assertTrue(
hasattr(mod, attr),
'%r does not have attribute %r' % (mod, attr)
)
#
# Quick test that logging works -- does not test logging output
#
class _TestLogging(BaseTestCase):
ALLOWED_TYPES = ('processes',)
def test_enable_logging(self):
logger = multiprocessing.get_logger()
logger.setLevel(util.SUBWARNING)
self.assertTrue(logger is not None)
logger.debug('this will not be printed')
logger.info('nor will this')
logger.setLevel(LOG_LEVEL)
@classmethod
def _test_level(cls, conn):
logger = multiprocessing.get_logger()
conn.send(logger.getEffectiveLevel())
def test_level(self):
LEVEL1 = 32
LEVEL2 = 37
logger = multiprocessing.get_logger()
root_logger = logging.getLogger()
root_level = root_logger.level
reader, writer = multiprocessing.Pipe(duplex=False)
logger.setLevel(LEVEL1)
p = self.Process(target=self._test_level, args=(writer,))
p.start()
self.assertEqual(LEVEL1, reader.recv())
p.join()
p.close()
logger.setLevel(logging.NOTSET)
root_logger.setLevel(LEVEL2)
p = self.Process(target=self._test_level, args=(writer,))
p.start()
self.assertEqual(LEVEL2, reader.recv())
p.join()
p.close()
root_logger.setLevel(root_level)
logger.setLevel(level=LOG_LEVEL)
# class _TestLoggingProcessName(BaseTestCase):
#
# def handle(self, record):
# assert record.processName == multiprocessing.current_process().name
# self.__handled = True
#
# def test_logging(self):
# handler = logging.Handler()
# handler.handle = self.handle
# self.__handled = False
# # Bypass getLogger() and side-effects
# logger = logging.getLoggerClass()(
# 'multiprocessing.test.TestLoggingProcessName')
# logger.addHandler(handler)
# logger.propagate = False
#
# logger.warn('foo')
# assert self.__handled
#
# Check that Process.join() retries if os.waitpid() fails with EINTR
#
class _TestPollEintr(BaseTestCase):
ALLOWED_TYPES = ('processes',)
@classmethod
def _killer(cls, pid):
time.sleep(0.1)
os.kill(pid, signal.SIGUSR1)
@unittest.skipUnless(hasattr(signal, 'SIGUSR1'), 'requires SIGUSR1')
def test_poll_eintr(self):
got_signal = [False]
def record(*args):
got_signal[0] = True
pid = os.getpid()
oldhandler = signal.signal(signal.SIGUSR1, record)
try:
killer = self.Process(target=self._killer, args=(pid,))
killer.start()
try:
p = self.Process(target=time.sleep, args=(2,))
p.start()
p.join()
finally:
killer.join()
self.assertTrue(got_signal[0])
self.assertEqual(p.exitcode, 0)
finally:
signal.signal(signal.SIGUSR1, oldhandler)
#
# Test to verify handle verification, see issue 3321
#
class TestInvalidHandle(unittest.TestCase):
@unittest.skipIf(WIN32, "skipped on Windows")
def test_invalid_handles(self):
conn = multiprocessing.connection.Connection(44977608)
# check that poll() doesn't crash
try:
conn.poll()
except (ValueError, OSError):
pass
finally:
# Hack private attribute _handle to avoid printing an error
# in conn.__del__
conn._handle = None
self.assertRaises((ValueError, OSError),
multiprocessing.connection.Connection, -1)
class OtherTest(unittest.TestCase):
# TODO: add more tests for deliver/answer challenge.
def test_deliver_challenge_auth_failure(self):
class _FakeConnection(object):
def recv_bytes(self, size):
return b'something bogus'
def send_bytes(self, data):
pass
self.assertRaises(multiprocessing.AuthenticationError,
multiprocessing.connection.deliver_challenge,
_FakeConnection(), b'abc')
def test_answer_challenge_auth_failure(self):
class _FakeConnection(object):
def __init__(self):
self.count = 0
def recv_bytes(self, size):
self.count += 1
if self.count == 1:
return multiprocessing.connection.CHALLENGE
elif self.count == 2:
return b'something bogus'
return b''
def send_bytes(self, data):
pass
self.assertRaises(multiprocessing.AuthenticationError,
multiprocessing.connection.answer_challenge,
_FakeConnection(), b'abc')
#
# Test Manager.start()/Pool.__init__() initializer feature - see issue 5585
#
def initializer(ns):
ns.test += 1
class TestInitializers(unittest.TestCase):
def setUp(self):
self.mgr = multiprocessing.Manager()
self.ns = self.mgr.Namespace()
self.ns.test = 0
def tearDown(self):
self.mgr.shutdown()
self.mgr.join()
def test_manager_initializer(self):
m = multiprocessing.managers.SyncManager()
self.assertRaises(TypeError, m.start, 1)
m.start(initializer, (self.ns,))
self.assertEqual(self.ns.test, 1)
m.shutdown()
m.join()
def test_pool_initializer(self):
self.assertRaises(TypeError, multiprocessing.Pool, initializer=1)
p = multiprocessing.Pool(1, initializer, (self.ns,))
p.close()
p.join()
self.assertEqual(self.ns.test, 1)
#
# Issue 5155, 5313, 5331: Test process in processes
# Verifies os.close(sys.stdin.fileno) vs. sys.stdin.close() behavior
#
def _this_sub_process(q):
try:
item = q.get(block=False)
except pyqueue.Empty:
pass
def _test_process():
queue = multiprocessing.Queue()
subProc = multiprocessing.Process(target=_this_sub_process, args=(queue,))
subProc.daemon = True
subProc.start()
subProc.join()
def _afunc(x):
return x*x
def pool_in_process():
pool = multiprocessing.Pool(processes=4)
x = pool.map(_afunc, [1, 2, 3, 4, 5, 6, 7])
pool.close()
pool.join()
class _file_like(object):
def __init__(self, delegate):
self._delegate = delegate
self._pid = None
@property
def cache(self):
pid = os.getpid()
# There are no race conditions since fork keeps only the running thread
if pid != self._pid:
self._pid = pid
self._cache = []
return self._cache
def write(self, data):
self.cache.append(data)
def flush(self):
self._delegate.write(''.join(self.cache))
self._cache = []
class TestStdinBadfiledescriptor(unittest.TestCase):
def test_queue_in_process(self):
proc = multiprocessing.Process(target=_test_process)
proc.start()
proc.join()
def test_pool_in_process(self):
p = multiprocessing.Process(target=pool_in_process)
p.start()
p.join()
def test_flushing(self):
sio = io.StringIO()
flike = _file_like(sio)
flike.write('foo')
proc = multiprocessing.Process(target=lambda: flike.flush())
flike.flush()
assert sio.getvalue() == 'foo'
class TestWait(unittest.TestCase):
@classmethod
def _child_test_wait(cls, w, slow):
for i in range(10):
if slow:
time.sleep(random.random()*0.1)
w.send((i, os.getpid()))
w.close()
def test_wait(self, slow=False):
from multiprocessing.connection import wait
readers = []
procs = []
messages = []
for i in range(4):
r, w = multiprocessing.Pipe(duplex=False)
p = multiprocessing.Process(target=self._child_test_wait, args=(w, slow))
p.daemon = True
p.start()
w.close()
readers.append(r)
procs.append(p)
self.addCleanup(p.join)
while readers:
for r in wait(readers):
try:
msg = r.recv()
except EOFError:
readers.remove(r)
r.close()
else:
messages.append(msg)
messages.sort()
expected = sorted((i, p.pid) for i in range(10) for p in procs)
self.assertEqual(messages, expected)
@classmethod
def _child_test_wait_socket(cls, address, slow):
s = socket.socket()
s.connect(address)
for i in range(10):
if slow:
time.sleep(random.random()*0.1)
s.sendall(('%s\n' % i).encode('ascii'))
s.close()
def test_wait_socket(self, slow=False):
from multiprocessing.connection import wait
l = socket.socket()
l.bind((test.support.HOST, 0))
l.listen()
addr = l.getsockname()
readers = []
procs = []
dic = {}
for i in range(4):
p = multiprocessing.Process(target=self._child_test_wait_socket,
args=(addr, slow))
p.daemon = True
p.start()
procs.append(p)
self.addCleanup(p.join)
for i in range(4):
r, _ = l.accept()
readers.append(r)
dic[r] = []
l.close()
while readers:
for r in wait(readers):
msg = r.recv(32)
if not msg:
readers.remove(r)
r.close()
else:
dic[r].append(msg)
expected = ''.join('%s\n' % i for i in range(10)).encode('ascii')
for v in dic.values():
self.assertEqual(b''.join(v), expected)
def test_wait_slow(self):
self.test_wait(True)
def test_wait_socket_slow(self):
self.test_wait_socket(True)
def test_wait_timeout(self):
from multiprocessing.connection import wait
expected = 5
a, b = multiprocessing.Pipe()
start = time.monotonic()
res = wait([a, b], expected)
delta = time.monotonic() - start
self.assertEqual(res, [])
self.assertLess(delta, expected * 2)
self.assertGreater(delta, expected * 0.5)
b.send(None)
start = time.monotonic()
res = wait([a, b], 20)
delta = time.monotonic() - start
self.assertEqual(res, [a])
self.assertLess(delta, 0.4)
@classmethod
def signal_and_sleep(cls, sem, period):
sem.release()
time.sleep(period)
def test_wait_integer(self):
from multiprocessing.connection import wait
expected = 3
sorted_ = lambda l: sorted(l, key=lambda x: id(x))
sem = multiprocessing.Semaphore(0)
a, b = multiprocessing.Pipe()
p = multiprocessing.Process(target=self.signal_and_sleep,
args=(sem, expected))
p.start()
self.assertIsInstance(p.sentinel, int)
self.assertTrue(sem.acquire(timeout=20))
start = time.monotonic()
res = wait([a, p.sentinel, b], expected + 20)
delta = time.monotonic() - start
self.assertEqual(res, [p.sentinel])
self.assertLess(delta, expected + 2)
self.assertGreater(delta, expected - 2)
a.send(None)
start = time.monotonic()
res = wait([a, p.sentinel, b], 20)
delta = time.monotonic() - start
self.assertEqual(sorted_(res), sorted_([p.sentinel, b]))
self.assertLess(delta, 0.4)
b.send(None)
start = time.monotonic()
res = wait([a, p.sentinel, b], 20)
delta = time.monotonic() - start
self.assertEqual(sorted_(res), sorted_([a, p.sentinel, b]))
self.assertLess(delta, 0.4)
p.terminate()
p.join()
def test_neg_timeout(self):
from multiprocessing.connection import wait
a, b = multiprocessing.Pipe()
t = time.monotonic()
res = wait([a], timeout=-1)
t = time.monotonic() - t
self.assertEqual(res, [])
self.assertLess(t, 1)
a.close()
b.close()
#
# Issue 14151: Test invalid family on invalid environment
#
class TestInvalidFamily(unittest.TestCase):
@unittest.skipIf(WIN32, "skipped on Windows")
def test_invalid_family(self):
with self.assertRaises(ValueError):
multiprocessing.connection.Listener(r'\\.\test')
@unittest.skipUnless(WIN32, "skipped on non-Windows platforms")
def test_invalid_family_win32(self):
with self.assertRaises(ValueError):
multiprocessing.connection.Listener('/var/test.pipe')
#
# Issue 12098: check sys.flags of child matches that for parent
#
class TestFlags(unittest.TestCase):
@classmethod
def run_in_grandchild(cls, conn):
conn.send(tuple(sys.flags))
@classmethod
def run_in_child(cls):
import json
r, w = multiprocessing.Pipe(duplex=False)
p = multiprocessing.Process(target=cls.run_in_grandchild, args=(w,))
p.start()
grandchild_flags = r.recv()
p.join()
r.close()
w.close()
flags = (tuple(sys.flags), grandchild_flags)
print(json.dumps(flags))
def test_flags(self):
import json, subprocess
# start child process using unusual flags
prog = ('from test._test_multiprocessing import TestFlags; ' +
'TestFlags.run_in_child()')
data = subprocess.check_output(
[sys.executable, '-E', '-S', '-O', '-c', prog])
child_flags, grandchild_flags = json.loads(data.decode('ascii'))
self.assertEqual(child_flags, grandchild_flags)
#
# Test interaction with socket timeouts - see Issue #6056
#
class TestTimeouts(unittest.TestCase):
@classmethod
def _test_timeout(cls, child, address):
time.sleep(1)
child.send(123)
child.close()
conn = multiprocessing.connection.Client(address)
conn.send(456)
conn.close()
def test_timeout(self):
old_timeout = socket.getdefaulttimeout()
try:
socket.setdefaulttimeout(0.1)
parent, child = multiprocessing.Pipe(duplex=True)
l = multiprocessing.connection.Listener(family='AF_INET')
p = multiprocessing.Process(target=self._test_timeout,
args=(child, l.address))
p.start()
child.close()
self.assertEqual(parent.recv(), 123)
parent.close()
conn = l.accept()
self.assertEqual(conn.recv(), 456)
conn.close()
l.close()
join_process(p)
finally:
socket.setdefaulttimeout(old_timeout)
#
# Test what happens with no "if __name__ == '__main__'"
#
class TestNoForkBomb(unittest.TestCase):
def test_noforkbomb(self):
sm = multiprocessing.get_start_method()
name = os.path.join(os.path.dirname(__file__), 'mp_fork_bomb.py')
if sm != 'fork':
rc, out, err = test.support.script_helper.assert_python_failure(name, sm)
self.assertEqual(out, b'')
self.assertIn(b'RuntimeError', err)
else:
rc, out, err = test.support.script_helper.assert_python_ok(name, sm)
self.assertEqual(out.rstrip(), b'123')
self.assertEqual(err, b'')
#
# Issue #17555: ForkAwareThreadLock
#
class TestForkAwareThreadLock(unittest.TestCase):
# We recursively start processes. Issue #17555 meant that the
# after fork registry would get duplicate entries for the same
# lock. The size of the registry at generation n was ~2**n.
@classmethod
def child(cls, n, conn):
if n > 1:
p = multiprocessing.Process(target=cls.child, args=(n-1, conn))
p.start()
conn.close()
join_process(p)
else:
conn.send(len(util._afterfork_registry))
conn.close()
def test_lock(self):
r, w = multiprocessing.Pipe(False)
l = util.ForkAwareThreadLock()
old_size = len(util._afterfork_registry)
p = multiprocessing.Process(target=self.child, args=(5, w))
p.start()
w.close()
new_size = r.recv()
join_process(p)
self.assertLessEqual(new_size, old_size)
#
# Check that non-forked child processes do not inherit unneeded fds/handles
#
class TestCloseFds(unittest.TestCase):
def get_high_socket_fd(self):
if WIN32:
# The child process will not have any socket handles, so
# calling socket.fromfd() should produce WSAENOTSOCK even
# if there is a handle of the same number.
return socket.socket().detach()
else:
# We want to produce a socket with an fd high enough that a
# freshly created child process will not have any fds as high.
fd = socket.socket().detach()
to_close = []
while fd < 50:
to_close.append(fd)
fd = os.dup(fd)
for x in to_close:
os.close(x)
return fd
def close(self, fd):
if WIN32:
socket.socket(socket.AF_INET, socket.SOCK_STREAM, fileno=fd).close()
else:
os.close(fd)
@classmethod
def _test_closefds(cls, conn, fd):
try:
s = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
except Exception as e:
conn.send(e)
else:
s.close()
conn.send(None)
def test_closefd(self):
if not HAS_REDUCTION:
raise unittest.SkipTest('requires fd pickling')
reader, writer = multiprocessing.Pipe()
fd = self.get_high_socket_fd()
try:
p = multiprocessing.Process(target=self._test_closefds,
args=(writer, fd))
p.start()
writer.close()
e = reader.recv()
join_process(p)
finally:
self.close(fd)
writer.close()
reader.close()
if multiprocessing.get_start_method() == 'fork':
self.assertIs(e, None)
else:
WSAENOTSOCK = 10038
self.assertIsInstance(e, OSError)
self.assertTrue(e.errno == errno.EBADF or
e.winerror == WSAENOTSOCK, e)
#
# Issue #17097: EINTR should be ignored by recv(), send(), accept() etc
#
class TestIgnoreEINTR(unittest.TestCase):
# Sending CONN_MAX_SIZE bytes into a multiprocessing pipe must block
CONN_MAX_SIZE = max(support.PIPE_MAX_SIZE, support.SOCK_MAX_SIZE)
@classmethod
def _test_ignore(cls, conn):
def handler(signum, frame):
pass
signal.signal(signal.SIGUSR1, handler)
conn.send('ready')
x = conn.recv()
conn.send(x)
conn.send_bytes(b'x' * cls.CONN_MAX_SIZE)
@unittest.skipUnless(hasattr(signal, 'SIGUSR1'), 'requires SIGUSR1')
def test_ignore(self):
conn, child_conn = multiprocessing.Pipe()
try:
p = multiprocessing.Process(target=self._test_ignore,
args=(child_conn,))
p.daemon = True
p.start()
child_conn.close()
self.assertEqual(conn.recv(), 'ready')
time.sleep(0.1)
os.kill(p.pid, signal.SIGUSR1)
time.sleep(0.1)
conn.send(1234)
self.assertEqual(conn.recv(), 1234)
time.sleep(0.1)
os.kill(p.pid, signal.SIGUSR1)
self.assertEqual(conn.recv_bytes(), b'x' * self.CONN_MAX_SIZE)
time.sleep(0.1)
p.join()
finally:
conn.close()
@classmethod
def _test_ignore_listener(cls, conn):
def handler(signum, frame):
pass
signal.signal(signal.SIGUSR1, handler)
with multiprocessing.connection.Listener() as l:
conn.send(l.address)
a = l.accept()
a.send('welcome')
@unittest.skipUnless(hasattr(signal, 'SIGUSR1'), 'requires SIGUSR1')
def test_ignore_listener(self):
conn, child_conn = multiprocessing.Pipe()
try:
p = multiprocessing.Process(target=self._test_ignore_listener,
args=(child_conn,))
p.daemon = True
p.start()
child_conn.close()
address = conn.recv()
time.sleep(0.1)
os.kill(p.pid, signal.SIGUSR1)
time.sleep(0.1)
client = multiprocessing.connection.Client(address)
self.assertEqual(client.recv(), 'welcome')
p.join()
finally:
conn.close()
class TestStartMethod(unittest.TestCase):
@classmethod
def _check_context(cls, conn):
conn.send(multiprocessing.get_start_method())
def check_context(self, ctx):
r, w = ctx.Pipe(duplex=False)
p = ctx.Process(target=self._check_context, args=(w,))
p.start()
w.close()
child_method = r.recv()
r.close()
p.join()
self.assertEqual(child_method, ctx.get_start_method())
def test_context(self):
for method in ('fork', 'spawn', 'forkserver'):
try:
ctx = multiprocessing.get_context(method)
except ValueError:
continue
self.assertEqual(ctx.get_start_method(), method)
self.assertIs(ctx.get_context(), ctx)
self.assertRaises(ValueError, ctx.set_start_method, 'spawn')
self.assertRaises(ValueError, ctx.set_start_method, None)
self.check_context(ctx)
def test_set_get(self):
multiprocessing.set_forkserver_preload(PRELOAD)
count = 0
old_method = multiprocessing.get_start_method()
try:
for method in ('fork', 'spawn', 'forkserver'):
try:
multiprocessing.set_start_method(method, force=True)
except ValueError:
continue
self.assertEqual(multiprocessing.get_start_method(), method)
ctx = multiprocessing.get_context()
self.assertEqual(ctx.get_start_method(), method)
self.assertTrue(type(ctx).__name__.lower().startswith(method))
self.assertTrue(
ctx.Process.__name__.lower().startswith(method))
self.check_context(multiprocessing)
count += 1
finally:
multiprocessing.set_start_method(old_method, force=True)
self.assertGreaterEqual(count, 1)
def test_get_all(self):
methods = multiprocessing.get_all_start_methods()
if sys.platform == 'win32':
self.assertEqual(methods, ['spawn'])
else:
self.assertTrue(methods == ['fork', 'spawn'] or
methods == ['fork', 'spawn', 'forkserver'])
def test_preload_resources(self):
if multiprocessing.get_start_method() != 'forkserver':
self.skipTest("test only relevant for 'forkserver' method")
name = os.path.join(os.path.dirname(__file__), 'mp_preload.py')
rc, out, err = test.support.script_helper.assert_python_ok(name)
out = out.decode()
err = err.decode()
if out.rstrip() != 'ok' or err != '':
print(out)
print(err)
self.fail("failed spawning forkserver or grandchild")
@unittest.skipIf(sys.platform == "win32",
"test semantics don't make sense on Windows")
class TestSemaphoreTracker(unittest.TestCase):
def test_semaphore_tracker(self):
#
# Check that killing process does not leak named semaphores
#
import subprocess
cmd = '''if 1:
import multiprocessing as mp, time, os
mp.set_start_method("spawn")
lock1 = mp.Lock()
lock2 = mp.Lock()
os.write(%d, lock1._semlock.name.encode("ascii") + b"\\n")
os.write(%d, lock2._semlock.name.encode("ascii") + b"\\n")
time.sleep(10)
'''
r, w = os.pipe()
p = subprocess.Popen([sys.executable,
'-E', '-c', cmd % (w, w)],
pass_fds=[w],
stderr=subprocess.PIPE)
os.close(w)
with open(r, 'rb', closefd=True) as f:
name1 = f.readline().rstrip().decode('ascii')
name2 = f.readline().rstrip().decode('ascii')
_multiprocessing.sem_unlink(name1)
p.terminate()
p.wait()
time.sleep(2.0)
with self.assertRaises(OSError) as ctx:
_multiprocessing.sem_unlink(name2)
# docs say it should be ENOENT, but OSX seems to give EINVAL
self.assertIn(ctx.exception.errno, (errno.ENOENT, errno.EINVAL))
err = p.stderr.read().decode('utf-8')
p.stderr.close()
expected = 'semaphore_tracker: There appear to be 2 leaked semaphores'
self.assertRegex(err, expected)
self.assertRegex(err, r'semaphore_tracker: %r: \[Errno' % name1)
def check_semaphore_tracker_death(self, signum, should_die):
# bpo-31310: if the semaphore tracker process has died, it should
# be restarted implicitly.
from multiprocessing.semaphore_tracker import _semaphore_tracker
pid = _semaphore_tracker._pid
if pid is not None:
os.kill(pid, signal.SIGKILL)
os.waitpid(pid, 0)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
_semaphore_tracker.ensure_running()
pid = _semaphore_tracker._pid
os.kill(pid, signum)
time.sleep(1.0) # give it time to die
ctx = multiprocessing.get_context("spawn")
with warnings.catch_warnings(record=True) as all_warn:
warnings.simplefilter("always")
sem = ctx.Semaphore()
sem.acquire()
sem.release()
wr = weakref.ref(sem)
# ensure `sem` gets collected, which triggers communication with
# the semaphore tracker
del sem
gc.collect()
self.assertIsNone(wr())
if should_die:
self.assertEqual(len(all_warn), 1)
the_warn = all_warn[0]
self.assertTrue(issubclass(the_warn.category, UserWarning))
self.assertTrue("semaphore_tracker: process died"
in str(the_warn.message))
else:
self.assertEqual(len(all_warn), 0)
def test_semaphore_tracker_sigint(self):
# Catchable signal (ignored by semaphore tracker)
self.check_semaphore_tracker_death(signal.SIGINT, False)
def test_semaphore_tracker_sigterm(self):
# Catchable signal (ignored by semaphore tracker)
self.check_semaphore_tracker_death(signal.SIGTERM, False)
def test_semaphore_tracker_sigkill(self):
# Uncatchable signal.
self.check_semaphore_tracker_death(signal.SIGKILL, True)
class TestSimpleQueue(unittest.TestCase):
@classmethod
def _test_empty(cls, queue, child_can_start, parent_can_continue):
child_can_start.wait()
# issue 30301, could fail under spawn and forkserver
try:
queue.put(queue.empty())
queue.put(queue.empty())
finally:
parent_can_continue.set()
def test_empty(self):
queue = multiprocessing.SimpleQueue()
child_can_start = multiprocessing.Event()
parent_can_continue = multiprocessing.Event()
proc = multiprocessing.Process(
target=self._test_empty,
args=(queue, child_can_start, parent_can_continue)
)
proc.daemon = True
proc.start()
self.assertTrue(queue.empty())
child_can_start.set()
parent_can_continue.wait()
self.assertFalse(queue.empty())
self.assertEqual(queue.get(), True)
self.assertEqual(queue.get(), False)
self.assertTrue(queue.empty())
proc.join()
class TestPoolNotLeakOnFailure(unittest.TestCase):
def test_release_unused_processes(self):
# Issue #19675: During pool creation, if we can't create a process,
# don't leak already created ones.
will_fail_in = 3
forked_processes = []
class FailingForkProcess:
def __init__(self, **kwargs):
self.name = 'Fake Process'
self.exitcode = None
self.state = None
forked_processes.append(self)
def start(self):
nonlocal will_fail_in
if will_fail_in <= 0:
raise OSError("Manually induced OSError")
will_fail_in -= 1
self.state = 'started'
def terminate(self):
self.state = 'stopping'
def join(self):
if self.state == 'stopping':
self.state = 'stopped'
def is_alive(self):
return self.state == 'started' or self.state == 'stopping'
with self.assertRaisesRegex(OSError, 'Manually induced OSError'):
p = multiprocessing.pool.Pool(5, context=unittest.mock.MagicMock(
Process=FailingForkProcess))
p.close()
p.join()
self.assertFalse(
any(process.is_alive() for process in forked_processes))
class MiscTestCase(unittest.TestCase):
def test__all__(self):
# Just make sure names in blacklist are excluded
support.check__all__(self, multiprocessing, extra=multiprocessing.__all__,
blacklist=['SUBDEBUG', 'SUBWARNING'])
#
# Mixins
#
class BaseMixin(object):
@classmethod
def setUpClass(cls):
cls.dangling = (multiprocessing.process._dangling.copy(),
threading._dangling.copy())
@classmethod
def tearDownClass(cls):
# bpo-26762: Some multiprocessing objects like Pool create reference
# cycles. Trigger a garbage collection to break these cycles.
test.support.gc_collect()
processes = set(multiprocessing.process._dangling) - set(cls.dangling[0])
if processes:
test.support.environment_altered = True
print('Warning -- Dangling processes: %s' % processes,
file=sys.stderr)
processes = None
threads = set(threading._dangling) - set(cls.dangling[1])
if threads:
test.support.environment_altered = True
print('Warning -- Dangling threads: %s' % threads,
file=sys.stderr)
threads = None
class ProcessesMixin(BaseMixin):
TYPE = 'processes'
Process = multiprocessing.Process
connection = multiprocessing.connection
current_process = staticmethod(multiprocessing.current_process)
active_children = staticmethod(multiprocessing.active_children)
Pool = staticmethod(multiprocessing.Pool)
Pipe = staticmethod(multiprocessing.Pipe)
Queue = staticmethod(multiprocessing.Queue)
JoinableQueue = staticmethod(multiprocessing.JoinableQueue)
Lock = staticmethod(multiprocessing.Lock)
RLock = staticmethod(multiprocessing.RLock)
Semaphore = staticmethod(multiprocessing.Semaphore)
BoundedSemaphore = staticmethod(multiprocessing.BoundedSemaphore)
Condition = staticmethod(multiprocessing.Condition)
Event = staticmethod(multiprocessing.Event)
Barrier = staticmethod(multiprocessing.Barrier)
Value = staticmethod(multiprocessing.Value)
Array = staticmethod(multiprocessing.Array)
RawValue = staticmethod(multiprocessing.RawValue)
RawArray = staticmethod(multiprocessing.RawArray)
class ManagerMixin(BaseMixin):
TYPE = 'manager'
Process = multiprocessing.Process
Queue = property(operator.attrgetter('manager.Queue'))
JoinableQueue = property(operator.attrgetter('manager.JoinableQueue'))
Lock = property(operator.attrgetter('manager.Lock'))
RLock = property(operator.attrgetter('manager.RLock'))
Semaphore = property(operator.attrgetter('manager.Semaphore'))
BoundedSemaphore = property(operator.attrgetter('manager.BoundedSemaphore'))
Condition = property(operator.attrgetter('manager.Condition'))
Event = property(operator.attrgetter('manager.Event'))
Barrier = property(operator.attrgetter('manager.Barrier'))
Value = property(operator.attrgetter('manager.Value'))
Array = property(operator.attrgetter('manager.Array'))
list = property(operator.attrgetter('manager.list'))
dict = property(operator.attrgetter('manager.dict'))
Namespace = property(operator.attrgetter('manager.Namespace'))
@classmethod
def Pool(cls, *args, **kwds):
return cls.manager.Pool(*args, **kwds)
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.manager = multiprocessing.Manager()
@classmethod
def tearDownClass(cls):
# only the manager process should be returned by active_children()
# but this can take a bit on slow machines, so wait a few seconds
# if there are other children too (see #17395)
start_time = time.monotonic()
t = 0.01
while len(multiprocessing.active_children()) > 1:
time.sleep(t)
t *= 2
dt = time.monotonic() - start_time
if dt >= 5.0:
test.support.environment_altered = True
print("Warning -- multiprocessing.Manager still has %s active "
"children after %s seconds"
% (multiprocessing.active_children(), dt),
file=sys.stderr)
break
gc.collect() # do garbage collection
if cls.manager._number_of_objects() != 0:
# This is not really an error since some tests do not
# ensure that all processes which hold a reference to a
# managed object have been joined.
test.support.environment_altered = True
print('Warning -- Shared objects which still exist at manager '
'shutdown:')
print(cls.manager._debug_info())
cls.manager.shutdown()
cls.manager.join()
cls.manager = None
super().tearDownClass()
class ThreadsMixin(BaseMixin):
TYPE = 'threads'
Process = multiprocessing.dummy.Process
connection = multiprocessing.dummy.connection
current_process = staticmethod(multiprocessing.dummy.current_process)
active_children = staticmethod(multiprocessing.dummy.active_children)
Pool = staticmethod(multiprocessing.dummy.Pool)
Pipe = staticmethod(multiprocessing.dummy.Pipe)
Queue = staticmethod(multiprocessing.dummy.Queue)
JoinableQueue = staticmethod(multiprocessing.dummy.JoinableQueue)
Lock = staticmethod(multiprocessing.dummy.Lock)
RLock = staticmethod(multiprocessing.dummy.RLock)
Semaphore = staticmethod(multiprocessing.dummy.Semaphore)
BoundedSemaphore = staticmethod(multiprocessing.dummy.BoundedSemaphore)
Condition = staticmethod(multiprocessing.dummy.Condition)
Event = staticmethod(multiprocessing.dummy.Event)
Barrier = staticmethod(multiprocessing.dummy.Barrier)
Value = staticmethod(multiprocessing.dummy.Value)
Array = staticmethod(multiprocessing.dummy.Array)
#
# Functions used to create test cases from the base ones in this module
#
def install_tests_in_module_dict(remote_globs, start_method):
__module__ = remote_globs['__name__']
local_globs = globals()
ALL_TYPES = {'processes', 'threads', 'manager'}
for name, base in local_globs.items():
if not isinstance(base, type):
continue
if issubclass(base, BaseTestCase):
if base is BaseTestCase:
continue
assert set(base.ALLOWED_TYPES) <= ALL_TYPES, base.ALLOWED_TYPES
for type_ in base.ALLOWED_TYPES:
newname = 'With' + type_.capitalize() + name[1:]
Mixin = local_globs[type_.capitalize() + 'Mixin']
class Temp(base, Mixin, unittest.TestCase):
pass
Temp.__name__ = Temp.__qualname__ = newname
Temp.__module__ = __module__
remote_globs[newname] = Temp
elif issubclass(base, unittest.TestCase):
class Temp(base, object):
pass
Temp.__name__ = Temp.__qualname__ = name
Temp.__module__ = __module__
remote_globs[name] = Temp
dangling = [None, None]
old_start_method = [None]
def setUpModule():
multiprocessing.set_forkserver_preload(PRELOAD)
multiprocessing.process._cleanup()
dangling[0] = multiprocessing.process._dangling.copy()
dangling[1] = threading._dangling.copy()
old_start_method[0] = multiprocessing.get_start_method(allow_none=True)
try:
multiprocessing.set_start_method(start_method, force=True)
except ValueError:
raise unittest.SkipTest(start_method +
' start method not supported')
if sys.platform.startswith("linux"):
try:
lock = multiprocessing.RLock()
except OSError:
raise unittest.SkipTest("OSError raises on RLock creation, "
"see issue 3111!")
check_enough_semaphores()
util.get_temp_dir() # creates temp directory
multiprocessing.get_logger().setLevel(LOG_LEVEL)
def tearDownModule():
need_sleep = False
# bpo-26762: Some multiprocessing objects like Pool create reference
# cycles. Trigger a garbage collection to break these cycles.
test.support.gc_collect()
multiprocessing.set_start_method(old_start_method[0], force=True)
# pause a bit so we don't get warning about dangling threads/processes
processes = set(multiprocessing.process._dangling) - set(dangling[0])
if processes:
need_sleep = True
test.support.environment_altered = True
print('Warning -- Dangling processes: %s' % processes,
file=sys.stderr)
processes = None
threads = set(threading._dangling) - set(dangling[1])
if threads:
need_sleep = True
test.support.environment_altered = True
print('Warning -- Dangling threads: %s' % threads,
file=sys.stderr)
threads = None
# Sleep 500 ms to give time to child processes to complete.
if need_sleep:
time.sleep(0.5)
multiprocessing.process._cleanup()
test.support.gc_collect()
remote_globs['setUpModule'] = setUpModule
remote_globs['tearDownModule'] = tearDownModule
|
tests_common.py | """
Copyright (C) 2021 Jesper Devantier <j.devantier@samsung.com>
NOTE: many test fixtures are split into a _<foo> and a <foo> function.
This split is done to satisfy the type-checker while providing a way
to delay operations until the test itself starts.
In other words, each <foo> function returns a thunk which, when invoked,
returns a context manager object which is designed to manage the lifetime
of the object in question, cleaning up after itself as the code exits its
scope.
"""
import os
import signal
from contextlib import contextmanager, suppress as ctx_suppress
from dataclasses import dataclass
from tempfile import NamedTemporaryFile
from pathlib import Path
from subprocess import run, PIPE, STDOUT, Popen
from typing import Optional, Union, Callable
from flexalloc import xnvme_env, FlexAlloc, mm, libflexalloc
from flexalloc.pyutils import loop
from typing import Generator
import threading
def subprocess_tail_lines(p: Popen) -> Generator[str, None, None]:
"""Create generator emitting each new line printed by process `p`."""
buf = []
while True:
out = p.stdout.read(1)
if out != "" and out != "\n":
buf.append(out)
elif out == "" and p.poll() is not None:
if buf:
yield ''.join(buf)
break
elif out == "\n":
yield ''.join(buf)
buf = []
def new_process(*args, **kwargs) -> Popen:
"""Construct process with reasonable defaults.
Constructs a process object whose defaults make it amenable to process
supervision/tailing using `subprocess_tail_lines`.
The default options will:
* interpret process output as UTF-8 formatted textual output (rather than bytes)
* on encoding errors, replace the faulty character
* redirect STDERR to STDOUT to capture all output in one unified stream
* capture STDOUT output (STDOUT=PIPE)
"""
return Popen(
*args,
**{**{
"stdout": PIPE,
"stderr": STDOUT,
"shell": False,
"encoding": "utf-8",
"errors": "replace"
},
**kwargs}
)
@dataclass
class Device:
lb_nbytes: int
nblocks: int
uri: str
def __repr__(self):
return f"{type(self).__name__}<uri: {self.uri}, lb_nbytes: {self.lb_nbytes}, nblocks: {self.nblocks}>"
def __str__(self):
return self.__repr__()
def dd_create_file(dst: Path, block_size: str, count: int) -> None:
"""Create temporary file of specified size
Raises:
CalledProcessError: if operation failed, inspect error for details"""
if count <= 0:
raise ValueError("block count must be 1 or greater")
run(
f"""dd if=/dev/zero of="{str(dst.absolute())}" bs={block_size} count={count}""",
shell=True,
check=True,
stdout=PIPE,
stderr=PIPE,
)
@contextmanager
def temp_backing_file(block_size: str, count: int) -> Path:
tmp = NamedTemporaryFile(delete=False)
try:
tmp.close()
dd_create_file(Path(tmp.name), block_size, count)
yield Path(tmp.name)
finally:
Path(tmp.name).unlink(missing_ok=True)
def temp_file_path() -> Path:
tmp = NamedTemporaryFile(delete=True)
tmp.close()
return Path(tmp.name)
DeviceContext = Generator[Device, None, None]
DeviceContextThunk = Callable[[], Generator[Device, None, None]]
@contextmanager
def _dev_loop(size_mb: int, block_size_bytes: int) -> DeviceContext:
with temp_backing_file(block_size=f"{size_mb}M", count=1) as file:
loop_path: Path = loop.setup_loop(file, block_size=block_size_bytes)
try:
dev = xnvme_env.XnvmeDev(str(loop_path))
lb_nbytes = xnvme_env.xne_dev_lba_nbytes(dev)
nblocks = int(xnvme_env.xne_dev_tbytes(dev) / lb_nbytes)
dev.close()
yield Device(
lb_nbytes=lb_nbytes,
nblocks=nblocks,
uri=str(loop_path),
)
finally:
loop.remove_loop(loop_path)
def dev_loop(size_mb: int, block_size_bytes: int) -> DeviceContextThunk:
"""Setup loop device for the duration of the context manager.
Sets up a loop device of capacity `size_mb` MiB and whose logical blocks are
of size `block_size_bytes` bytes.
The loop device and underlying backing file are automatically released upon
exiting the context manager's scope.
Args:
size_mb:
block_size_bytes:
Returns:
thunk function - when invoked, the device is created.
"""
return lambda: _dev_loop(size_mb=size_mb, block_size_bytes=block_size_bytes)
@contextmanager
def _dev_hw(min_size_mb: int,
device: Optional[Union[str, Path]] = None,
device_envvar: Optional[str] = None) -> DeviceContext:
# need access to the original, provided value to determine whether device
# value was explicitly specified or resolved by examining an environment variable
device_arg = device
device_envvar = device_envvar or "FLEXALLOC_TEST_DEVICE"
if not device:
device = os.environ.get(device_envvar)
if not device:
raise ValueError(
f"no device to use - no device specified and {device_envvar} unset"
)
if not isinstance(device, Path):
device = Path(device)
if not device.exists():
if device_arg:
raise RuntimeError(f"specified device '{device_arg}' does not exist!")
raise RuntimeError(f"device '{device}' resolved from ENV var '{device_envvar}' does not exist!")
dev = xnvme_env.XnvmeDev(str(device))
try:
lb_nbytes = xnvme_env.xne_dev_lba_nbytes(dev)
tbytes = xnvme_env.xne_dev_tbytes(dev)
nblocks = int(tbytes / lb_nbytes)
finally:
dev.close()
if tbytes <= (min_size_mb * 1024 ** 2):
raise RuntimeError(
f"hardware device too small, test desires {min_size_mb}MB, device has {tbytes / 1024**2}MB"
)
yield Device(
lb_nbytes=lb_nbytes, nblocks=nblocks, uri=str(device.absolute())
)
def dev_hw(min_size_mb: int,
device: Optional[Union[str, Path]] = None,
device_envvar: Optional[str] = None) -> DeviceContextThunk:
"""Get `Device` reference to hardware device for duration of context.
Provide `Device` reference for use during the context manager's scope.
The physical device may either be specified or resolved from an environment variable
which can be overridden by setting `device_envvar`.
Args:
min_size_mb:
device:
device_envvar:
Returns:
a thunk function which starts the work and returns a context manager
when invoked.
"""
return lambda: _dev_hw(min_size_mb=min_size_mb,
device=device,
device_envvar=device_envvar)
DiskFormatFn = Callable[[Device,], None]
def format_fla_mkfs(npools: int, slab_nlb: int) -> DiskFormatFn:
def do_mkfs(device: Device) -> None:
mm.mkfs(device.uri, npools, slab_nlb)
return do_mkfs
@contextmanager
def _fla_open_direct(device: DeviceContextThunk,
formatter: Optional[DiskFormatFn] = None,
md_device: Optional[DeviceContextThunk] = None,
md_formatter: Optional[DiskFormatFn] = None) -> Generator[FlexAlloc, None, None]:
"""Open FlexAlloc system directly.
NOTE: `device` and `md_device` may point to loop devices which are released upon exiting the scope.
therefore, do not attempt to re-open an already initialized system!
Args:
device: device containing the FlexAlloc system (or the data, if a metadata device is provided)
formatter: (optional) routine to use for formatting the `device`
md_device: (optional) if provided, treat this as the device containing the FlexAlloc system's metadata.
md_formatter: (optional) routine to use for formatting the `md_device`, if provided.
Returns:
None, however, context manager *yields* a `FlexAlloc` system instance.
"""
# if no md device is provided, use a NOOP context manager
md_device = md_device if md_device is not None else ctx_suppress
with md_device() as md_device:
if md_formatter:
if md_device is None:
raise RuntimeError("provided a function to format a metadata device, but `md_device` gave None, not a device")
md_formatter(md_device)
with device() as device:
if formatter:
formatter(device)
fs = None
try:
if md_device:
fs = libflexalloc.md_open(device.uri, md_device.uri)
else:
fs = libflexalloc.open(device.uri)
yield fs
finally:
if fs:
libflexalloc.close(fs)
def fla_open_direct(device: DeviceContextThunk,
formatter: Optional[DiskFormatFn] = None,
md_device: Optional[DeviceContextThunk] = None,
md_formatter: Optional[DiskFormatFn] = None) -> Callable[[], Generator[FlexAlloc, None, None]]:
return lambda: _fla_open_direct(
device=device,
formatter=formatter,
md_device=md_device,
md_formatter=md_formatter
)
# TODO: extend support to also take a metadata device and formatter
# A prerequisite of this change is to extend the daemon program to also
# support opening a device and separate metadata device.
@contextmanager
def _fla_daemon(device: DeviceContextThunk,
formatter: Optional[DiskFormatFn] = None) -> Generator[Path, None, None]:
"""Start FlexAlloc daemon instance in the background and yield path to its UNIX socket.
Takes the provided device and formatter, opening the FlexAlloc system in daemon-mode
and yielding a `Path` object pointing to the UNIX socket which the daemon is listening on.
Upon exiting the context-provider scope, the daemon is automatically shut down and the
underlying device is released.
Args:
device: context-provider providing a `Device` instance for the daemon to operate on.
formatter: (optional) function specifying how to format `device`.
Returns:
None, the context manager *yields* a Path object pointing to the UNIX socket
the daemon is listening on.
"""
with device() as device:
if formatter:
formatter(device)
daemon = None
meson_build_root = os.environ.get("MESON_BUILD_ROOT")
if not meson_build_root:
raise RuntimeError("required environment variable MESON_BUILD_ROOT is not defined!")
daemon_program_path = Path(meson_build_root) / "flexalloc_daemon"
if not daemon_program_path.exists():
raise RuntimeError(f"could not find daemon program in '{daemon_program_path}'")
socket_path: Path = temp_file_path()
try:
cmd = [
str(daemon_program_path),
"-d", device.uri,
"-s", str(socket_path)
]
print(f"""Daemon start command: {" ".join(cmd)}""")
daemon = new_process(cmd)
proc_tail_lines = subprocess_tail_lines(daemon)
def wait_for_daemon_ready_fn():
for line in proc_tail_lines:
print(f"server> {line}")
if line.startswith("daemon ready for connections"):
return True
def tail_daemon_output():
for line in proc_tail_lines:
print(f"server> {line}")
th = threading.Thread(target=wait_for_daemon_ready_fn)
th.start()
th.join(timeout=10)
if th.is_alive():
raise RuntimeError("timeout waiting for daemon to start")
# print server output in the background.
# it will not be fully caught up in case of sudden segfaults, but it
# remains useful.
th = threading.Thread(target=tail_daemon_output)
th.start()
yield socket_path
finally:
if not daemon:
socket_path.unlink(missing_ok=True)
return
daemon.send_signal(signal.SIGINT)
daemon.wait(timeout=10)
socket_path.unlink(missing_ok=True)
def fla_daemon(device: DeviceContextThunk,
formatter: Optional[DiskFormatFn] = None) -> Callable[[], Generator[Path, None, None]]:
return lambda: _fla_daemon(device=device, formatter=formatter)
@contextmanager
def _fla_daemon_client(socket: Path) -> Generator[libflexalloc.FlexAllocDaemonClient, None, None]:
client = None
try:
client = libflexalloc.daemon_open(socket)
yield client
finally:
libflexalloc.close(client.fs)
def fla_daemon_client(socket: Path) -> Callable[[], Generator[libflexalloc.FlexAllocDaemonClient, None, None]]:
return lambda: _fla_daemon_client(socket=socket)
@contextmanager
def _fla_open_daemon(device: DeviceContextThunk,
formatter: Optional[DiskFormatFn] = None) -> Generator[FlexAlloc, None, None]:
with fla_daemon(device=device, formatter=formatter)() as daemon_socket_path:
with fla_daemon_client(daemon_socket_path)() as client:
yield client.fs
def fla_open_daemon(device: DeviceContextThunk,
formatter: Optional[DiskFormatFn] = None) -> Callable[[], Generator[FlexAlloc, None, None]]:
return lambda: _fla_open_daemon(device=device, formatter=formatter)
|
v2rayMS_Server.py | #!/usr/bin/python3
# -*- coding: UTF-8 -*-
import threading
from socketserver import BaseRequestHandler, ThreadingTCPServer
import queue
import time
import v2server
'''
@Author : Npist <npist35@gmail.com>
@File : v2rayMS_Server.py
@License : http://opensource.org/licenses/MIT The MIT License
@Link : https://npist.com/
@Time : 2018.9.6
@Ver : 0.3
'''
HOST = '0.0.0.0'
PORT = 8854
BUFSIZE = 4096
ins_queue = queue.Queue()
# ๅค็บฟ็จ
class Handler(BaseRequestHandler):
def handle(self):
global AES_Key
conn_sql = v2server.sqlconn()
while True:
try:
# ๆฅๆถๆฐๆฎ
data = self.accept_data()
proc_data = data.decode().split('#')
if proc_data[0] == 'pull_list':
msg = conn_sql.pull_user()
if msg is not None:
self.send_data(msg)
elif proc_data[0] == 'push_traffic':
if len(proc_data) != 1:
users_traffic = [
eval(i) for i in proc_data if i != 'push_traffic'
]
ins_queue.put(users_traffic)
# ๅๅค็กฎ่ฎค
self.send_data('$%^')
except Exception as e:
print(e)
break
# ็ปๆๅค็
print("close:", self.request.getpeername())
# ๅ
ณ้ญ่ฟๆฅ
conn_sql.conn.close()
self.request.close()
# ๅ้ๆฐๆฎ
def send_data(self, data):
data_len = len(data)
self.request.sendall(str(data_len).encode())
time.sleep(0.1)
if self.request.recv(BUFSIZE) == b'!#%':
self.request.sendall(data.encode())
# ๆฅๆถๆฐๆฎ
def accept_data(self):
data_size = self.request.recv(BUFSIZE)
if data_size == b'':
return None
self.request.sendall(b'!#%')
recevied_size = 0
recevied_data = b''
while recevied_size < int(data_size.decode()):
data_res = self.request.recv(BUFSIZE)
recevied_size += len(data_res)
recevied_data += data_res
return recevied_data
# ๆต้ๆดๆฐ
def sql_queue():
conn_sql = v2server.sqlconn()
while True:
if ins_queue.empty() is not True:
sql_task = ins_queue.get()
for i in sql_task:
conn_sql.update_traffic(i)
time.sleep(0.1)
# ๆๅกๅจ็ๅฌ
def serve_listen():
server = ThreadingTCPServer((HOST, PORT), Handler)
print('listening')
server.serve_forever()
print(server)
# ไธปๅฝๆฐ
def main():
que_thread = threading.Thread(target=sql_queue)
ser_thread = threading.Thread(target=serve_listen)
que_thread.start()
ser_thread.start()
que_thread.join()
ser_thread.join()
if __name__ == '__main__':
main()
|
app.py | #!/usr/bin/python
########################################################
__author__ = 'Theophilus Siameh'
__author_email__ = 'theodondre@gmail.com'
__copyright__ = 'Copyright (C) 2020 Theophilus Siameh'
__version__ = 1.0
########################################################
from functools import wraps
from bson.objectid import ObjectId
from flask import jsonify, request, Flask
from flask import render_template, flash, redirect, url_for, session
from flask_mail import Message, Mail
from flask_paginate import Pagination, get_page_args
from flask_pymongo import PyMongo
from flask_restful import Api
from itsdangerous import URLSafeTimedSerializer
# from pymongo import MongoClient
from passlib.hash import sha256_crypt
from flasgger import Swagger
from wtforms import Form, StringField, PasswordField, validators
from flask_jwt_extended import (JWTManager, jwt_required, create_access_token,get_jwt_identity)
from Users.mongodbObjects import UsersRegisteration
from common.config import mongo, api, mail, app
from common.mongo_cred import data
from common.util import date_time, generateApiKeys, getNetworkName, gen_reset_password, UserExist, \
generateReturnDictionary
##################################################
# API SECTION
##################################################
from resources.checkbalance import CheckBalance
from resources.payloan import PayLoan
from resources.register import Registration
from resources.takeloan import TakeLoan
from resources.topup import TopUp
from resources.transfer import TransferMoney
from resources.withdraw import WithdrawMoney
# MongoDB Credentials
DB = data.get("DB")
USERNAME = data.get("username")
PASSWORD = data.get("password")
app = Flask(__name__)
swagger = Swagger(app)
jwt = JWTManager(app)
app.config.update(dict(
DEBUG=True,
MAIL_SERVER='smtp.googlemail.com',
MAIL_PORT=465,
MAIL_USE_TLS=False,
MAIL_USE_SSL=True,
MAIL_USERNAME='theodondre@gmail.com',
MAIL_PASSWORD='offpjnvauklxwivk'
))
# export SECRET_KEY = "f15f6748-c4d9-4c2b-bf61-1be3b7a9ed2c"
app.config['SECRET_KEY'] = "f15f6748-c4d9-4c2b-bf61-1be3b7a9ed2c" #$SECRET_KEY
app.config["MONGO_URI"] = "mongodb+srv://{0}:{1}@mobilemoney-q3w48.mongodb.net/{2}?retryWrites=true&w=majority".format(USERNAME, PASSWORD, DB)
mongo = PyMongo(app)
api = Api(app)
mail = Mail(app)
#######################################################################################################################
# client = MongoClient("mongodb+srv://mobilemoney:Abc12345@mobilemoney-q3w48.mongodb.net/MobileMoneyDB?retryWrites=true&w=majority")
# mongo = client.MobileMoneyDB
# users = db["Users"]
# mongo = pymongo.MongoClient('mongodb+srv://mobilemoney:Abc12345@mobilemoney-q3w48.mongodb.net/MobileMoneyDB?retryWrites=true&w=majority', maxPoolSize=50, connect=False)
# db = pymongo.database.Database(mongo, 'mydatabase')
# col = pymongo.collection.Collection(db, 'mycollection')
# col_results = json.loads(dumps(col.find().limit(5).sort("time", -1)))
#######################################################################################################################
users = list(range(100))
# Check if user logged in
def is_logged_in(f):
@wraps(f)
def wrap(*args, **kwargs):
if 'logged_in' in session:
return f(*args, **kwargs)
else:
flash('Unauthorized, Please login', 'danger')
return redirect(url_for('login'))
return wrap
# Logout
@app.route('/logout')
@is_logged_in
def logout():
session.clear()
flash('You are now logged out', 'success')
return redirect(url_for('login'))
def get_users(offset=0, per_page=3):
# mongo.db.Register.find({}).skip(offset).limit(offset + per_page)
return users[offset: offset + per_page]
# Index
@app.route('/')
def index():
# return jsonify({'ip': request.remote_addr}), 200
# register = mongo.db.Register
# list_users = register.insert_one({"Username":"Anthony"})
if 'username' in session:
return 'You are logged in as ' + session['username']
return render_template('home.html')
############################################
# send email
############################################
def send_mail(subject, body, recipients):
try:
msg = Message(subject, sender="theodondre@gmail.com", recipients=[recipients])
msg.body = body
mail.send(msg)
return 'Mail sent!'
except Exception as e:
return (str(e))
# def send_email(subject, recipients, html_body):
# msg = Message(subject, recipients=recipients)
# msg.html = html_body
# thr = Thread(target=send_async_email, args=[msg])
# thr.start()
# def send_password_reset_email(user_email):
# password_reset_serializer = URLSafeTimedSerializer(app.config['SECRET_KEY'])
#
# password_reset_url = url_for(
# 'reset_with_token',
# token = password_reset_serializer.dumps(user_email, salt='password-reset-salt'),
# _external=True)
#
# html = render_template(
# 'email_password_reset.html',
# password_reset_url = password_reset_url)
#
# send_email('Password Reset Requested', user_email, html)
#######################
# Search
#######################
@app.route('/search', methods=['GET', 'POST'])
def search():
if request.method == "POST":
q = request.form['search']
findByUsername = mongo.db.Register
# search db by username, email or phone
searchResult = findByUsername.find({"$or": [
{"Username": {'$regex': q}},
{"Email": {'$regex': q}},
{"Phone": {'$regex': q}}
]})
return render_template('search.html', searchResult=searchResult)
return render_template('search.html')
@app.route('/searchtop', methods=['GET', 'POST'])
def searchtop():
if request.method == "POST":
q = request.form['search']
findByUsername = mongo.db.TopUps
# search db
searchTop = findByUsername.find({"$or": [
{"Username": {'$regex': q}},
{"Email": {'$regex': q}},
{"Phone": {'$regex': q}}
]})
return render_template('searchtop.html', searchTop=searchTop)
return render_template('searchtop.html')
@app.route('/searchloan', methods=['GET', 'POST'])
def searchloan():
if request.method == "POST":
q = request.form['search']
findByUsername = mongo.db.Takeloan
# search db
searchLoan = findByUsername.find({"$or": [
{"Username": {'$regex': q}},
{"Email": {'$regex': q}},
{"Phone": {'$regex': q}}
]})
return render_template('searchloan.html', searchLoan=searchLoan)
return render_template('searchloan.html')
@app.route('/searchPay', methods=['GET', 'POST'])
def searchPay():
if request.method == "POST":
q = request.form['search']
findByUsername = mongo.db.Payloan
# search db
searchPay = findByUsername.find({"$or": [
{"Username": {'$regex': q}},
{"Email": {'$regex': q}},
{"Phone": {'$regex': q}}
]})
return render_template('searchpay.html', searchPay=searchPay)
return render_template('searchpay.html')
@app.route('/listusers')
def listusers():
registeredUsers = mongo.db.Register
listUsers = registeredUsers.find({})
# total = listUsers.count()
total = len(users)
page, per_page, offset = get_page_args(page_parameter='page', per_page_parameter='per_page')
listUser = listUsers.skip((page - 1) * per_page).limit(per_page)
pagination = Pagination(page=page, per_page=per_page, total=total, css_framework='bootstrap4')
return render_template("listusers.html",
listUser=listUser,
page=page,
per_page=per_page,
pagination=pagination)
@app.route('/withdraw')
def withdraw():
withdrawHistory = mongo.db.Withdrawal
withdrawalObject = withdrawHistory.find({})
total = len(users)
page, per_page, offset = get_page_args(page_parameter='page', per_page_parameter='per_page')
withdrawalObject = withdrawalObject.skip((page - 1) * per_page).limit(per_page)
pagination = Pagination(page=page, per_page=per_page, total=total, css_framework='bootstrap4')
return render_template("withdrawal.html",
withdrawalObject=withdrawalObject,
page=page,
per_page=per_page,
pagination=pagination)
@app.route('/balance')
def balance():
balanceHistory = mongo.db.Register
balanceObject = balanceHistory.find({})
total = len(users)
page, per_page, offset = get_page_args(page_parameter='page', per_page_parameter='per_page')
balanceObject = balanceObject.skip((page - 1) * per_page).limit(per_page)
pagination = Pagination(page=page, per_page=per_page, total=total, css_framework='bootstrap4')
return render_template("checkbalance.html",
balanceObject=balanceObject,
page=page,
per_page=per_page,
pagination=pagination)
@app.route('/topups')
def topups():
tops = mongo.db.TopUps
topup = tops.find({})
total = len(users)
page, per_page, offset = get_page_args(page_parameter='page', per_page_parameter='per_page')
topup = topup.skip((page - 1) * per_page).limit(per_page)
pagination = Pagination(page=page, per_page=per_page, total=total, css_framework='bootstrap4')
return render_template("topups.html",
topup=topup,
page=page,
per_page=per_page,
pagination=pagination)
@app.route('/loan')
def loan():
loans = mongo.db.Takeloan
loanObject = loans.find({})
total = len(users)
page, per_page, offset = get_page_args(page_parameter='page', per_page_parameter='per_page')
loanObject = loanObject.skip((page - 1) * per_page).limit(per_page)
pagination = Pagination(page=page, per_page=per_page, total=total, css_framework='bootstrap4')
return render_template("takeloan.html",
loanObject=loanObject,
page=page,
per_page=per_page,
pagination=pagination)
@app.route('/pay')
def pay():
payloans = mongo.db.Payloan
payloanObject = payloans.find({})
total = len(users)
page, per_page, offset = get_page_args(page_parameter='page', per_page_parameter='per_page')
payloanObject = payloanObject.skip((page - 1) * per_page).limit(per_page)
pagination = Pagination(page=page, per_page=per_page, total=total, css_framework='bootstrap4')
return render_template("payloan.html",
payloanObject=payloanObject,
page=page,
per_page=per_page,
pagination=pagination)
@app.route('/transfer')
def transfer():
transfers = mongo.db.Transfer
transfersObject = transfers.find({})
total = len(users)
page, per_page, offset = get_page_args(page_parameter='page', per_page_parameter='per_page')
transfersObject = transfersObject.skip((page - 1) * per_page).limit(per_page)
pagination = Pagination(page=page, per_page=per_page, total=total, css_framework='bootstrap4')
return render_template("transfer.html",
transfersObject=transfersObject,
page=page,
per_page=per_page,
pagination=pagination)
@app.route("/dashboard")
def dashboard():
all_account = mongo.db.Register
momo_account = all_account.find({})
total = len(users)
page, per_page, offset = get_page_args(page_parameter='page', per_page_parameter='per_page')
momo_account = momo_account.skip((page - 1) * per_page).limit(per_page)
pagination = Pagination(page=page, per_page=per_page, total=total, css_framework='bootstrap4')
return render_template("dashboard.html",
momo_account=momo_account,
page=page,
per_page=per_page,
pagination=pagination)
# Balance Form Class
class BalanceForm(Form):
balance = StringField('Balance')
debt = StringField('Debt')
# Email Form Class
class EmailForm(Form):
email = StringField('Email', [validators.DataRequired(), validators.Length(min=6, max=50)])
# email = StringField('Email', validators=[validators.DataRequired(), Email(), Length(min=6, max=40)])
# Password Form
class PasswordForm(Form):
password = PasswordField('Password', [validators.DataRequired()])
# Register Form Class
class RegisterForm(Form):
firstname = StringField('First Name', [validators.DataRequired(), validators.Length(min=1, max=50)])
lastname = StringField('Last Name', [validators.DataRequired(), validators.Length(min=1, max=50)])
username = StringField('Username', [validators.DataRequired(), validators.Length(min=4, max=25)])
email = StringField('Email', [validators.DataRequired(), validators.Length(min=6, max=50)])
phone = StringField('Phone', [validators.DataRequired(), validators.Length(min=10, max=50)])
password = PasswordField('Password', [
validators.DataRequired(),
validators.EqualTo('confirm', message='Passwords do not match')
])
confirm = PasswordField('Confirm Password')
# Logon Form Class
class LogonForm(Form):
username = StringField('Username', [validators.DataRequired(), validators.Length(min=4, max=25)])
password = PasswordField('Password', [validators.DataRequired(), validators.Length(min=4, max=25)])
@app.route('/show')
def showdata():
data = mongo.db.Register.find_one({"Username": "iwan"})
#dumps(data['Username'] + ':' + data['Password'])
return jsonify(data.get("Password"))
# User Register
@app.route('/signup', methods=['GET', 'POST'])
def signup():
'''User Registeration'''
form = RegisterForm(request.form)
if request.method == 'POST' and form.validate():
# fields
firstname = form.firstname.data
lastname = form.lastname.data
email = form.email.data
phone = form.phone.data
username = form.username.data
password = form.password.data
network = getNetworkName(phone)
# check if phone/username number exist
if not UserExist(phone):
# return jsonify(generateReturnDictionary(301, 'Phone number already Exist', "FAILURE"))
error = 'Phone number already Exists'
return render_template('login.html', error=error)
if not UserExist(username):
return jsonify(generateReturnDictionary(301, 'Username already Exist', "FAILURE"))
reg = mongo.db.Register
existing_user = reg.find_one({"Phone": phone})
if existing_user is None:
# hash password
hashed_pw = sha256_crypt.hash(password)
# insert into db
userReg = UsersRegisteration(firstname, lastname, email, phone, network, username, hashed_pw, balance=0.0,debt=0.0)
reg.insert_one({
"FirstName": userReg.firstname,
"LastName": userReg.lastname,
"Email": userReg.email,
"Phone": userReg.phone,
"Network": userReg.network,
"Username": userReg.username,
"Password": userReg.password,
"Balance": userReg.balance,
"Debt": userReg.debt,
"DateTimeCreated": date_time(),
"apiKeys": generateApiKeys()
})
flash('You successfully signed up for the mobile money wallet, you can now log-in', 'success')
return redirect(url_for('login'))
return render_template('signup.html', form=form)
# User login
@app.route('/login', methods=['GET', 'POST'])
def login():
'''User login'''
form = LogonForm(request.form)
if request.method == 'POST':
# Get Form Fields
# phone = form.phone.data # request.form['phone']
username = form.username.data # request.form['username']
password_candidate = form.password.data # request.form['password']
if password_candidate == '' or username == '':
error = 'Password/Username is required'
return render_template('login.html', error=error)
if username is None or username == '':
error = 'Username is required'
return render_template('login.html', error=error)
if password_candidate is None or password_candidate == '':
error = 'Password is required'
return render_template('login.html', error=error)
# Get user by username
# Get stored hash
hashed_pw = mongo.db.Register.find_one({"Username": username})
print(hashed_pw)
username_new = hashed_pw["Username"]
print(username_new)
#password_new = hashed_pw["Password"]
# Compare Passwords
if sha256_crypt.verify(password_candidate, hashed_pw["Password"]):
# passed
session['logged_in'] = True
session['username'] = username
flash('You are now logged in', 'success')
return redirect(url_for('dashboard'))
if not sha256_crypt.verify(password_candidate, hashed_pw['Password']):
error = 'Invalid Username/Password, Try Again!'
return render_template('login.html', error=error)
if not (sha256_crypt.verify(hashed_pw['Username'], str(username))):
error = 'Invalid Username/Password, Try Again!'
return render_template('login.html', error=error)
return render_template('login.html')
#########################################################
# change password
#########################################################
@app.route("/change_password/", methods=['GET', 'POST'])
@is_logged_in
def change_password():
if request.method == 'GET': # Send the change password form
return render_template('change_password.html')
elif request.method == 'POST':
# Get the post data
username = request.form['username'] # email = request.form.get('email')
current_password = request.form['current_password']
new_password = request.form['password']
confirm_new_password = request.form['confirm_password']
# Checks
errors = []
if username is None or username == '':
errors.append('Username is required')
if current_password is None or current_password == '':
errors.append('Current Password is required')
if new_password is None or new_password == '':
errors.append('New Password is required')
if confirm_new_password is None or confirm_new_password == '':
errors.append('Confirm New Password is required')
if new_password != confirm_new_password:
errors.append('New Passwords do not match')
# current hashed password
usernameByPassword = mongo.db.Register.find_one({"Username": username})["Password"]
if usernameByPassword:
if not sha256_crypt.verify(current_password, usernameByPassword):
errors.append("Password is incorrect")
# Query for user from database and check password
elif len(errors) == 0:
# if verifyPw(username, current_password):
hashed_pw = sha256_crypt.hash(new_password)
# update password
mongo.db.Register.update_one({
"Username": username
}, {
"$set": {
"Password": hashed_pw
}
})
# return "Password Changed"
flash('Password Changed Successfully', 'success')
return redirect(url_for('login'))
else: # No usable password
errors.append("User has no Password")
# Error Message
if len(errors) > 0:
return render_template('change_password.html', errors=errors)
@app.route('/reset', methods=["GET", "POST"])
def reset():
form = EmailForm()
if request.method == 'POST' and form.validate():
try:
# user = User.query.filter_by(email=form.email.data).first_or_404()
email = form.email.data
emailFound = mongo.db.Register.find_one({"Email": email})["Email"]
except:
flash('There is no account with that email. You must register first.!', 'error')
return render_template('password_reset_email.html', form=form)
if emailFound:
#send_password_reset_email(emailFound)
flash('Please check your email for a password reset link.', 'success')
else:
flash('Your email address must be confirmed before attempting a password reset.', 'error')
return redirect(url_for('login'))
return render_template('password_reset_email.html', form=form)
@app.route('/reset/<token>', methods=["GET", "POST"])
def reset_with_token(token):
try:
password_reset_serializer = URLSafeTimedSerializer(app.config['SECRET_KEY'])
email = password_reset_serializer.loads(token, salt='password-reset-salt', max_age=3600)
except:
flash('The password reset link is invalid or has expired.', 'error')
return redirect(url_for('login'))
form = PasswordForm()
if form.validate():
try:
# user = User.query.filter_by(email=email).first_or_404()
emailFound = mongo.db.Register.find_one({"Email": email})["Email"]
except:
flash('Invalid email address!', 'error')
return redirect(url_for('login'))
# user.password = form.password.data
# db.session.add(user)
# db.session.commit()
username = form.username.data
password = form.password.data
mongo.db.Register.update_one({
"Username": username
}, {
"$set": {
"Password": password
}
})
flash('Your password has been updated!', 'success')
return redirect(url_for('login'))
return render_template('reset_password_with_token.html', form=form, token=token)
@app.route("/forgot_password/", methods=['GET', 'POST'])
def forgot_password():
'''Forgot Password'''
if request.method == 'GET': # Send the forgot password form
return render_template('forgot_password.html')
elif request.method == 'POST':
# Get the post data
emailFound = request.form.get('email')
username = request.form.get('username')
if username is None or username == '':
flash('Username is required')
# Generate Random Pass and Set it to User object
generated_password = gen_reset_password()
hashed_pw = sha256_crypt.hash(generated_password)
# update password
mongo.db.Register.update_one({
"Username": username
}, {
"$set": {
"Password": hashed_pw
}
})
# Send Reset Mail
# message = sendmail.SendPasswordResetMail(user, generated_password)
send_mail("Password Reset",
"Password Reset has been sent to your Email. \nHere is your new password : {0}".format(
generated_password), emailFound)
flash('Password Reset Link has been sent to your Email.', 'success')
return redirect(url_for('login'))
# if message is not None:
# return "Password Reset Link has been sent to your Email. "
# else:
# errors.append("Could Not Send Mail. Try Again Later.")
# if len(errors) > 0:
# return render_template('error.html', errors=errors)
# Edit Balance
@app.route('/edit_balance/<string:id>', methods=['GET', 'POST'])
@is_logged_in
def edit_balance(id):
# Create cursor
bal = mongo.db.Register.find_one({"_id": ObjectId(id)}) # ["Password"]
# Get form
form = BalanceForm(request.form)
# Populate balance form fields
form.balance.data = bal['Balance']
form.debt.data = bal['Debt']
if request.method == 'POST' and form.validate():
balance = request.form['balance']
debt = request.form['debt']
# Update Query Execute
mongo.db.Register.update_one({
"_id": ObjectId(id)
}, {
"$set": {
"Balance": round(float(balance), 2),
"Debt": round(float(debt), 2)
}
}, upsert=True)
flash('Balance/Debt Updated', 'success')
return redirect(url_for('dashboard'))
return render_template('edit_balance.html', form=form)
# Delete Account
@app.route('/delete_account/<string:id>', methods=['POST'])
@is_logged_in
def delete_account(id):
# Create cursor
account = mongo.db.Register.find_one({"_id": ObjectId(id)}) # ["Password"]
if account is None:
flash('Account does not exist', 'failure')
else:
mongo.db.Register.delete_one({"_id": ObjectId(account['_id'])})
flash('Account Deleted', 'success')
return redirect(url_for('dashboard'))
#####################################
# TODO : add interest to loan
#####################################
# def getMonthlyPayment(loanAmount, monthlyInterateRate, numberOfYears):
# import math
# monthlyPayment = loanAmount * monthlyInterateRate/(1.0 - math.pow(1.0 + monthlyInterateRate,-(numberOfYears * 12)))
# return monthlyPayment
# End Points
api.add_resource(Registration, '/momo/api/v1/register', endpoint = '/register')
api.add_resource(TopUp, '/momo/api/v1/topup', endpoint = '/topup')
api.add_resource(TransferMoney, '/momo/api/v1/transfer', endpoint = '/transfer')
api.add_resource(CheckBalance, '/momo/api/v1/balance', endpoint = '/balance')
api.add_resource(WithdrawMoney, '/momo/api/v1/withdraw', endpoint = '/withdraw')
api.add_resource(TakeLoan, '/momo/api/v1/loan', endpoint = '/loan')
api.add_resource(PayLoan, '/momo/api/v1/pay', endpoint = '/pay')
if __name__ == '__main__':
# app.run(host='0.0.0.0',port=80,debug=True)
app.run(debug=True)
|
ng.py | #!/usr/bin/env python
#
# Copyright 2004-2015, Martian Software, Inc.
# Copyright 2017-Present Facebook, 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 writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
import ctypes
import platform
import optparse
import os
import os.path
import select
import socket
import struct
import sys
from threading import Condition, Event, Thread, RLock
is_py2 = sys.version_info[0] == 2
if is_py2:
import Queue as Queue
import __builtin__ as builtin
def to_bytes(s):
return s
else:
import queue as Queue
import builtins as builtin
from io import UnsupportedOperation
def to_bytes(s):
return bytes(s, "utf-8")
if sys.platform == "win32":
import os, msvcrt
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
msvcrt.setmode(sys.stderr.fileno(), os.O_BINARY)
def bytes_to_str(bytes_to_convert):
"""Version independent way of converting bytes to string."""
return bytes_to_convert if is_py2 else bytes_to_convert.decode("utf-8")
# @author <a href="http://www.martiansoftware.com/contact.html">Marty Lamb</a>
# @author Pete Kirkham (Win32 port)
# @author Sergey Balabanov, Ben Hamilton (Python port)
#
# Please try to keep this working on Python 2.6.
NAILGUN_VERSION = "1.0.0"
BUFSIZE = 2048
NAILGUN_PORT_DEFAULT = 2113
CHUNK_HEADER_LEN = 5
THREAD_TERMINATION_TIMEOUT_SEC = 0.5
STDIN_BUFFER_LINE_SIZE = 10
CHUNKTYPE_STDIN = b"0"
CHUNKTYPE_STDOUT = b"1"
CHUNKTYPE_STDERR = b"2"
CHUNKTYPE_STDIN_EOF = b"."
CHUNKTYPE_ARG = b"A"
CHUNKTYPE_LONGARG = b"L"
CHUNKTYPE_ENV = b"E"
CHUNKTYPE_DIR = b"D"
CHUNKTYPE_CMD = b"C"
CHUNKTYPE_EXIT = b"X"
CHUNKTYPE_SENDINPUT = b"S"
CHUNKTYPE_HEARTBEAT = b"H"
NSEC_PER_SEC = 1000000000
DEFAULT_HEARTBEAT_INTERVAL_SEC = 0.5
SELECT_MAX_BLOCK_TIME_SEC = 1.0
SEND_THREAD_WAIT_TERMINATION_SEC = 5.0
# We need to support Python 2.6 hosts which lack memoryview().
HAS_MEMORYVIEW = "memoryview" in dir(builtin)
EVENT_STDIN_CHUNK = 0
EVENT_STDIN_CLOSED = 1
EVENT_STDIN_EXCEPTION = 2
def compat_memoryview_py2(buf):
return memoryview(buf)
def compat_memoryview_py3(buf):
return memoryview(buf).cast("c")
# memoryview in python3, while wrapping ctypes.create_string_buffer has problems with
# that type's default format (<c) and assignment operators. For python3, cast to
# a 'c' array. Little endian single byte doesn't make sense anyways. However,
# 'cast' does not exist for python2. So, we have to toggle a bit.
compat_memoryview = compat_memoryview_py2 if is_py2 else compat_memoryview_py3
class NailgunException(Exception):
SOCKET_FAILED = 231
CONNECT_FAILED = 230
UNEXPECTED_CHUNKTYPE = 229
CONNECTION_BROKEN = 227
def __init__(self, message, code):
self.message = message
self.code = code
def __str__(self):
return self.message
class Transport(object):
def close(self):
raise NotImplementedError()
def sendall(self, data):
raise NotImplementedError()
def recv(self, size):
raise NotImplementedError()
def recv_into(self, buffer, size=None):
raise NotImplementedError()
def select(self, timeout_secs):
raise NotImplementedError()
class UnixTransport(Transport):
def __init__(self, __socket):
self.__socket = __socket
self.recv_flags = 0
self.send_flags = 0
if hasattr(socket, "MSG_WAITALL"):
self.recv_flags |= socket.MSG_WAITALL
if hasattr(socket, "MSG_NOSIGNAL"):
self.send_flags |= socket.MSG_NOSIGNAL
def close(self):
return self.__socket.close()
def sendall(self, data):
result = self.__socket.sendall(data, self.send_flags)
return result
def recv(self, nbytes):
return self.__socket.recv(nbytes, self.recv_flags)
def recv_into(self, buffer, nbytes=None):
return self.__socket.recv_into(buffer, nbytes, self.recv_flags)
def select(self, timeout_secs):
select_list = [self.__socket]
readable, _, exceptional = select.select(
select_list, [], select_list, timeout_secs
)
return (self.__socket in readable), (self.__socket in exceptional)
if os.name == "nt":
import ctypes.wintypes
wintypes = ctypes.wintypes
GENERIC_READ = 0x80000000
GENERIC_WRITE = 0x40000000
FILE_FLAG_OVERLAPPED = 0x40000000
OPEN_EXISTING = 3
INVALID_HANDLE_VALUE = ctypes.c_void_p(-1).value
FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000
FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100
FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200
WAIT_FAILED = 0xFFFFFFFF
WAIT_TIMEOUT = 0x00000102
WAIT_OBJECT_0 = 0x00000000
WAIT_IO_COMPLETION = 0x000000C0
INFINITE = 0xFFFFFFFF
# Overlapped I/O operation is in progress. (997)
ERROR_IO_PENDING = 0x000003E5
ERROR_PIPE_BUSY = 231
# No process is on the other end of the pipe error on Windows
ERROR_NO_PROCESS_ON_OTHER_END_OF_PIPE = 233
# The pointer size follows the architecture
# We use WPARAM since this type is already conditionally defined
ULONG_PTR = ctypes.wintypes.WPARAM
class OVERLAPPED(ctypes.Structure):
_fields_ = [
("Internal", ULONG_PTR),
("InternalHigh", ULONG_PTR),
("Offset", wintypes.DWORD),
("OffsetHigh", wintypes.DWORD),
("hEvent", wintypes.HANDLE),
]
LPDWORD = ctypes.POINTER(wintypes.DWORD)
CreateFile = ctypes.windll.kernel32.CreateFileW
CreateFile.argtypes = [
wintypes.LPCWSTR,
wintypes.DWORD,
wintypes.DWORD,
wintypes.LPVOID,
wintypes.DWORD,
wintypes.DWORD,
wintypes.HANDLE,
]
CreateFile.restype = wintypes.HANDLE
CloseHandle = ctypes.windll.kernel32.CloseHandle
CloseHandle.argtypes = [wintypes.HANDLE]
CloseHandle.restype = wintypes.BOOL
ReadFile = ctypes.windll.kernel32.ReadFile
ReadFile.argtypes = [
wintypes.HANDLE,
wintypes.LPVOID,
wintypes.DWORD,
LPDWORD,
ctypes.POINTER(OVERLAPPED),
]
ReadFile.restype = wintypes.BOOL
WriteFile = ctypes.windll.kernel32.WriteFile
WriteFile.argtypes = [
wintypes.HANDLE,
wintypes.LPVOID,
wintypes.DWORD,
LPDWORD,
ctypes.POINTER(OVERLAPPED),
]
WriteFile.restype = wintypes.BOOL
GetLastError = ctypes.windll.kernel32.GetLastError
GetLastError.argtypes = []
GetLastError.restype = wintypes.DWORD
SetLastError = ctypes.windll.kernel32.SetLastError
SetLastError.argtypes = [wintypes.DWORD]
SetLastError.restype = None
FormatMessage = ctypes.windll.kernel32.FormatMessageW
FormatMessage.argtypes = [
wintypes.DWORD,
wintypes.LPVOID,
wintypes.DWORD,
wintypes.DWORD,
ctypes.POINTER(wintypes.LPCWSTR),
wintypes.DWORD,
wintypes.LPVOID,
]
FormatMessage.restype = wintypes.DWORD
LocalFree = ctypes.windll.kernel32.LocalFree
GetOverlappedResult = ctypes.windll.kernel32.GetOverlappedResult
GetOverlappedResult.argtypes = [
wintypes.HANDLE,
ctypes.POINTER(OVERLAPPED),
LPDWORD,
wintypes.BOOL,
]
GetOverlappedResult.restype = wintypes.BOOL
CreateEvent = ctypes.windll.kernel32.CreateEventW
CreateEvent.argtypes = [LPDWORD, wintypes.BOOL, wintypes.BOOL, wintypes.LPCWSTR]
CreateEvent.restype = wintypes.HANDLE
PeekNamedPipe = ctypes.windll.kernel32.PeekNamedPipe
PeekNamedPipe.argtypes = [
wintypes.HANDLE,
wintypes.LPVOID,
wintypes.DWORD,
LPDWORD,
LPDWORD,
LPDWORD,
]
PeekNamedPipe.restype = wintypes.BOOL
WaitNamedPipe = ctypes.windll.kernel32.WaitNamedPipeW
WaitNamedPipe.argtypes = [wintypes.LPCWSTR, wintypes.DWORD]
WaitNamedPipe.restype = wintypes.BOOL
def _win32_strerror(err):
""" expand a win32 error code into a human readable message """
# FormatMessage will allocate memory and assign it here
buf = ctypes.c_wchar_p()
FormatMessage(
FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_IGNORE_INSERTS,
None,
err,
0,
buf,
0,
None,
)
try:
return buf.value
finally:
LocalFree(buf)
class WindowsNamedPipeTransport(Transport):
""" connect to a named pipe """
def __init__(self, sockpath):
self.sockpath = u"\\\\.\\pipe\\{0}".format(sockpath)
while True:
self.pipe = CreateFile(
self.sockpath,
GENERIC_READ | GENERIC_WRITE,
0,
None,
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,
None,
)
err1 = GetLastError()
msg = _win32_strerror(err1)
if self.pipe != INVALID_HANDLE_VALUE:
break
if err1 != ERROR_PIPE_BUSY:
self.pipe = None
raise NailgunException(msg, NailgunException.CONNECT_FAILED)
if not WaitNamedPipe(self.sockpath, 5000):
self.pipe = None
raise NailgunException(
"time out while waiting for a pipe", NailgunException.CONNECT_FAILED
)
# event for the overlapped I/O operations
self.read_waitable = CreateEvent(None, True, False, None)
if self.read_waitable is None:
raise NailgunException(
"CreateEvent failed", NailgunException.CONNECT_FAILED
)
self.write_waitable = CreateEvent(None, True, False, None)
if self.write_waitable is None:
raise NailgunException(
"CreateEvent failed", NailgunException.CONNECT_FAILED
)
def _raise_win_err(self, msg, err):
raise IOError("%s win32 error code: %d %s" % (msg, err, _win32_strerror(err)))
def close(self):
if self.pipe:
CloseHandle(self.pipe)
self.pipe = None
if self.read_waitable is not None:
CloseHandle(self.read_waitable)
self.read_waitable = None
if self.write_waitable is not None:
CloseHandle(self.write_waitable)
self.write_waitable = None
def recv_into(self, buffer, nbytes):
# we don't use memoryview because OVERLAPPED I/O happens
# after the method (ReadFile) returns
buf = ctypes.create_string_buffer(nbytes)
olap = OVERLAPPED()
olap.hEvent = self.read_waitable
immediate = ReadFile(self.pipe, buf, nbytes, None, olap)
err = GetLastError()
if err == ERROR_NO_PROCESS_ON_OTHER_END_OF_PIPE:
raise NailgunException(
"No process on the other end of pipe",
NailgunException.CONNECTION_BROKEN,
)
if not immediate:
if err != ERROR_IO_PENDING:
self._raise_win_err("failed to read %d bytes" % nbytes, GetLastError())
nread = wintypes.DWORD()
if not GetOverlappedResult(self.pipe, olap, nread, True):
err = GetLastError()
self._raise_win_err("error while waiting for read", err)
nread = nread.value
if not is_py2:
# Wrap in a memoryview, as python3 does not let you assign from a
# ctypes.c_char_array slice directly to a memory view, as one is 'c', and one
# is '<c' struct/buffer proto format.
buf = compat_memoryview(buf)
buffer[:nread] = buf[:nread]
return nread
def sendall(self, data):
olap = OVERLAPPED()
olap.hEvent = self.write_waitable
p = (ctypes.c_ubyte * len(data))(*(bytearray(data)))
immediate = WriteFile(self.pipe, p, len(data), None, olap)
if not immediate:
err = GetLastError()
if err != ERROR_IO_PENDING:
self._raise_win_err(
"failed to write %d bytes" % len(data), GetLastError()
)
# Obtain results, waiting if needed
nwrote = wintypes.DWORD()
if not GetOverlappedResult(self.pipe, olap, nwrote, True):
err = GetLastError()
self._raise_win_err("error while waiting for write", err)
nwrote = nwrote.value
if nwrote != len(data):
raise IOError("Async wrote less bytes!")
return nwrote
def select(self, timeout_secs):
start = monotonic_time_nanos()
timeout_nanos = timeout_secs * NSEC_PER_SEC
while True:
readable, exceptional = self.select_now()
if (
readable
or exceptional
or monotonic_time_nanos() - start > timeout_nanos
):
return readable, exceptional
def select_now(self):
available_total = wintypes.DWORD()
exceptional = not PeekNamedPipe(self.pipe, None, 0, None, available_total, None)
readable = available_total.value > 0
result = readable, exceptional
return result
class NailgunConnection(object):
"""Stateful object holding the connection to the Nailgun server."""
def __init__(
self,
server_name,
server_port=None,
stdin=sys.stdin,
stdout=sys.stdout,
stderr=sys.stderr,
cwd=None,
heartbeat_interval_sec=DEFAULT_HEARTBEAT_INTERVAL_SEC,
):
self.transport = make_nailgun_transport(server_name, server_port, cwd)
self.stdin = stdin
self.stdout = stdout
self.stderr = stderr
self.recv_flags = 0
self.send_flags = 0
self.header_buf = ctypes.create_string_buffer(CHUNK_HEADER_LEN)
self.buf = ctypes.create_string_buffer(BUFSIZE)
self.exit_code = None
self.shutdown_event = Event()
self.error_lock = RLock()
self.error = None
self.error_traceback = None
self.stdin_condition = Condition()
self.stdin_thread = Thread(target=stdin_thread_main, args=(self,))
self.stdin_thread.daemon = True
self.send_queue = Queue.Queue()
self.send_condition = Condition()
self.send_thread = Thread(target=send_thread_main, args=(self,))
self.send_thread.daemon = True
self.heartbeat_interval_sec = heartbeat_interval_sec
self.heartbeat_condition = Condition()
self.heartbeat_thread = None
if heartbeat_interval_sec > 0:
self.heartbeat_thread = Thread(target=heartbeat_thread_main, args=(self,))
self.heartbeat_thread.daemon = True
def send_command(
self, cmd, cmd_args=[], filearg=None, env=os.environ, cwd=os.getcwd()
):
"""
Sends the command and environment to the nailgun server, then loops forever
reading the response until the server sends an exit chunk.
Returns the exit value, or raises NailgunException on error.
"""
try:
return self._send_command_and_read_response(
cmd, cmd_args, filearg, env, cwd
)
except socket.error as e:
re_raise(
NailgunException(
"Server disconnected unexpectedly: {0}".format(e),
NailgunException.CONNECTION_BROKEN,
)
)
def _send_command_and_read_response(self, cmd, cmd_args, filearg, env, cwd):
self.stdin_thread.start()
self.send_thread.start()
try:
if filearg:
self._send_file_arg(filearg)
for cmd_arg in cmd_args:
self._send_chunk(cmd_arg, CHUNKTYPE_ARG)
self._send_env_var("NAILGUN_FILESEPARATOR", os.sep)
self._send_env_var("NAILGUN_PATHSEPARATOR", os.pathsep)
self._send_tty_format(self.stdin)
self._send_tty_format(self.stdout)
self._send_tty_format(self.stderr)
for k, v in env.items():
self._send_env_var(k, v)
self._send_chunk(cwd, CHUNKTYPE_DIR)
self._send_chunk(cmd, CHUNKTYPE_CMD)
if self.heartbeat_thread is not None:
self.heartbeat_thread.start()
while self.exit_code is None:
self._process_next_chunk()
finally:
self.shutdown_event.set()
with self.stdin_condition:
self.stdin_condition.notify()
with self.send_condition:
self.send_condition.notify()
if self.heartbeat_thread is not None:
with self.heartbeat_condition:
self.heartbeat_condition.notify()
self.heartbeat_thread.join(THREAD_TERMINATION_TIMEOUT_SEC)
self.stdin_thread.join(THREAD_TERMINATION_TIMEOUT_SEC)
self.send_thread.join(THREAD_TERMINATION_TIMEOUT_SEC)
return self.exit_code
def _process_next_chunk(self):
"""
Processes the next chunk from the nailgun server.
"""
readable, exceptional = self.transport.select(SELECT_MAX_BLOCK_TIME_SEC)
if readable:
self._process_nailgun_stream()
if exceptional:
raise NailgunException(
"Server disconnected in select", NailgunException.CONNECTION_BROKEN
)
# if daemon thread threw, rethrow here
if self.shutdown_event.is_set():
e = None
e_tb = None
with self.error_lock:
e = self.error
e_tb = self.error_traceback
if e is not None:
re_raise(e, e_tb)
def _send_chunk(self, buf, chunk_type):
"""
Send chunk to the server asynchronously
"""
self.send_queue.put((chunk_type, buf))
with self.send_condition:
self.send_condition.notify()
def _send_env_var(self, name, value):
"""
Sends an environment variable in KEY=VALUE format.
"""
self._send_chunk("=".join((name, value)), CHUNKTYPE_ENV)
def _send_tty_format(self, f):
"""
Sends a NAILGUN_TTY_# environment variable.
"""
if not f or not hasattr(f, "fileno"):
return
try:
fileno = f.fileno()
isatty = os.isatty(fileno)
self._send_env_var("NAILGUN_TTY_" + str(fileno), str(int(isatty)))
except UnsupportedOperation:
return
def _send_file_arg(self, filename):
"""
Sends the contents of a file to the server.
"""
with open(filename) as f:
while True:
num_bytes = f.readinto(self.buf)
if not num_bytes:
break
self._send_chunk(self.buf.raw[:num_bytes], CHUNKTYPE_LONGARG)
def _recv_to_fd(self, dest_file, num_bytes):
"""
Receives num_bytes bytes from the nailgun socket and copies them to the specified file
object. Used to route data to stdout or stderr on the client.
"""
bytes_read = 0
while bytes_read < num_bytes:
bytes_to_read = min(len(self.buf), num_bytes - bytes_read)
bytes_received = self.transport.recv_into(self.buf, bytes_to_read)
if dest_file:
dest_file.write(bytes_to_str(self.buf[:bytes_received]))
bytes_read += bytes_received
def _recv_to_buffer(self, num_bytes, buf):
"""
Receives num_bytes from the nailgun socket and writes them into the specified buffer.
"""
# We'd love to use socket.recv_into() everywhere to avoid
# unnecessary copies, but we need to support Python 2.6. The
# only way to provide an offset to recv_into() is to use
# memoryview(), which doesn't exist until Python 2.7.
if HAS_MEMORYVIEW:
self._recv_into_memoryview(num_bytes, compat_memoryview(buf))
else:
self._recv_to_buffer_with_copy(num_bytes, buf)
def _recv_into_memoryview(self, num_bytes, buf_view):
"""
Receives num_bytes from the nailgun socket and writes them into the specified memoryview
to avoid an extra copy.
"""
bytes_read = 0
while bytes_read < num_bytes:
bytes_received = self.transport.recv_into(
buf_view[bytes_read:], num_bytes - bytes_read
)
if not bytes_received:
raise NailgunException(
"Server unexpectedly disconnected in recv_into()",
NailgunException.CONNECTION_BROKEN,
)
bytes_read += bytes_received
def _recv_to_buffer_with_copy(self, num_bytes, buf):
"""
Receives num_bytes from the nailgun socket and writes them into the specified buffer.
"""
bytes_read = 0
while bytes_read < num_bytes:
recv_buf = self.transport.recv(num_bytes - bytes_read)
if not len(recv_buf):
raise NailgunException(
"Server unexpectedly disconnected in recv()",
NailgunException.CONNECTION_BROKEN,
)
buf[bytes_read : bytes_read + len(recv_buf)] = recv_buf
bytes_read += len(recv_buf)
def _process_exit(self, exit_len):
"""
Receives an exit code from the nailgun server and sets nailgun_connection.exit_code
to indicate the client should exit.
"""
num_bytes = min(len(self.buf), exit_len)
self._recv_to_buffer(num_bytes, self.buf)
self.exit_code = int(self.buf.raw[:num_bytes])
def _send_heartbeat(self):
"""
Sends a heartbeat to the nailgun server to indicate the client is still alive.
"""
self._send_chunk("", CHUNKTYPE_HEARTBEAT)
def _process_nailgun_stream(self):
"""
Processes a single chunk from the nailgun server.
"""
self._recv_to_buffer(len(self.header_buf), self.header_buf)
(chunk_len, chunk_type) = struct.unpack_from(">ic", self.header_buf.raw)
if chunk_type == CHUNKTYPE_STDOUT:
self._recv_to_fd(self.stdout, chunk_len)
elif chunk_type == CHUNKTYPE_STDERR:
self._recv_to_fd(self.stderr, chunk_len)
elif chunk_type == CHUNKTYPE_EXIT:
self._process_exit(chunk_len)
elif chunk_type == CHUNKTYPE_SENDINPUT:
# signal stdin thread to get and send more data
with self.stdin_condition:
self.stdin_condition.notify()
else:
raise NailgunException(
"Unexpected chunk type: {0}".format(chunk_type),
NailgunException.UNEXPECTED_CHUNKTYPE,
)
def wait_termination(self, timeout):
"""
Wait for shutdown event to be signalled within specified interval
Return True if termination was signalled, False otherwise
"""
wait_time = timeout
start = monotonic_time_nanos()
with self.send_condition:
while True:
if self.shutdown_event.is_set():
return True
self.send_condition.wait(wait_time)
elapsed = (monotonic_time_nanos() - start) * 1.0 / NSEC_PER_SEC
wait_time = timeout - elapsed
if wait_time <= 0:
return False
return False
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
try:
self.transport.close()
except socket.error:
pass
def monotonic_time_nanos():
"""Returns a monotonically-increasing timestamp value in nanoseconds.
The epoch of the return value is undefined. To use this, you must call
it more than once and calculate the delta between two calls.
"""
# This function should be overwritten below on supported platforms.
raise Exception("Unsupported platform: " + platform.system())
if platform.system() == "Linux":
# From <linux/time.h>, available since 2.6.28 (released 24-Dec-2008).
CLOCK_MONOTONIC_RAW = 4
librt = ctypes.CDLL("librt.so.1", use_errno=True)
clock_gettime = librt.clock_gettime
class struct_timespec(ctypes.Structure):
_fields_ = [("tv_sec", ctypes.c_long), ("tv_nsec", ctypes.c_long)]
clock_gettime.argtypes = [ctypes.c_int, ctypes.POINTER(struct_timespec)]
def _monotonic_time_nanos_linux():
t = struct_timespec()
clock_gettime(CLOCK_MONOTONIC_RAW, ctypes.byref(t))
return t.tv_sec * NSEC_PER_SEC + t.tv_nsec
monotonic_time_nanos = _monotonic_time_nanos_linux
elif platform.system() == "Darwin":
# From <mach/mach_time.h>
KERN_SUCCESS = 0
libSystem = ctypes.CDLL("/usr/lib/libSystem.dylib", use_errno=True)
mach_timebase_info = libSystem.mach_timebase_info
class struct_mach_timebase_info(ctypes.Structure):
_fields_ = [("numer", ctypes.c_uint32), ("denom", ctypes.c_uint32)]
mach_timebase_info.argtypes = [ctypes.POINTER(struct_mach_timebase_info)]
mach_ti = struct_mach_timebase_info()
ret = mach_timebase_info(ctypes.byref(mach_ti))
if ret != KERN_SUCCESS:
raise Exception("Could not get mach_timebase_info, error: " + str(ret))
mach_absolute_time = libSystem.mach_absolute_time
mach_absolute_time.restype = ctypes.c_uint64
def _monotonic_time_nanos_darwin():
return (mach_absolute_time() * mach_ti.numer) / mach_ti.denom
monotonic_time_nanos = _monotonic_time_nanos_darwin
elif platform.system() == "Windows":
# From <Winbase.h>
perf_frequency = ctypes.c_uint64()
ctypes.windll.kernel32.QueryPerformanceFrequency(ctypes.byref(perf_frequency))
def _monotonic_time_nanos_windows():
perf_counter = ctypes.c_uint64()
ctypes.windll.kernel32.QueryPerformanceCounter(ctypes.byref(perf_counter))
return perf_counter.value * NSEC_PER_SEC / perf_frequency.value
monotonic_time_nanos = _monotonic_time_nanos_windows
elif sys.platform == "cygwin":
k32 = ctypes.CDLL("Kernel32", use_errno=True)
perf_frequency = ctypes.c_uint64()
k32.QueryPerformanceFrequency(ctypes.byref(perf_frequency))
def _monotonic_time_nanos_cygwin():
perf_counter = ctypes.c_uint64()
k32.QueryPerformanceCounter(ctypes.byref(perf_counter))
return perf_counter.value * NSEC_PER_SEC / perf_frequency.value
monotonic_time_nanos = _monotonic_time_nanos_cygwin
def send_thread_main(conn):
"""
Sending thread worker function
Waits for data and transmits it to server
"""
try:
header_buf = ctypes.create_string_buffer(CHUNK_HEADER_LEN)
while True:
connection_error = None
while not conn.send_queue.empty():
# only this thread can deplete the queue, so it is safe to use blocking get()
(chunk_type, buf) = conn.send_queue.get()
struct.pack_into(">ic", header_buf, 0, len(buf), chunk_type)
bbuf = to_bytes(buf)
# these chunk types are not required for server to accept and process and server may terminate
# any time without waiting for them
is_required = chunk_type not in (
CHUNKTYPE_HEARTBEAT,
CHUNKTYPE_STDIN,
CHUNKTYPE_STDIN_EOF,
)
try:
conn.transport.sendall(header_buf.raw)
conn.transport.sendall(bbuf)
except socket.error as e:
# The server may send termination signal and close the socket immediately; attempt to write
# to such a socket (i.e. heartbeats) results in an error (SIGPIPE)
# Nailgun protocol is not duplex so the server does not wait on client to acknowledge
# We catch an exception and ignore it if termination has happened shortly afterwards
if not is_required and conn.wait_termination(
SEND_THREAD_WAIT_TERMINATION_SEC
):
return
raise
with conn.send_condition:
if conn.shutdown_event.is_set():
return
if not conn.send_queue.empty():
continue
conn.send_condition.wait()
if conn.shutdown_event.is_set():
return
except Exception as e:
# save exception to rethrow on main thread
with conn.error_lock:
conn.error = e
conn.error_traceback = sys.exc_info()[2]
conn.shutdown_event.set()
def stdin_thread_main(conn):
"""
Stdin thread reading worker function
If stdin is available, read it to internal buffer and send to server
"""
try:
eof = False
while True:
# wait for signal to read new line from stdin or shutdown
# we do not start reading from stdin before server actually requests that
with conn.stdin_condition:
if conn.shutdown_event.is_set():
return
conn.stdin_condition.wait()
if conn.shutdown_event.is_set():
return
if not conn.stdin or eof:
conn._send_chunk(buf, CHUNKTYPE_STDIN_EOF)
continue
buf = conn.stdin.readline()
if buf == "":
eof = True
conn._send_chunk(buf, CHUNKTYPE_STDIN_EOF)
continue
conn._send_chunk(buf, CHUNKTYPE_STDIN)
except Exception as e:
# save exception to rethrow on main thread
with conn.error_lock:
conn.error = e
conn.error_traceback = sys.exc_info()[2]
conn.shutdown_event.set()
def heartbeat_thread_main(conn):
"""
Heartbeat thread worker function
Periodically sends heartbeats to server as long as command is running
"""
try:
while True:
with conn.heartbeat_condition:
if conn.shutdown_event.is_set():
return
conn.heartbeat_condition.wait(conn.heartbeat_interval_sec)
if conn.shutdown_event.is_set():
return
conn._send_heartbeat()
except Exception as e:
# save exception to rethrow on main thread
with conn.error_lock:
conn.error = e
conn.error_traceback = sys.exc_info()[2]
conn.shutdown_event.set()
def make_nailgun_transport(nailgun_server, nailgun_port=None, cwd=None):
"""
Creates and returns a socket connection to the nailgun server.
"""
transport = None
if nailgun_server.startswith("local:"):
if platform.system() == "Windows":
pipe_addr = nailgun_server[6:]
transport = WindowsNamedPipeTransport(pipe_addr)
else:
try:
s = socket.socket(socket.AF_UNIX)
except socket.error as msg:
re_raise(
NailgunException(
"Could not create local socket connection to server: {0}".format(
msg
),
NailgunException.SOCKET_FAILED,
)
)
socket_addr = nailgun_server[6:]
prev_cwd = os.getcwd()
try:
if cwd is not None:
os.chdir(cwd)
s.connect(socket_addr)
transport = UnixTransport(s)
except socket.error as msg:
re_raise(
NailgunException(
"Could not connect to local server at {0}: {1}".format(
socket_addr, msg
),
NailgunException.CONNECT_FAILED,
)
)
finally:
if cwd is not None:
os.chdir(prev_cwd)
else:
socket_addr = nailgun_server
socket_family = socket.AF_UNSPEC
for (af, socktype, proto, _, sa) in socket.getaddrinfo(
nailgun_server, nailgun_port, socket.AF_UNSPEC, socket.SOCK_STREAM
):
try:
s = socket.socket(af, socktype, proto)
except socket.error as msg:
s = None
continue
try:
s.connect(sa)
transport = UnixTransport(s)
except socket.error as msg:
s.close()
s = None
continue
break
if transport is None:
raise NailgunException(
"Could not connect to server {0}:{1}".format(nailgun_server, nailgun_port),
NailgunException.CONNECT_FAILED,
)
return transport
if is_py2:
exec(
'''
def re_raise(ex, ex_trace = None):
"""
Throw ex and preserve stack trace of original exception if we run on Python 2
"""
if ex_trace is None:
ex_trace = sys.exc_info()[2]
raise ex, None, ex_trace
'''
)
else:
def re_raise(ex, ex_trace=None):
"""
Throw ex and preserve stack trace of original exception if we run on Python 2
"""
raise ex
def main():
"""
Main entry point to the nailgun client.
"""
default_nailgun_server = os.environ.get("NAILGUN_SERVER", "127.0.0.1")
default_nailgun_port = int(os.environ.get("NAILGUN_PORT", NAILGUN_PORT_DEFAULT))
parser = optparse.OptionParser(usage="%prog [options] cmd arg1 arg2 ...")
parser.add_option("--nailgun-server", default=default_nailgun_server)
parser.add_option("--nailgun-port", type="int", default=default_nailgun_port)
parser.add_option("--nailgun-filearg")
parser.add_option("--nailgun-showversion", action="store_true")
parser.add_option("--nailgun-help", action="help")
(options, args) = parser.parse_args()
if options.nailgun_showversion:
print("NailGun client version " + NAILGUN_VERSION)
if len(args):
cmd = args.pop(0)
else:
cmd = os.path.basename(sys.argv[0])
# Pass any remaining command line arguments to the server.
cmd_args = args
try:
with NailgunConnection(
options.nailgun_server, server_port=options.nailgun_port
) as c:
exit_code = c.send_command(cmd, cmd_args, options.nailgun_filearg)
sys.exit(exit_code)
except NailgunException as e:
sys.stderr.write(str(e))
sys.exit(e.code)
except KeyboardInterrupt as e:
pass
if __name__ == "__main__":
main()
|
hpds-02-A-01.py | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 7 08:59:27 2020
Contoh Threading sederhana di Python 3
@author: Taufik Sutanto
"""
import threading
def print_cube(num):
print("Cube: {}".format(num * num * num))
def print_square(num):
print("Square: {}".format(num * num))
if __name__ == "__main__":
# creating thread
t1 = threading.Thread(target=print_square, args=(10,))
t2 = threading.Thread(target=print_cube, args=(10,))
t1.start() # starting thread 1
t2.start() # starting thread 2
t1.join() # wait until thread 1 is completely executed
t2.join() # wait until thread 2 is completely executed
# both threads completely executed
print("Done!") |
test_multiprocessing.py | # coding: utf-8
import os
from multiprocessing import Process
# ๅญ่ฟ็จ่ฆๆง่ก็ไปฃ็
def run_proc(name):
print('Run child process %s (%s)...' % (name, os.getpid()))
print('Pid: %s, __name__: %s' % (os.getpid(), __name__))
if __name__ == '__main__':
print('Parent process %s.' % (os.getpid(),))
p = Process(target=run_proc, args=('test',))
print('Child process will start.')
p.start()
p.join()
print('child process end.')
'''
on windows:
Pid: 22236, __name__: __main__
Parent process 22236.
Child process will start.
Pid: 17600, __name__: __mp_main__ # windowsไธไผๅค่ฟไธ่ก
Run child process test (17600)...
child process end.
on linux:
Pid: 11860, __name__: __main__
Parent process 11860.
Child process will start.
Run child process test (11861)...
child process end.
'''
|
__main__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# MIT License
# Copyright (c) 2020 Stษrry Shivษm // This file is part of AcuteBot
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import os, sys, importlib
from threading import Thread
from acutebot import LOG, dp, updater, DEV_ID
from acutebot.funcs import ALL_FUNCS
import acutebot.helpers.strings as st
from telegram import InlineKeyboardMarkup, InlineKeyboardButton
from telegram.ext.dispatcher import run_async
from telegram.ext import CommandHandler, CallbackQueryHandler, Filters
# Import all funcs in main
for func_name in ALL_FUNCS:
imported_module = importlib.import_module("acutebot.funcs." + func_name)
def send_start(update):
msg = update.effective_message
msg.reply_photo(
"https://telegra.ph/file/35c83c568502b9944c76d.jpg",
st.START_STRING.format(update.effective_user.first_name),
reply_markup=InlineKeyboardMarkup(
[
[
InlineKeyboardButton(
text="Movie", switch_inline_query_current_chat="<movie> ",
),
InlineKeyboardButton(
text="TVshow", switch_inline_query_current_chat="<tv> ",
),
InlineKeyboardButton(
text="Anime", switch_inline_query_current_chat="<anime> ",
),
],
[InlineKeyboardButton(text="๐พ About me ๐พ", callback_data="about")],
[InlineKeyboardButton(text="Help and Commandsโ", callback_data="help")],
]
),
)
@run_async
def about_button(update, context):
query = update.callback_query
query.answer()
query.message.delete()
query.message.reply_text(
st.ABOUT_STR,
disable_web_page_preview=True,
reply_markup=InlineKeyboardMarkup(
[
[
InlineKeyboardButton(
text="Github ๐ญ", url="https://github.com/starry69"
),
InlineKeyboardButton(text="Donate ๐ค", url="paypal.me/starryrays"),
],
[InlineKeyboardButton(text="Go back ๐", callback_data="back_btn")],
]
),
)
@run_async
def help_button(update, context):
query = update.callback_query
query.answer()
query.message.delete()
query.message.reply_text(
st.HELP_STR,
reply_markup=InlineKeyboardMarkup(
[[InlineKeyboardButton(text="Go back ๐", callback_data="back_btn")]]
),
)
@run_async
def start(update, context):
if update.effective_chat.type == "private":
return send_start(update)
update.effective_message.reply_text(st.START_STRING_GRP)
@run_async
def back_btn(update, context):
query = update.callback_query
query.message.delete()
send_start(update)
context.bot.answer_callback_query(query.id)
BANNER = r"""
___ ___ ______ ___
/ _ \ | | | ___ \ | |
/ /_\ \ ___ _ _| |_ ___| |_/ / ___ | |_
| _ |/ __| | | | __/ _ \ ___ \/ _ \| __|
| | | | (__| |_| | || __/ |_/ / (_) | |_
\_| |_/\___|\__,_|\__\___\____/ \___/ \__|
Is Running ๐ถ๐ถ๐ต
"""
def main():
def stop_and_restart():
updater.stop()
os.execl(sys.executable, sys.executable, *sys.argv)
def restart(update, context):
context.bot.sendMessage(update.effective_chat.id, "Rebooted โจ")
Thread(target=stop_and_restart).start()
restart_handler = CommandHandler("reboot", restart, filters=Filters.user(DEV_ID))
start_handler = CommandHandler("start", start)
about_handler = CallbackQueryHandler(about_button, pattern=r"about")
help_handler = CallbackQueryHandler(help_button, pattern=r"help")
back_btn_handler = CallbackQueryHandler(back_btn, pattern=r"back_btn")
dp.add_handler(restart_handler)
dp.add_handler(start_handler)
dp.add_handler(about_handler)
dp.add_handler(help_handler)
dp.add_handler(back_btn_handler)
LOG.info("%s", BANNER)
# Start the bot.
updater.start_polling(timeout=15, read_latency=4)
updater.idle()
if __name__ == "__main__":
main()
|
Hiwin_RT605_ArmCommand_Socket_20190627203926.py | #!/usr/bin/env python3
# license removed for brevity
import rospy
import os
import socket
##ๅคๅท่กๅบ
import threading
import time
import sys
import matplotlib as plot
import HiwinRA605_socket_TCPcmd as TCP
import HiwinRA605_socket_Taskcmd as Taskcmd
import numpy as np
from std_msgs.msg import String
from ROS_Socket.srv import *
from ROS_Socket.msg import *
from std_msgs.msg import Int32MultiArray
import math
import enum
#Socket = 0
data = '0' #่จญๅฎๅณ่ผธ่ณๆๅๅงๅผ
Arm_feedback = 1 #ๅ่จญๆ่ๅฟ็ข
NAME = 'socket_server'
arm_mode_flag = False
##------------class pos-------
class point():
def __init__(self, x, y, z, pitch, roll, yaw):
self.x = x
self.y = y
self.z = z
self.pitch = pitch
self.roll = roll
self.yaw = yaw
pos = point(0.0,36.8,11.35,-90.0,0.0,0.0)
##------------class socket_cmd---------
class socket_data():
def __init__(self, grip, setvel, ra, delay, setboth, action,Speedmode):
self.grip = grip
self.setvel = setvel
self.ra = ra
self.delay = delay
self.setboth = setboth
self.action = action
self.Speedmode = Speedmode
socket_cmd = socket_data(0,0.0,0,0,0,0,0)
##-----------switch define------------##
class switch(object):
def __init__(self, value):
self.value = value
self.fall = False
def __iter__(self):
"""Return the match method once, then stop"""
yield self.match
raise StopIteration
def match(self, *args):
"""Indicate whether or not to enter a case suite"""
if self.fall or not args:
return True
elif self.value in args: # changed for v1.5, see below
self.fall = True
return True
else:
return False
##-----------client feedback arm state----------
class StateFeedback():
def __init__(self,ArmState,SentFlag):
self.ArmState = ArmState
self.SentFlag = SentFlag
state_feedback = StateFeedback(0,0)
class client():
def __init__(self):
#self.get_connect()
pass
def get_connect(self):
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.s.connect(('192.168.0.1', 8080))
def send(self, msg):
self.s.send(msg.encode('utf-8')) #็จutf-8ไพencode๏ผ้ๆๅ
ถไปencode็ๆนๆณ๏ผstr็จutf-8ๅฐฑOK!
def get_recieve(self):
data = self.s.recv(1024) #1024ๆๅฎbuffer็ๅคงๅฐ๏ผ้ๅถไธๆฌกๆถๅคๅฐ
data.decode('utf-8')
return data
def close(self):
self.s.close()
Socket = client()
def point_data(x,y,z,pitch,roll,yaw): ##ๆฅๆถ็ญ็ฅ็ซฏๅณ้ไฝๅงฟ่ณๆ
pos.x = x
pos.y = y
pos.z = z
pos.pitch = pitch
pos.roll = roll
pos.yaw = yaw
##----------Arm Mode-------------###
def Arm_Mode(action,grip,ra,setvel,setboth): ##ๆฅๆถ็ญ็ฅ็ซฏๅณ้ๆ่ๆจกๅผ่ณๆ
global arm_mode_flag
socket_cmd.action = action
socket_cmd.grip = grip
socket_cmd.ra = ra
socket_cmd.setvel = setvel
socket_cmd.setboth = setboth
arm_mode_flag = True
Socket_command()
##-------Arm Speed Mode------------###
def Speed_Mode(speedmode): ##ๆฅๆถ็ญ็ฅ็ซฏๅณ้ๆ่ๆจกๅผ่ณๆ
socket_cmd.Speedmode = speedmode
def socket_talker(): ##ๅตๅปบServer node
pub = rospy.Publisher('chatter', Int32MultiArray, queue_size=10)
rospy.init_node(NAME)
rate = rospy.Rate(10) # 10hz
print ("Ready to connect")
while not rospy.is_shutdown():
# hello_str = "hello world %s" % rospy.get_time()
state = Int32MultiArray()
state.data = [state_feedback.ArmState,state_feedback.SentFlag]
pub.publish(state)
rate.sleep()
##----------socket ๅฐๅ
ๅณ่ผธ--------------##
##---------------socket ๅณ่ผธๆ่ๅฝไปค-----------------
def Socket_command():
global arm_mode_flag,data
# if arm_mode_flag == True:
# arm_mode_flag = False
for case in switch(socket_cmd.action):
#-------PtP Mode--------
if case(Taskcmd.Action_Type.PtoP):
for case in switch(socket_cmd.setboth):
if case(Taskcmd.Ctrl_Mode.CTRL_POS):
data = TCP.SetPtoP(socket_cmd.grip,Taskcmd.RA.ABS,Taskcmd.Ctrl_Mode.CTRL_POS,pos.x,pos.y,pos.z,pos.pitch,pos.roll,pos.yaw,socket_cmd.setvel)
break
if case(Taskcmd.Ctrl_Mode.CTRL_EULER):
data = TCP.SetPtoP(socket_cmd.grip,Taskcmd.RA.ABS,Taskcmd.Ctrl_Mode.CTRL_EULER,pos.x,pos.y,pos.z,pos.pitch,pos.roll,pos.yaw,socket_cmd.setvel)
break
if case(Taskcmd.Ctrl_Mode.CTRL_BOTH):
data = TCP.SetPtoP(socket_cmd.grip,Taskcmd.RA.ABS,Taskcmd.Ctrl_Mode.CTRL_BOTH,pos.x,pos.y,pos.z,pos.pitch,pos.roll,pos.yaw,socket_cmd.setvel)
break
break
#-------Line Mode--------
if case(Taskcmd.Action_Type.Line):
for case in switch(socket_cmd.setboth):
if case(Taskcmd.Ctrl_Mode.CTRL_POS):
data = TCP.SetLine(socket_cmd.grip,Taskcmd.RA.ABS,Taskcmd.Ctrl_Mode.CTRL_POS,pos.x,pos.y,pos.z,pos.pitch,pos.roll,pos.yaw,socket_cmd.setvel)
break
if case(Taskcmd.Ctrl_Mode.CTRL_EULER):
data = TCP.SetLine(socket_cmd.grip,Taskcmd.RA.ABS,Taskcmd.Ctrl_Mode.CTRL_EULER,pos.x,pos.y,pos.z,pos.pitch,pos.roll,pos.yaw,socket_cmd.setvel )
break
if case(Taskcmd.Ctrl_Mode.CTRL_BOTH):
data = TCP.SetLine(socket_cmd.grip,Taskcmd.RA.ABS,Taskcmd.Ctrl_Mode.CTRL_BOTH,pos.x,pos.y,pos.z,pos.pitch,pos.roll,pos.yaw,socket_cmd.setvel )
break
break
#-------่จญๅฎๆ่้ๅบฆ--------
if case(Taskcmd.Action_Type.SetVel):
data = TCP.SetVel(socket_cmd.grip, socket_cmd.setvel)
break
#-------่จญๅฎๆ่Delayๆ้--------
if case(Taskcmd.Action_Type.Delay):
data = TCP.SetDelay(socket_cmd.grip,0)
break
#-------่จญๅฎๆ่ๆฅ้&ๅฎๅ
จๆจกๅผ--------
if case(Taskcmd.Action_Type.Mode):
data = TCP.Set_SpeedMode(socket_cmd.grip,socket_cmd.Speedmode)
break
socket_cmd.action= 6 ##ๅๆๅๅงmode็ๆ
print(data)
print("Socket:", Socket)
#Socket.send(data.encode('utf-8'))#socketๅณ้for python to translate str
Socket.send(data)
##-----------socket client--------
def socket_client():
#global Socket
try:
#Socket = client()
Socket.get_connect()
#Socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#Socket.connect(('192.168.0.1', 8080))#iclab 5 ๏ผ iclab hiwin
#s.connect(('192.168.1.102', 8080))#iclab computerx
print('Connection has been successful')
except socket.error as msg:
print(msg)
sys.exit(1)
#print('Connection has been successful')
Socket_feedback(Socket)
rospy.on_shutdown(myhook)
Socket.close()
def Socket_feedback(s):
Socket = s
while 1:
feedback_str = Socket.get_recieve()
#ๆ่็ซฏๅณ้ๆ่็ๆ
if str(feedback_str[2]) == '48':# F ๆ่็บReady็ๆ
ๆบๅๆฅๆถไธไธๅ้ๅๆไปค
state_feedback.ArmState = 0
if str(feedback_str[2]) == '49':# T ๆ่็บๅฟ็ข็ๆ
็กๆณๅท่กไธไธๅ้ๅๆไปค
state_feedback.ArmState = 1
if str(feedback_str[2]) == '54':# 6 ็ญ็ฅๅฎๆ
state_feedback.ArmState = 6
print("shutdown")
#็ขบ่ชๅณ้ๆๆจ
if str(feedback_str[4]) == '48':#ๅๅณ0 false
state_feedback.SentFlag = 0
if str(feedback_str[4]) == '49':#ๅๅณ1 true
state_feedback.SentFlag = 1
##---------------socket ๅณ่ผธๆ่ๅฝไปค end-----------------
if state_feedback.ArmState == Taskcmd.Arm_feedback_Type.shutdown:
break
##-----------socket client end--------
##-------------socket ๅฐๅ
ๅณ่ผธ end--------------##
def myhook():
print ("shutdown time!")
if __name__ == '__main__':
socket_cmd.action = 6##ๅๆๅๅงmode็ๆ
## ๅคๅท่ก็ท
t = threading.Thread(target=socket_client)
t.start() # ้ๅๅคๅท่ก็ท
#time.sleep(1)
try:
socket_talker()
except rospy.ROSInterruptException:
pass
t.join()
## ๅคๅท่กๅบ end
|
test_queue.py | import unittest
from queue import Empty, Full
from threading import Thread
from extra_foam.pipeline.f_queue import SimpleQueue
class TestSimpleQueue(unittest.TestCase):
def testGeneral(self):
queue = SimpleQueue(maxsize=2)
self.assertTrue(queue.empty())
queue.put_nowait(1)
queue.put(2)
with self.assertRaises(Full):
queue.put(3)
self.assertTrue(queue.full())
self.assertEqual(2, queue.qsize())
self.assertEqual(1, queue.get())
self.assertEqual(2, queue.get())
with self.assertRaises(Empty):
queue.get()
self.assertTrue(queue.empty())
# test no maxsize
queue = SimpleQueue()
for i in range(100):
queue.put(i)
self.assertEqual(100, queue.qsize())
self.assertFalse(queue.full())
queue.clear()
self.assertTrue(queue.empty())
def testMultiThreads(self):
def worker1(queue):
for i in range(100):
queue.put(i)
def worker2(queue):
for _ in range(100):
queue.get()
queue = SimpleQueue()
t1 = Thread(target=worker1, args=(queue,))
t2 = Thread(target=worker2, args=(queue,))
t1.start()
t2.start()
t1.join()
t2.join()
self.assertTrue(queue.empty())
|
logistic_parallel.py | import multiprocessing as mp
import queue
import time
from multiprocessing import sharedctypes
import numpy as np
from numpy import ctypeslib
from scipy.sparse import isspmatrix
from scipy.special import expit as sigmoid
from base_logistic import BaseLogistic
from constants import INIT_WEIGHT_STD
from memory import GradientMemory
from parameters import Parameters
TIMEOUT = 1
LOSS_PER_EPOCH = 10
class LogisticParallelSGD(BaseLogistic):
"""2 classes logistic regression on dense dataset.
X: (num_samples, num_features)
y: (num_features, ) 0, 1 labels
"""
def __init__(self, params: Parameters):
super().__init__(params)
self.params = params
self.w = None
self.epoch_callback = None
self.print = False
def fit_until(self, X, y, num_samples, num_features, baseline=None):
# num_samples, num_features = X.shape
p = self.params
if self.w is None:
self.w = np.random.normal(0, INIT_WEIGHT_STD, size=(num_features,))
def worker_fit(id_w, num_workers, X_w, y_w, weights_w, shape, indices, results, params_w, stopper):
# reconstruct numpy shared array
num_samples, num_features = shape
weights_w = ctypeslib.as_array(weights_w)
weights_w.shape = (num_features,)
if not isspmatrix(X_w):
X_w = ctypeslib.as_array(X_w)
X_w.shape = (num_samples, num_features)
y_w = ctypeslib.as_array(y_w)
y_w.shape = (num_samples,)
memory = GradientMemory(take_k=params_w.take_k, take_top=params_w.take_top,
with_memory=params_w.with_memory)
if id_w == 0:
losses = np.zeros(params_w.num_epoch * LOSS_PER_EPOCH + 1)
losses[0] = self.loss(X, y)
start_time = time.time()
last_printed = 0
loss_every = num_samples // LOSS_PER_EPOCH
for epoch in range(params_w.num_epoch):
for iteration in range(id_w, num_samples, num_workers):
# worker 0 gave stop signal, reached accuracy
if stopper.value:
return
sample_idx = indices[epoch][iteration]
lr = self.lr(epoch, iteration, num_samples, num_features)
x = X_w[sample_idx]
if isspmatrix(x):
x = np.array(x.todense()).squeeze(0)
minus_grad = y[sample_idx] * x * sigmoid(-y[sample_idx] * np.dot(x, self.w))
# minus_grad = - x * (pred_proba - y_w[sample_idx])
if params_w.regularizer:
minus_grad -= 2 * params_w.regularizer * weights_w
sparse = params_w.take_k and (params_w.take_k < num_features)
# next_real -= 1
lr_minus_grad = memory(lr * minus_grad, sparse=sparse) # , no_apply=(next_real != 0))
# if next_real == 0:
# next_real = params_w.real_update_every
if sparse:
weights_w[lr_minus_grad[0]] += lr_minus_grad[1]
else:
weights_w += lr_minus_grad
if id_w == 0 and num_samples * epoch + iteration - last_printed >= loss_every:
last_printed = num_samples * epoch + iteration
timing = time.time() - start_time
loss = self.loss(X, y)
losses[epoch * LOSS_PER_EPOCH + (iteration // loss_every) + 1] = loss
print("epoch {} iter {} loss {} time {}s".format(
epoch, iteration, loss, timing))
if baseline and loss <= baseline:
stopper.value = True
results['epoch'] = epoch
results['losses'] = losses
results['iteration'] = iteration
results['timing'] = timing
return
# if failed to converge...
if id_w == 0:
results['epoch'] = epoch
results['losses'] = losses
results['iteration'] = iteration
results['timing'] = time.time() - start_time
with mp.Manager() as manager: # multiprocessing -----------------------------------
results = manager.dict()
stopper = manager.Value('b', False)
indices = np.zeros((p.num_epoch, num_samples), dtype=int)
for i in range(p.num_epoch):
indices[i] = np.arange(num_samples)
np.random.shuffle(indices[i])
weights_w = sharedctypes.RawArray('d', self.w)
self.w = ctypeslib.as_array(weights_w)
self.w.shape = (num_features,)
if isspmatrix(X):
X_w = X
y_w = y
else:
X_w = sharedctypes.RawArray('d', np.ravel(X))
y_w = sharedctypes.RawArray('d', y)
# ------- multiprocessing -------
processes = [mp.Process(target=worker_fit,
args=(i, p.n_cores, X_w, y_w, weights_w, X.shape, indices, results, self.params, stopper))
for i in range(p.n_cores)]
for p in processes:
p.start()
for i, p in enumerate(processes):
p.join()
print(results)
return results['timing'], results['epoch'], results['iteration'], results['losses']
def fit(self, X, y, num_samples, num_features, loss_per_epoch=10):
p = self.params
if self.w is None:
self.w = np.random.normal(0, INIT_WEIGHT_STD, size=(num_features,))
def worker_fit(id_w, num_workers, X_w, y_w, weights_w, shape, indices, counter, start_barrier, params_w):
assert params_w.regularizer is not None
# reconstruct numpy shared array
num_samples, num_features = shape
weights_w = ctypeslib.as_array(weights_w)
weights_w.shape = (num_features,)
if not isspmatrix(X_w):
X_w = ctypeslib.as_array(X_w)
X_w.shape = (num_samples, num_features)
y_w = ctypeslib.as_array(y_w)
y_w.shape = (num_samples,)
memory = GradientMemory(take_k=params_w.take_k, take_top=params_w.take_top,
with_memory=params_w.with_memory)
start_barrier.wait()
while True:
with counter.get_lock():
idx = counter.value
counter.value += 1
if idx >= num_samples * params_w.num_epoch:
break
sample_idx = indices[idx]
epoch = idx // num_samples
iteration = idx % num_samples
lr = self.lr(epoch, iteration, num_samples, num_features)
x = X_w[sample_idx]
if isspmatrix(x):
minus_grad = -1. * params_w.regularizer * weights_w
sparse_minus_grad = y[sample_idx] * x * sigmoid(-y[sample_idx] * x.dot(weights_w).squeeze(0))
minus_grad[sparse_minus_grad.indices] += sparse_minus_grad.data
else:
minus_grad = y[sample_idx] * x * sigmoid(-y[sample_idx] * x.dot(weights_w))
minus_grad -= params_w.regularizer * weights_w
sparse = params_w.take_k and (params_w.take_k < num_features)
lr_minus_grad = memory(lr * minus_grad, sparse=sparse)
if sparse:
weights_w[lr_minus_grad[0]] += lr_minus_grad[1]
else:
weights_w += lr_minus_grad
with mp.Manager() as manager: # multiprocessing -----------------------------------
counter = mp.Value('i', 0)
start_barrier = manager.Barrier(p.n_cores + 1) # wait all worker and the monitor to be ready
indices = np.zeros((p.num_epoch, num_samples), dtype=int)
for i in range(p.num_epoch):
indices[i] = np.arange(num_samples)
np.random.shuffle(indices[i])
indices = indices.flatten()
weights_w = sharedctypes.RawArray('d', self.w)
self.w = ctypeslib.as_array(weights_w)
self.w.shape = (num_features,)
if isspmatrix(X):
X_w = X
y_w = y
else:
X_w = sharedctypes.RawArray('d', np.ravel(X))
y_w = sharedctypes.RawArray('d', y)
# ------- multiprocessing -------
processes = [mp.Process(target=worker_fit,
args=(
i, p.n_cores, X_w, y_w, weights_w, X.shape, indices, counter, start_barrier,
self.params))
for i in range(p.n_cores)]
for p in processes:
p.start()
# monitor the progress
print_every = num_samples // loss_per_epoch
next_print = 0
# loss computing on another thread through the queue
stop = manager.Value('b', False)
w_queue = mp.Queue() # multiprocessing -----------------------------------
results = manager.dict()
def loss_computer(q, regularizer, res, stop): # should be stoppable
print('start loss computer')
losses = []
iters = []
timers = []
while not q.empty() or not stop.value:
try:
epoch, iter_, total_iter, chrono, w = q.get(block=True, timeout=1)
except queue.Empty:
# print('empty queue')
continue
# print('dequeue', epoch, iter_)
loss = np.sum(np.log(1 + np.exp(-y * (X @ w)))) / X.shape[0]
if regularizer is not None:
loss += regularizer * np.square(w).sum() / 2
timers.append(chrono)
losses.append(loss)
iters.append(total_iter)
print("epoch {} iteration {} loss {} time {}s".format(epoch, iter_, loss, chrono))
res['losses'] = np.array(losses)
res['iters'] = np.array(iters)
res['timers'] = np.array(timers)
start_barrier.wait()
start_time = time.time()
# ------- multiprocessing -------
loss_computer = mp.Process(target=loss_computer, args=(w_queue, self.params.regularizer, results, stop))
loss_computer.start()
while counter.value < self.params.num_epoch * num_samples:
if counter.value > next_print:
w_copy = (self.w_estimate if self.w_estimate is not None else self.w).copy()
epoch = next_print // num_samples
iter_ = next_print % num_samples
chrono = time.time() - start_time
w_queue.put((epoch, iter_, next_print, chrono, w_copy))
# print('enqueue', epoch, iter_)
next_print += print_every
else:
time.sleep(.1)
stop.value = True # stop the loss computer
for i, p in enumerate(processes):
p.join()
loss_computer.join()
print(results)
return results['iters'], results['timers'], results['losses']
|
test_sigma_dut.py | # Test cases for sigma_dut
# Copyright (c) 2017, Qualcomm Atheros, Inc.
#
# This software may be distributed under the terms of the BSD license.
# See README for more details.
import logging
logger = logging.getLogger()
import os
import socket
import subprocess
import threading
import time
import hostapd
from utils import HwsimSkip
from hwsim import HWSimRadio
from test_dpp import check_dpp_capab, update_hapd_config
from test_suite_b import check_suite_b_192_capa, suite_b_as_params, suite_b_192_rsa_ap_params
def check_sigma_dut():
if not os.path.exists("./sigma_dut"):
raise HwsimSkip("sigma_dut not available")
def sigma_dut_cmd(cmd, port=9000, timeout=2):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
socket.IPPROTO_TCP)
sock.settimeout(timeout)
addr = ('127.0.0.1', port)
sock.connect(addr)
sock.send(cmd + "\r\n")
try:
res = sock.recv(1000)
running = False
done = False
for line in res.splitlines():
if line.startswith("status,RUNNING"):
running = True
elif line.startswith("status,INVALID"):
done = True
elif line.startswith("status,ERROR"):
done = True
elif line.startswith("status,COMPLETE"):
done = True
if running and not done:
# Read the actual response
res = sock.recv(1000)
except:
res = ''
pass
sock.close()
res = res.rstrip()
logger.debug("sigma_dut: '%s' --> '%s'" % (cmd, res))
return res
def sigma_dut_cmd_check(cmd, port=9000, timeout=2):
res = sigma_dut_cmd(cmd, port=port, timeout=timeout)
if "COMPLETE" not in res:
raise Exception("sigma_dut command failed: " + cmd)
return res
def start_sigma_dut(ifname, debug=False, hostapd_logdir=None, cert_path=None):
check_sigma_dut()
cmd = [ './sigma_dut',
'-M', ifname,
'-S', ifname,
'-F', '../../hostapd/hostapd',
'-G',
'-w', '/var/run/wpa_supplicant/',
'-j', ifname ]
if debug:
cmd += [ '-d' ]
if hostapd_logdir:
cmd += [ '-H', hostapd_logdir ]
if cert_path:
cmd += [ '-C', cert_path ]
sigma = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
for i in range(20):
try:
res = sigma_dut_cmd("HELLO")
break
except:
time.sleep(0.05)
return sigma
def stop_sigma_dut(sigma):
sigma.terminate()
sigma.wait()
out, err = sigma.communicate()
logger.debug("sigma_dut stdout: " + str(out))
logger.debug("sigma_dut stderr: " + str(err))
def sigma_dut_wait_connected(ifname):
for i in range(50):
res = sigma_dut_cmd("sta_is_connected,interface," + ifname)
if "connected,1" in res:
break
time.sleep(0.2)
if i == 49:
raise Exception("Connection did not complete")
def test_sigma_dut_basic(dev, apdev):
"""sigma_dut basic functionality"""
sigma = start_sigma_dut(dev[0].ifname)
res = sigma_dut_cmd("UNKNOWN")
if "status,INVALID,errorCode,Unknown command" not in res:
raise Exception("Unexpected sigma_dut response to unknown command")
tests = [ ("ca_get_version", "status,COMPLETE,version,1.0"),
("device_get_info", "status,COMPLETE,vendor"),
("device_list_interfaces,interfaceType,foo", "status,ERROR"),
("device_list_interfaces,interfaceType,802.11",
"status,COMPLETE,interfaceType,802.11,interfaceID," + dev[0].ifname) ]
for cmd, response in tests:
res = sigma_dut_cmd(cmd)
if response not in res:
raise Exception("Unexpected %s response: %s" % (cmd, res))
stop_sigma_dut(sigma)
def test_sigma_dut_open(dev, apdev):
"""sigma_dut controlled open network association"""
try:
run_sigma_dut_open(dev, apdev)
finally:
dev[0].set("ignore_old_scan_res", "0")
def run_sigma_dut_open(dev, apdev):
ifname = dev[0].ifname
sigma = start_sigma_dut(ifname)
hapd = hostapd.add_ap(apdev[0], { "ssid": "open" })
sigma_dut_cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
sigma_dut_cmd_check("sta_set_encryption,interface,%s,ssid,%s,encpType,none" % (ifname, "open"))
sigma_dut_cmd_check("sta_associate,interface,%s,ssid,%s" % (ifname, "open"))
sigma_dut_wait_connected(ifname)
sigma_dut_cmd_check("sta_get_ip_config,interface," + ifname)
sigma_dut_cmd_check("sta_disconnect,interface," + ifname)
sigma_dut_cmd_check("sta_reset_default,interface," + ifname)
stop_sigma_dut(sigma)
def test_sigma_dut_psk_pmf(dev, apdev):
"""sigma_dut controlled PSK+PMF association"""
try:
run_sigma_dut_psk_pmf(dev, apdev)
finally:
dev[0].set("ignore_old_scan_res", "0")
def run_sigma_dut_psk_pmf(dev, apdev):
ifname = dev[0].ifname
sigma = start_sigma_dut(ifname)
ssid = "test-pmf-required"
params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
params["wpa_key_mgmt"] = "WPA-PSK-SHA256"
params["ieee80211w"] = "2"
hapd = hostapd.add_ap(apdev[0], params)
sigma_dut_cmd_check("sta_reset_default,interface,%s,prog,PMF" % ifname)
sigma_dut_cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
sigma_dut_cmd_check("sta_set_psk,interface,%s,ssid,%s,passphrase,%s,encpType,aes-ccmp,keymgmttype,wpa2,PMF,Required" % (ifname, "test-pmf-required", "12345678"))
sigma_dut_cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "test-pmf-required"))
sigma_dut_wait_connected(ifname)
sigma_dut_cmd_check("sta_get_ip_config,interface," + ifname)
sigma_dut_cmd_check("sta_disconnect,interface," + ifname)
sigma_dut_cmd_check("sta_reset_default,interface," + ifname)
stop_sigma_dut(sigma)
def test_sigma_dut_psk_pmf_bip_cmac_128(dev, apdev):
"""sigma_dut controlled PSK+PMF association with BIP-CMAC-128"""
try:
run_sigma_dut_psk_pmf_cipher(dev, apdev, "BIP-CMAC-128", "AES-128-CMAC")
finally:
dev[0].set("ignore_old_scan_res", "0")
def test_sigma_dut_psk_pmf_bip_cmac_256(dev, apdev):
"""sigma_dut controlled PSK+PMF association with BIP-CMAC-256"""
try:
run_sigma_dut_psk_pmf_cipher(dev, apdev, "BIP-CMAC-256", "BIP-CMAC-256")
finally:
dev[0].set("ignore_old_scan_res", "0")
def test_sigma_dut_psk_pmf_bip_gmac_128(dev, apdev):
"""sigma_dut controlled PSK+PMF association with BIP-GMAC-128"""
try:
run_sigma_dut_psk_pmf_cipher(dev, apdev, "BIP-GMAC-128", "BIP-GMAC-128")
finally:
dev[0].set("ignore_old_scan_res", "0")
def test_sigma_dut_psk_pmf_bip_gmac_256(dev, apdev):
"""sigma_dut controlled PSK+PMF association with BIP-GMAC-256"""
try:
run_sigma_dut_psk_pmf_cipher(dev, apdev, "BIP-GMAC-256", "BIP-GMAC-256")
finally:
dev[0].set("ignore_old_scan_res", "0")
def test_sigma_dut_psk_pmf_bip_gmac_256_mismatch(dev, apdev):
"""sigma_dut controlled PSK+PMF association with BIP-GMAC-256 mismatch"""
try:
run_sigma_dut_psk_pmf_cipher(dev, apdev, "BIP-GMAC-256", "AES-128-CMAC",
failure=True)
finally:
dev[0].set("ignore_old_scan_res", "0")
def run_sigma_dut_psk_pmf_cipher(dev, apdev, sigma_cipher, hostapd_cipher,
failure=False):
ifname = dev[0].ifname
sigma = start_sigma_dut(ifname)
ssid = "test-pmf-required"
params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
params["wpa_key_mgmt"] = "WPA-PSK-SHA256"
params["ieee80211w"] = "2"
params["group_mgmt_cipher"] = hostapd_cipher
hapd = hostapd.add_ap(apdev[0], params)
sigma_dut_cmd_check("sta_reset_default,interface,%s,prog,PMF" % ifname)
sigma_dut_cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
sigma_dut_cmd_check("sta_set_psk,interface,%s,ssid,%s,passphrase,%s,encpType,aes-ccmp,keymgmttype,wpa2,PMF,Required,GroupMgntCipher,%s" % (ifname, "test-pmf-required", "12345678", sigma_cipher))
sigma_dut_cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "test-pmf-required"))
if failure:
ev = dev[0].wait_event(["CTRL-EVENT-NETWORK-NOT-FOUND",
"CTRL-EVENT-CONNECTED"], timeout=10)
if ev is None:
raise Exception("Network selection result not indicated")
if "CTRL-EVENT-CONNECTED" in ev:
raise Exception("Unexpected connection")
res = sigma_dut_cmd("sta_is_connected,interface," + ifname)
if "connected,1" in res:
raise Exception("Connection reported")
else:
sigma_dut_wait_connected(ifname)
sigma_dut_cmd_check("sta_get_ip_config,interface," + ifname)
sigma_dut_cmd_check("sta_disconnect,interface," + ifname)
sigma_dut_cmd_check("sta_reset_default,interface," + ifname)
stop_sigma_dut(sigma)
def test_sigma_dut_sae(dev, apdev):
"""sigma_dut controlled SAE association"""
if "SAE" not in dev[0].get_capability("auth_alg"):
raise HwsimSkip("SAE not supported")
ifname = dev[0].ifname
sigma = start_sigma_dut(ifname)
ssid = "test-sae"
params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
params['wpa_key_mgmt'] = 'SAE'
params["ieee80211w"] = "2"
hapd = hostapd.add_ap(apdev[0], params)
sigma_dut_cmd_check("sta_reset_default,interface,%s" % ifname)
sigma_dut_cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
sigma_dut_cmd_check("sta_set_security,interface,%s,ssid,%s,passphrase,%s,type,SAE,encpType,aes-ccmp,keymgmttype,wpa2" % (ifname, "test-sae", "12345678"))
sigma_dut_cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "test-sae"))
sigma_dut_wait_connected(ifname)
sigma_dut_cmd_check("sta_get_ip_config,interface," + ifname)
if dev[0].get_status_field('sae_group') != '19':
raise Exception("Expected default SAE group not used")
sigma_dut_cmd_check("sta_disconnect,interface," + ifname)
sigma_dut_cmd_check("sta_reset_default,interface," + ifname)
sigma_dut_cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
sigma_dut_cmd_check("sta_set_security,interface,%s,ssid,%s,passphrase,%s,type,SAE,encpType,aes-ccmp,keymgmttype,wpa2,ECGroupID,20" % (ifname, "test-sae", "12345678"))
sigma_dut_cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "test-sae"))
sigma_dut_wait_connected(ifname)
sigma_dut_cmd_check("sta_get_ip_config,interface," + ifname)
if dev[0].get_status_field('sae_group') != '20':
raise Exception("Expected SAE group not used")
sigma_dut_cmd_check("sta_disconnect,interface," + ifname)
sigma_dut_cmd_check("sta_reset_default,interface," + ifname)
stop_sigma_dut(sigma)
def test_sigma_dut_sae_password(dev, apdev):
"""sigma_dut controlled SAE association and long password"""
if "SAE" not in dev[0].get_capability("auth_alg"):
raise HwsimSkip("SAE not supported")
ifname = dev[0].ifname
sigma = start_sigma_dut(ifname)
try:
ssid = "test-sae"
params = hostapd.wpa2_params(ssid=ssid)
params['sae_password'] = 100*'B'
params['wpa_key_mgmt'] = 'SAE'
params["ieee80211w"] = "2"
hapd = hostapd.add_ap(apdev[0], params)
sigma_dut_cmd_check("sta_reset_default,interface,%s" % ifname)
sigma_dut_cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
sigma_dut_cmd_check("sta_set_security,interface,%s,ssid,%s,passphrase,%s,type,SAE,encpType,aes-ccmp,keymgmttype,wpa2" % (ifname, "test-sae", 100*'B'))
sigma_dut_cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "test-sae"))
sigma_dut_wait_connected(ifname)
sigma_dut_cmd_check("sta_get_ip_config,interface," + ifname)
sigma_dut_cmd_check("sta_disconnect,interface," + ifname)
sigma_dut_cmd_check("sta_reset_default,interface," + ifname)
finally:
stop_sigma_dut(sigma)
def test_sigma_dut_sta_override_rsne(dev, apdev):
"""sigma_dut and RSNE override on STA"""
try:
run_sigma_dut_sta_override_rsne(dev, apdev)
finally:
dev[0].set("ignore_old_scan_res", "0")
def run_sigma_dut_sta_override_rsne(dev, apdev):
ifname = dev[0].ifname
sigma = start_sigma_dut(ifname)
ssid = "test-psk"
params = hostapd.wpa2_params(ssid=ssid, passphrase="12345678")
hapd = hostapd.add_ap(apdev[0], params)
sigma_dut_cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
tests = [ "30120100000fac040100000fac040100000fac02",
"30140100000fac040100000fac040100000fac02ffff" ]
for test in tests:
sigma_dut_cmd_check("sta_set_security,interface,%s,ssid,%s,type,PSK,passphrase,%s,EncpType,aes-ccmp,KeyMgmtType,wpa2" % (ifname, "test-psk", "12345678"))
sigma_dut_cmd_check("dev_configure_ie,interface,%s,IE_Name,RSNE,Contents,%s" % (ifname, test))
sigma_dut_cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "test-psk"))
sigma_dut_wait_connected(ifname)
sigma_dut_cmd_check("sta_disconnect,interface," + ifname)
dev[0].dump_monitor()
sigma_dut_cmd_check("sta_set_security,interface,%s,ssid,%s,type,PSK,passphrase,%s,EncpType,aes-ccmp,KeyMgmtType,wpa2" % (ifname, "test-psk", "12345678"))
sigma_dut_cmd_check("dev_configure_ie,interface,%s,IE_Name,RSNE,Contents,300101" % ifname)
sigma_dut_cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "test-psk"))
ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT"])
if ev is None:
raise Exception("Association rejection not reported")
if "status_code=40" not in ev:
raise Exception("Unexpected status code: " + ev)
sigma_dut_cmd_check("sta_reset_default,interface," + ifname)
stop_sigma_dut(sigma)
def test_sigma_dut_ap_psk(dev, apdev):
"""sigma_dut controlled AP"""
with HWSimRadio() as (radio, iface):
sigma = start_sigma_dut(iface)
try:
sigma_dut_cmd_check("ap_reset_default")
sigma_dut_cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-psk,MODE,11ng")
sigma_dut_cmd_check("ap_set_security,NAME,AP,KEYMGNT,WPA2-PSK,PSK,12345678")
sigma_dut_cmd_check("ap_config_commit,NAME,AP")
dev[0].connect("test-psk", psk="12345678", scan_freq="2412")
sigma_dut_cmd_check("ap_reset_default")
finally:
stop_sigma_dut(sigma)
def test_sigma_dut_ap_pskhex(dev, apdev, params):
"""sigma_dut controlled AP and PSKHEX"""
logdir = os.path.join(params['logdir'],
"sigma_dut_ap_pskhex.sigma-hostapd")
with HWSimRadio() as (radio, iface):
sigma = start_sigma_dut(iface, hostapd_logdir=logdir)
try:
psk = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
sigma_dut_cmd_check("ap_reset_default")
sigma_dut_cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-psk,MODE,11ng")
sigma_dut_cmd_check("ap_set_security,NAME,AP,KEYMGNT,WPA2-PSK,PSKHEX," + psk)
sigma_dut_cmd_check("ap_config_commit,NAME,AP")
dev[0].connect("test-psk", raw_psk=psk, scan_freq="2412")
sigma_dut_cmd_check("ap_reset_default")
finally:
stop_sigma_dut(sigma)
def test_sigma_dut_suite_b(dev, apdev, params):
"""sigma_dut controlled STA Suite B"""
check_suite_b_192_capa(dev)
logdir = params['logdir']
with open("auth_serv/ec2-ca.pem", "r") as f:
with open(os.path.join(logdir, "suite_b_ca.pem"), "w") as f2:
f2.write(f.read())
with open("auth_serv/ec2-user.pem", "r") as f:
with open("auth_serv/ec2-user.key", "r") as f2:
with open(os.path.join(logdir, "suite_b.pem"), "w") as f3:
f3.write(f.read())
f3.write(f2.read())
dev[0].flush_scan_cache()
params = suite_b_as_params()
params['ca_cert'] = 'auth_serv/ec2-ca.pem'
params['server_cert'] = 'auth_serv/ec2-server.pem'
params['private_key'] = 'auth_serv/ec2-server.key'
params['openssl_ciphers'] = 'SUITEB192'
hostapd.add_ap(apdev[1], params)
params = { "ssid": "test-suite-b",
"wpa": "2",
"wpa_key_mgmt": "WPA-EAP-SUITE-B-192",
"rsn_pairwise": "GCMP-256",
"group_mgmt_cipher": "BIP-GMAC-256",
"ieee80211w": "2",
"ieee8021x": "1",
'auth_server_addr': "127.0.0.1",
'auth_server_port': "18129",
'auth_server_shared_secret': "radius",
'nas_identifier': "nas.w1.fi" }
hapd = hostapd.add_ap(apdev[0], params)
ifname = dev[0].ifname
sigma = start_sigma_dut(ifname, cert_path=logdir)
sigma_dut_cmd_check("sta_reset_default,interface,%s,prog,PMF" % ifname)
sigma_dut_cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
sigma_dut_cmd_check("sta_set_security,type,eaptls,interface,%s,ssid,%s,PairwiseCipher,AES-GCMP-256,GroupCipher,AES-GCMP-256,GroupMgntCipher,BIP-GMAC-256,keymgmttype,SuiteB,clientCertificate,suite_b.pem,trustedRootCA,suite_b_ca.pem,CertType,ECC" % (ifname, "test-suite-b"))
sigma_dut_cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "test-suite-b"))
sigma_dut_wait_connected(ifname)
sigma_dut_cmd_check("sta_get_ip_config,interface," + ifname)
sigma_dut_cmd_check("sta_disconnect,interface," + ifname)
sigma_dut_cmd_check("sta_reset_default,interface," + ifname)
stop_sigma_dut(sigma)
def test_sigma_dut_suite_b_rsa(dev, apdev, params):
"""sigma_dut controlled STA Suite B (RSA)"""
check_suite_b_192_capa(dev)
logdir = params['logdir']
with open("auth_serv/rsa3072-ca.pem", "r") as f:
with open(os.path.join(logdir, "suite_b_ca_rsa.pem"), "w") as f2:
f2.write(f.read())
with open("auth_serv/rsa3072-user.pem", "r") as f:
with open("auth_serv/rsa3072-user.key", "r") as f2:
with open(os.path.join(logdir, "suite_b_rsa.pem"), "w") as f3:
f3.write(f.read())
f3.write(f2.read())
dev[0].flush_scan_cache()
params = suite_b_192_rsa_ap_params()
hapd = hostapd.add_ap(apdev[0], params)
ifname = dev[0].ifname
sigma = start_sigma_dut(ifname, cert_path=logdir)
cmd = "sta_set_security,type,eaptls,interface,%s,ssid,%s,PairwiseCipher,AES-GCMP-256,GroupCipher,AES-GCMP-256,GroupMgntCipher,BIP-GMAC-256,keymgmttype,SuiteB,clientCertificate,suite_b_rsa.pem,trustedRootCA,suite_b_ca_rsa.pem,CertType,RSA" % (ifname, "test-suite-b")
tests = [ "",
",TLSCipher,TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
",TLSCipher,TLS_DHE_RSA_WITH_AES_256_GCM_SHA384" ]
for extra in tests:
sigma_dut_cmd_check("sta_reset_default,interface,%s,prog,PMF" % ifname)
sigma_dut_cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
sigma_dut_cmd_check(cmd + extra)
sigma_dut_cmd_check("sta_associate,interface,%s,ssid,%s,channel,1" % (ifname, "test-suite-b"))
sigma_dut_wait_connected(ifname)
sigma_dut_cmd_check("sta_get_ip_config,interface," + ifname)
sigma_dut_cmd_check("sta_disconnect,interface," + ifname)
sigma_dut_cmd_check("sta_reset_default,interface," + ifname)
stop_sigma_dut(sigma)
def test_sigma_dut_ap_suite_b(dev, apdev, params):
"""sigma_dut controlled AP Suite B"""
check_suite_b_192_capa(dev)
logdir = os.path.join(params['logdir'],
"sigma_dut_ap_suite_b.sigma-hostapd")
params = suite_b_as_params()
params['ca_cert'] = 'auth_serv/ec2-ca.pem'
params['server_cert'] = 'auth_serv/ec2-server.pem'
params['private_key'] = 'auth_serv/ec2-server.key'
params['openssl_ciphers'] = 'SUITEB192'
hostapd.add_ap(apdev[1], params)
with HWSimRadio() as (radio, iface):
sigma = start_sigma_dut(iface, hostapd_logdir=logdir)
try:
sigma_dut_cmd_check("ap_reset_default")
sigma_dut_cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-suite-b,MODE,11ng")
sigma_dut_cmd_check("ap_set_radius,NAME,AP,IPADDR,127.0.0.1,PORT,18129,PASSWORD,radius")
sigma_dut_cmd_check("ap_set_security,NAME,AP,KEYMGNT,SuiteB")
sigma_dut_cmd_check("ap_config_commit,NAME,AP")
dev[0].connect("test-suite-b", key_mgmt="WPA-EAP-SUITE-B-192",
ieee80211w="2",
openssl_ciphers="SUITEB192",
eap="TLS", identity="tls user",
ca_cert="auth_serv/ec2-ca.pem",
client_cert="auth_serv/ec2-user.pem",
private_key="auth_serv/ec2-user.key",
pairwise="GCMP-256", group="GCMP-256",
scan_freq="2412")
sigma_dut_cmd_check("ap_reset_default")
finally:
stop_sigma_dut(sigma)
def test_sigma_dut_ap_cipher_gcmp_128(dev, apdev, params):
"""sigma_dut controlled AP with GCMP-128/BIP-GMAC-128 cipher"""
run_sigma_dut_ap_cipher(dev, apdev, params, "AES-GCMP-128", "BIP-GMAC-128",
"GCMP")
def test_sigma_dut_ap_cipher_gcmp_256(dev, apdev, params):
"""sigma_dut controlled AP with GCMP-256/BIP-GMAC-256 cipher"""
run_sigma_dut_ap_cipher(dev, apdev, params, "AES-GCMP-256", "BIP-GMAC-256",
"GCMP-256")
def test_sigma_dut_ap_cipher_ccmp_128(dev, apdev, params):
"""sigma_dut controlled AP with CCMP-128/BIP-CMAC-128 cipher"""
run_sigma_dut_ap_cipher(dev, apdev, params, "AES-CCMP-128", "BIP-CMAC-128",
"CCMP")
def test_sigma_dut_ap_cipher_ccmp_256(dev, apdev, params):
"""sigma_dut controlled AP with CCMP-256/BIP-CMAC-256 cipher"""
run_sigma_dut_ap_cipher(dev, apdev, params, "AES-CCMP-256", "BIP-CMAC-256",
"CCMP-256")
def test_sigma_dut_ap_cipher_ccmp_gcmp_1(dev, apdev, params):
"""sigma_dut controlled AP with CCMP-128+GCMP-256 ciphers (1)"""
run_sigma_dut_ap_cipher(dev, apdev, params, "AES-CCMP-128 AES-GCMP-256",
"BIP-GMAC-256", "CCMP")
def test_sigma_dut_ap_cipher_ccmp_gcmp_2(dev, apdev, params):
"""sigma_dut controlled AP with CCMP-128+GCMP-256 ciphers (2)"""
run_sigma_dut_ap_cipher(dev, apdev, params, "AES-CCMP-128 AES-GCMP-256",
"BIP-GMAC-256", "GCMP-256", "CCMP")
def test_sigma_dut_ap_cipher_gcmp_256_group_ccmp(dev, apdev, params):
"""sigma_dut controlled AP with GCMP-256/CCMP/BIP-GMAC-256 cipher"""
run_sigma_dut_ap_cipher(dev, apdev, params, "AES-GCMP-256", "BIP-GMAC-256",
"GCMP-256", "CCMP", "AES-CCMP-128")
def run_sigma_dut_ap_cipher(dev, apdev, params, ap_pairwise, ap_group_mgmt,
sta_cipher, sta_cipher_group=None, ap_group=None):
check_suite_b_192_capa(dev)
logdir = os.path.join(params['logdir'],
"sigma_dut_ap_cipher.sigma-hostapd")
params = suite_b_as_params()
params['ca_cert'] = 'auth_serv/ec2-ca.pem'
params['server_cert'] = 'auth_serv/ec2-server.pem'
params['private_key'] = 'auth_serv/ec2-server.key'
params['openssl_ciphers'] = 'SUITEB192'
hostapd.add_ap(apdev[1], params)
with HWSimRadio() as (radio, iface):
sigma = start_sigma_dut(iface, hostapd_logdir=logdir)
try:
sigma_dut_cmd_check("ap_reset_default")
sigma_dut_cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-suite-b,MODE,11ng")
sigma_dut_cmd_check("ap_set_radius,NAME,AP,IPADDR,127.0.0.1,PORT,18129,PASSWORD,radius")
cmd = "ap_set_security,NAME,AP,KEYMGNT,SuiteB,PMF,Required,PairwiseCipher,%s,GroupMgntCipher,%s" % (ap_pairwise, ap_group_mgmt)
if ap_group:
cmd += ",GroupCipher,%s" % ap_group
sigma_dut_cmd_check(cmd)
sigma_dut_cmd_check("ap_config_commit,NAME,AP")
if sta_cipher_group is None:
sta_cipher_group = sta_cipher
dev[0].connect("test-suite-b", key_mgmt="WPA-EAP-SUITE-B-192",
ieee80211w="2",
openssl_ciphers="SUITEB192",
eap="TLS", identity="tls user",
ca_cert="auth_serv/ec2-ca.pem",
client_cert="auth_serv/ec2-user.pem",
private_key="auth_serv/ec2-user.key",
pairwise=sta_cipher, group=sta_cipher_group,
scan_freq="2412")
sigma_dut_cmd_check("ap_reset_default")
finally:
stop_sigma_dut(sigma)
def test_sigma_dut_ap_override_rsne(dev, apdev):
"""sigma_dut controlled AP overriding RSNE"""
with HWSimRadio() as (radio, iface):
sigma = start_sigma_dut(iface)
try:
sigma_dut_cmd_check("ap_reset_default")
sigma_dut_cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-psk,MODE,11ng")
sigma_dut_cmd_check("ap_set_security,NAME,AP,KEYMGNT,WPA2-PSK,PSK,12345678")
sigma_dut_cmd_check("dev_configure_ie,NAME,AP,interface,%s,IE_Name,RSNE,Contents,30180100000fac040200ffffffff000fac040100000fac020c00" % iface)
sigma_dut_cmd_check("ap_config_commit,NAME,AP")
dev[0].connect("test-psk", psk="12345678", scan_freq="2412")
sigma_dut_cmd_check("ap_reset_default")
finally:
stop_sigma_dut(sigma)
def test_sigma_dut_ap_sae(dev, apdev, params):
"""sigma_dut controlled AP with SAE"""
logdir = os.path.join(params['logdir'],
"sigma_dut_ap_sae.sigma-hostapd")
if "SAE" not in dev[0].get_capability("auth_alg"):
raise HwsimSkip("SAE not supported")
with HWSimRadio() as (radio, iface):
sigma = start_sigma_dut(iface, hostapd_logdir=logdir)
try:
sigma_dut_cmd_check("ap_reset_default")
sigma_dut_cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-sae,MODE,11ng")
sigma_dut_cmd_check("ap_set_security,NAME,AP,KEYMGNT,WPA2-SAE,PSK,12345678")
sigma_dut_cmd_check("ap_config_commit,NAME,AP")
dev[0].request("SET sae_groups ")
dev[0].connect("test-sae", key_mgmt="SAE", psk="12345678",
ieee80211w="2", scan_freq="2412")
if dev[0].get_status_field('sae_group') != '19':
raise Exception("Expected default SAE group not used")
sigma_dut_cmd_check("ap_reset_default")
finally:
stop_sigma_dut(sigma)
def test_sigma_dut_ap_sae_password(dev, apdev, params):
"""sigma_dut controlled AP with SAE and long password"""
logdir = os.path.join(params['logdir'],
"sigma_dut_ap_sae_password.sigma-hostapd")
if "SAE" not in dev[0].get_capability("auth_alg"):
raise HwsimSkip("SAE not supported")
with HWSimRadio() as (radio, iface):
sigma = start_sigma_dut(iface, hostapd_logdir=logdir)
try:
sigma_dut_cmd_check("ap_reset_default")
sigma_dut_cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-sae,MODE,11ng")
sigma_dut_cmd_check("ap_set_security,NAME,AP,KEYMGNT,WPA2-SAE,PSK," + 100*'C')
sigma_dut_cmd_check("ap_config_commit,NAME,AP")
dev[0].request("SET sae_groups ")
dev[0].connect("test-sae", key_mgmt="SAE", sae_password=100*'C',
ieee80211w="2", scan_freq="2412")
if dev[0].get_status_field('sae_group') != '19':
raise Exception("Expected default SAE group not used")
sigma_dut_cmd_check("ap_reset_default")
finally:
stop_sigma_dut(sigma)
def test_sigma_dut_ap_sae_group(dev, apdev, params):
"""sigma_dut controlled AP with SAE and specific group"""
logdir = os.path.join(params['logdir'],
"sigma_dut_ap_sae_group.sigma-hostapd")
if "SAE" not in dev[0].get_capability("auth_alg"):
raise HwsimSkip("SAE not supported")
with HWSimRadio() as (radio, iface):
sigma = start_sigma_dut(iface, hostapd_logdir=logdir)
try:
sigma_dut_cmd_check("ap_reset_default")
sigma_dut_cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-sae,MODE,11ng")
sigma_dut_cmd_check("ap_set_security,NAME,AP,KEYMGNT,WPA2-SAE,PSK,12345678,ECGroupID,20")
sigma_dut_cmd_check("ap_config_commit,NAME,AP")
dev[0].request("SET sae_groups ")
dev[0].connect("test-sae", key_mgmt="SAE", psk="12345678",
ieee80211w="2", scan_freq="2412")
if dev[0].get_status_field('sae_group') != '20':
raise Exception("Expected SAE group not used")
sigma_dut_cmd_check("ap_reset_default")
finally:
stop_sigma_dut(sigma)
def test_sigma_dut_ap_psk_sae(dev, apdev, params):
"""sigma_dut controlled AP with PSK+SAE"""
if "SAE" not in dev[0].get_capability("auth_alg"):
raise HwsimSkip("SAE not supported")
logdir = os.path.join(params['logdir'],
"sigma_dut_ap_psk_sae.sigma-hostapd")
with HWSimRadio() as (radio, iface):
sigma = start_sigma_dut(iface, hostapd_logdir=logdir)
try:
sigma_dut_cmd_check("ap_reset_default")
sigma_dut_cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,test-sae,MODE,11ng")
sigma_dut_cmd_check("ap_set_security,NAME,AP,KEYMGNT,WPA2-PSK-SAE,PSK,12345678")
sigma_dut_cmd_check("ap_config_commit,NAME,AP")
dev[2].request("SET sae_groups ")
dev[2].connect("test-sae", key_mgmt="SAE", psk="12345678",
scan_freq="2412", ieee80211w="0", wait_connect=False)
dev[0].request("SET sae_groups ")
dev[0].connect("test-sae", key_mgmt="SAE", psk="12345678",
scan_freq="2412", ieee80211w="2")
dev[1].connect("test-sae", psk="12345678", scan_freq="2412")
ev = dev[2].wait_event(["CTRL-EVENT-CONNECTED"], timeout=0.1)
dev[2].request("DISCONNECT")
if ev is not None:
raise Exception("Unexpected connection without PMF")
sigma_dut_cmd_check("ap_reset_default")
finally:
stop_sigma_dut(sigma)
def test_sigma_dut_owe(dev, apdev):
"""sigma_dut controlled OWE station"""
try:
run_sigma_dut_owe(dev, apdev)
finally:
dev[0].set("ignore_old_scan_res", "0")
def run_sigma_dut_owe(dev, apdev):
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
ifname = dev[0].ifname
sigma = start_sigma_dut(ifname)
try:
params = { "ssid": "owe",
"wpa": "2",
"wpa_key_mgmt": "OWE",
"ieee80211w": "2",
"rsn_pairwise": "CCMP" }
hapd = hostapd.add_ap(apdev[0], params)
bssid = hapd.own_addr()
sigma_dut_cmd_check("sta_reset_default,interface,%s,prog,WPA3" % ifname)
sigma_dut_cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
sigma_dut_cmd_check("sta_set_security,interface,%s,ssid,owe,Type,OWE" % ifname)
sigma_dut_cmd_check("sta_associate,interface,%s,ssid,owe,channel,1" % ifname)
sigma_dut_wait_connected(ifname)
sigma_dut_cmd_check("sta_get_ip_config,interface," + ifname)
dev[0].dump_monitor()
sigma_dut_cmd("sta_reassoc,interface,%s,Channel,1,bssid,%s" % (ifname, bssid))
dev[0].wait_connected()
sigma_dut_cmd_check("sta_disconnect,interface," + ifname)
dev[0].wait_disconnected()
dev[0].dump_monitor()
sigma_dut_cmd_check("sta_reset_default,interface,%s,prog,WPA3" % ifname)
sigma_dut_cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
sigma_dut_cmd_check("sta_set_security,interface,%s,ssid,owe,Type,OWE,ECGroupID,20" % ifname)
sigma_dut_cmd_check("sta_associate,interface,%s,ssid,owe,channel,1" % ifname)
sigma_dut_wait_connected(ifname)
sigma_dut_cmd_check("sta_get_ip_config,interface," + ifname)
sigma_dut_cmd_check("sta_disconnect,interface," + ifname)
dev[0].wait_disconnected()
dev[0].dump_monitor()
sigma_dut_cmd_check("sta_reset_default,interface,%s,prog,WPA3" % ifname)
sigma_dut_cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
sigma_dut_cmd_check("sta_set_security,interface,%s,ssid,owe,Type,OWE,ECGroupID,0" % ifname)
sigma_dut_cmd_check("sta_associate,interface,%s,ssid,owe,channel,1" % ifname)
ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT"], timeout=10)
sigma_dut_cmd_check("sta_disconnect,interface," + ifname)
if ev is None:
raise Exception("Association not rejected")
if "status_code=77" not in ev:
raise Exception("Unexpected rejection reason: " + ev)
sigma_dut_cmd_check("sta_reset_default,interface," + ifname)
finally:
stop_sigma_dut(sigma)
def test_sigma_dut_ap_owe(dev, apdev, params):
"""sigma_dut controlled AP with OWE"""
logdir = os.path.join(params['logdir'],
"sigma_dut_ap_owe.sigma-hostapd")
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
with HWSimRadio() as (radio, iface):
sigma = start_sigma_dut(iface, hostapd_logdir=logdir)
try:
sigma_dut_cmd_check("ap_reset_default,NAME,AP,Program,WPA3")
sigma_dut_cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,owe,MODE,11ng")
sigma_dut_cmd_check("ap_set_security,NAME,AP,KEYMGNT,OWE")
sigma_dut_cmd_check("ap_config_commit,NAME,AP")
dev[0].connect("owe", key_mgmt="OWE", ieee80211w="2",
scan_freq="2412")
sigma_dut_cmd_check("ap_reset_default")
finally:
stop_sigma_dut(sigma)
def test_sigma_dut_ap_owe_ecgroupid(dev, apdev):
"""sigma_dut controlled AP with OWE and ECGroupID"""
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
with HWSimRadio() as (radio, iface):
sigma = start_sigma_dut(iface)
try:
sigma_dut_cmd_check("ap_reset_default,NAME,AP,Program,WPA3")
sigma_dut_cmd_check("ap_set_wireless,NAME,AP,CHANNEL,1,SSID,owe,MODE,11ng")
sigma_dut_cmd_check("ap_set_security,NAME,AP,KEYMGNT,OWE,ECGroupID,20 21,PMF,Required")
sigma_dut_cmd_check("ap_config_commit,NAME,AP")
dev[0].connect("owe", key_mgmt="OWE", ieee80211w="2",
owe_group="20", scan_freq="2412")
dev[0].request("REMOVE_NETWORK all")
dev[0].wait_disconnected()
dev[0].connect("owe", key_mgmt="OWE", ieee80211w="2",
owe_group="21", scan_freq="2412")
dev[0].request("REMOVE_NETWORK all")
dev[0].wait_disconnected()
dev[0].connect("owe", key_mgmt="OWE", ieee80211w="2",
owe_group="19", scan_freq="2412", wait_connect=False)
ev = dev[0].wait_event(["CTRL-EVENT-ASSOC-REJECT"], timeout=10)
dev[0].request("DISCONNECT")
if ev is None:
raise Exception("Association not rejected")
if "status_code=77" not in ev:
raise Exception("Unexpected rejection reason: " + ev)
dev[0].dump_monitor()
sigma_dut_cmd_check("ap_reset_default")
finally:
stop_sigma_dut(sigma)
def test_sigma_dut_ap_owe_transition_mode(dev, apdev, params):
"""sigma_dut controlled AP with OWE and transition mode"""
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
logdir = os.path.join(params['logdir'],
"sigma_dut_ap_owe_transition_mode.sigma-hostapd")
with HWSimRadio() as (radio, iface):
sigma = start_sigma_dut(iface, hostapd_logdir=logdir)
try:
sigma_dut_cmd_check("ap_reset_default,NAME,AP,Program,WPA3")
sigma_dut_cmd_check("ap_set_wireless,NAME,AP,WLAN_TAG,1,CHANNEL,1,SSID,owe,MODE,11ng")
sigma_dut_cmd_check("ap_set_security,NAME,AP,WLAN_TAG,1,KEYMGNT,OWE")
sigma_dut_cmd_check("ap_set_wireless,NAME,AP,WLAN_TAG,2,CHANNEL,1,SSID,owe,MODE,11ng")
sigma_dut_cmd_check("ap_set_security,NAME,AP,WLAN_TAG,2,KEYMGNT,NONE")
sigma_dut_cmd_check("ap_config_commit,NAME,AP")
res1 = sigma_dut_cmd_check("ap_get_mac_address,NAME,AP,WLAN_TAG,1,Interface,24G")
res2 = sigma_dut_cmd_check("ap_get_mac_address,NAME,AP,WLAN_TAG,2,Interface,24G")
dev[0].connect("owe", key_mgmt="OWE", ieee80211w="2",
scan_freq="2412")
dev[1].connect("owe", key_mgmt="NONE", scan_freq="2412")
if dev[0].get_status_field('bssid') not in res1:
raise Exception("Unexpected ap_get_mac_address WLAN_TAG,1: " + res1)
if dev[1].get_status_field('bssid') not in res2:
raise Exception("Unexpected ap_get_mac_address WLAN_TAG,2: " + res2)
sigma_dut_cmd_check("ap_reset_default")
finally:
stop_sigma_dut(sigma)
def test_sigma_dut_ap_owe_transition_mode_2(dev, apdev, params):
"""sigma_dut controlled AP with OWE and transition mode (2)"""
if "OWE" not in dev[0].get_capability("key_mgmt"):
raise HwsimSkip("OWE not supported")
logdir = os.path.join(params['logdir'],
"sigma_dut_ap_owe_transition_mode_2.sigma-hostapd")
with HWSimRadio() as (radio, iface):
sigma = start_sigma_dut(iface, hostapd_logdir=logdir)
try:
sigma_dut_cmd_check("ap_reset_default,NAME,AP,Program,WPA3")
sigma_dut_cmd_check("ap_set_wireless,NAME,AP,WLAN_TAG,1,CHANNEL,1,SSID,owe,MODE,11ng")
sigma_dut_cmd_check("ap_set_security,NAME,AP,WLAN_TAG,1,KEYMGNT,NONE")
sigma_dut_cmd_check("ap_set_wireless,NAME,AP,WLAN_TAG,2,CHANNEL,1,MODE,11ng")
sigma_dut_cmd_check("ap_set_security,NAME,AP,WLAN_TAG,2,KEYMGNT,OWE")
sigma_dut_cmd_check("ap_config_commit,NAME,AP")
res1 = sigma_dut_cmd_check("ap_get_mac_address,NAME,AP,WLAN_TAG,1,Interface,24G")
res2 = sigma_dut_cmd_check("ap_get_mac_address,NAME,AP,WLAN_TAG,2,Interface,24G")
dev[0].connect("owe", key_mgmt="OWE", ieee80211w="2",
scan_freq="2412")
dev[1].connect("owe", key_mgmt="NONE", scan_freq="2412")
if dev[0].get_status_field('bssid') not in res2:
raise Exception("Unexpected ap_get_mac_address WLAN_TAG,2: " + res1)
if dev[1].get_status_field('bssid') not in res1:
raise Exception("Unexpected ap_get_mac_address WLAN_TAG,1: " + res2)
sigma_dut_cmd_check("ap_reset_default")
finally:
stop_sigma_dut(sigma)
def dpp_init_enrollee(dev, id1):
logger.info("Starting DPP initiator/enrollee in a thread")
time.sleep(1)
cmd = "DPP_AUTH_INIT peer=%d role=enrollee" % id1
if "OK" not in dev.request(cmd):
raise Exception("Failed to initiate DPP Authentication")
ev = dev.wait_event(["DPP-CONF-RECEIVED"], timeout=5)
if ev is None:
raise Exception("DPP configuration not completed (Enrollee)")
logger.info("DPP initiator/enrollee done")
def test_sigma_dut_dpp_qr_resp_1(dev, apdev):
"""sigma_dut DPP/QR responder (conf index 1)"""
run_sigma_dut_dpp_qr_resp(dev, apdev, 1)
def test_sigma_dut_dpp_qr_resp_2(dev, apdev):
"""sigma_dut DPP/QR responder (conf index 2)"""
run_sigma_dut_dpp_qr_resp(dev, apdev, 2)
def test_sigma_dut_dpp_qr_resp_3(dev, apdev):
"""sigma_dut DPP/QR responder (conf index 3)"""
run_sigma_dut_dpp_qr_resp(dev, apdev, 3)
def test_sigma_dut_dpp_qr_resp_4(dev, apdev):
"""sigma_dut DPP/QR responder (conf index 4)"""
run_sigma_dut_dpp_qr_resp(dev, apdev, 4)
def test_sigma_dut_dpp_qr_resp_5(dev, apdev):
"""sigma_dut DPP/QR responder (conf index 5)"""
run_sigma_dut_dpp_qr_resp(dev, apdev, 5)
def test_sigma_dut_dpp_qr_resp_6(dev, apdev):
"""sigma_dut DPP/QR responder (conf index 6)"""
run_sigma_dut_dpp_qr_resp(dev, apdev, 6)
def test_sigma_dut_dpp_qr_resp_7(dev, apdev):
"""sigma_dut DPP/QR responder (conf index 7)"""
run_sigma_dut_dpp_qr_resp(dev, apdev, 7)
def test_sigma_dut_dpp_qr_resp_chan_list(dev, apdev):
"""sigma_dut DPP/QR responder (channel list override)"""
run_sigma_dut_dpp_qr_resp(dev, apdev, 1, chan_list='81/2 81/6 81/1',
listen_chan=2)
def run_sigma_dut_dpp_qr_resp(dev, apdev, conf_idx, chan_list=None,
listen_chan=None):
check_dpp_capab(dev[0])
check_dpp_capab(dev[1])
sigma = start_sigma_dut(dev[0].ifname)
try:
cmd = "dev_exec_action,program,DPP,DPPActionType,GetLocalBootstrap,DPPCryptoIdentifier,P-256,DPPBS,QR"
if chan_list:
cmd += ",DPPChannelList," + chan_list
res = sigma_dut_cmd(cmd)
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
hex = res.split(',')[3]
uri = hex.decode('hex')
logger.info("URI from sigma_dut: " + uri)
res = dev[1].request("DPP_QR_CODE " + uri)
if "FAIL" in res:
raise Exception("Failed to parse QR Code URI")
id1 = int(res)
t = threading.Thread(target=dpp_init_enrollee, args=(dev[1], id1))
t.start()
cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Responder,DPPConfIndex,%d,DPPAuthDirection,Single,DPPProvisioningRole,Configurator,DPPConfEnrolleeRole,STA,DPPSigningKeyECC,P-256,DPPBS,QR,DPPTimeout,6" % conf_idx
if listen_chan:
cmd += ",DPPListenChannel," + str(listen_chan)
res = sigma_dut_cmd(cmd, timeout=10)
t.join()
if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
raise Exception("Unexpected result: " + res)
finally:
stop_sigma_dut(sigma)
def test_sigma_dut_dpp_qr_init_enrollee(dev, apdev):
"""sigma_dut DPP/QR initiator as Enrollee"""
check_dpp_capab(dev[0])
check_dpp_capab(dev[1])
csign = "30770201010420768240a3fc89d6662d9782f120527fe7fb9edc6366ab0b9c7dde96125cfd250fa00a06082a8648ce3d030107a144034200042908e1baf7bf413cc66f9e878a03e8bb1835ba94b033dbe3d6969fc8575d5eb5dfda1cb81c95cee21d0cd7d92ba30541ffa05cb6296f5dd808b0c1c2a83c0708"
csign_pub = "3059301306072a8648ce3d020106082a8648ce3d030107034200042908e1baf7bf413cc66f9e878a03e8bb1835ba94b033dbe3d6969fc8575d5eb5dfda1cb81c95cee21d0cd7d92ba30541ffa05cb6296f5dd808b0c1c2a83c0708"
ap_connector = "eyJ0eXAiOiJkcHBDb24iLCJraWQiOiJwYWtZbXVzd1dCdWpSYTl5OEsweDViaTVrT3VNT3dzZHRlaml2UG55ZHZzIiwiYWxnIjoiRVMyNTYifQ.eyJncm91cHMiOlt7Imdyb3VwSWQiOiIqIiwibmV0Um9sZSI6ImFwIn1dLCJuZXRBY2Nlc3NLZXkiOnsia3R5IjoiRUMiLCJjcnYiOiJQLTI1NiIsIngiOiIybU5vNXZuRkI5bEw3d1VWb1hJbGVPYzBNSEE1QXZKbnpwZXZULVVTYzVNIiwieSI6IlhzS3dqVHJlLTg5WWdpU3pKaG9CN1haeUttTU05OTl3V2ZaSVl0bi01Q3MifX0.XhjFpZgcSa7G2lHy0OCYTvaZFRo5Hyx6b7g7oYyusLC7C_73AJ4_BxEZQVYJXAtDuGvb3dXSkHEKxREP9Q6Qeg"
ap_netaccesskey = "30770201010420ceba752db2ad5200fa7bc565b9c05c69b7eb006751b0b329b0279de1c19ca67ca00a06082a8648ce3d030107a14403420004da6368e6f9c507d94bef0515a1722578e73430703902f267ce97af4fe51273935ec2b08d3adefbcf588224b3261a01ed76722a630cf7df7059f64862d9fee42b"
params = { "ssid": "DPPNET01",
"wpa": "2",
"ieee80211w": "2",
"wpa_key_mgmt": "DPP",
"rsn_pairwise": "CCMP",
"dpp_connector": ap_connector,
"dpp_csign": csign_pub,
"dpp_netaccesskey": ap_netaccesskey }
try:
hapd = hostapd.add_ap(apdev[0], params)
except:
raise HwsimSkip("DPP not supported")
sigma = start_sigma_dut(dev[0].ifname)
try:
dev[0].set("dpp_config_processing", "2")
cmd = "DPP_CONFIGURATOR_ADD key=" + csign
res = dev[1].request(cmd);
if "FAIL" in res:
raise Exception("Failed to add configurator")
conf_id = int(res)
addr = dev[1].own_addr().replace(':', '')
cmd = "DPP_BOOTSTRAP_GEN type=qrcode chan=81/6 mac=" + addr
res = dev[1].request(cmd)
if "FAIL" in res:
raise Exception("Failed to generate bootstrapping info")
id0 = int(res)
uri0 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
dev[1].set("dpp_configurator_params",
" conf=sta-dpp ssid=%s configurator=%d" % ("DPPNET01".encode("hex"), conf_id));
cmd = "DPP_LISTEN 2437 role=configurator"
if "OK" not in dev[1].request(cmd):
raise Exception("Failed to start listen operation")
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % uri0.encode('hex'))
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,Enrollee,DPPBS,QR,DPPTimeout,6,DPPWaitForConnect,Yes", timeout=10)
if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK,NetworkIntroResult,OK,NetworkConnectResult,OK" not in res:
raise Exception("Unexpected result: " + res)
finally:
dev[0].set("dpp_config_processing", "0")
stop_sigma_dut(sigma)
def test_sigma_dut_dpp_qr_mutual_init_enrollee(dev, apdev):
"""sigma_dut DPP/QR (mutual) initiator as Enrollee"""
run_sigma_dut_dpp_qr_mutual_init_enrollee_check(dev, apdev)
def test_sigma_dut_dpp_qr_mutual_init_enrollee_check(dev, apdev):
"""sigma_dut DPP/QR (mutual) initiator as Enrollee (extra check)"""
run_sigma_dut_dpp_qr_mutual_init_enrollee_check(dev, apdev,
extra="DPPAuthDirection,Mutual,")
def run_sigma_dut_dpp_qr_mutual_init_enrollee_check(dev, apdev, extra=''):
check_dpp_capab(dev[0])
check_dpp_capab(dev[1])
csign = "30770201010420768240a3fc89d6662d9782f120527fe7fb9edc6366ab0b9c7dde96125cfd250fa00a06082a8648ce3d030107a144034200042908e1baf7bf413cc66f9e878a03e8bb1835ba94b033dbe3d6969fc8575d5eb5dfda1cb81c95cee21d0cd7d92ba30541ffa05cb6296f5dd808b0c1c2a83c0708"
csign_pub = "3059301306072a8648ce3d020106082a8648ce3d030107034200042908e1baf7bf413cc66f9e878a03e8bb1835ba94b033dbe3d6969fc8575d5eb5dfda1cb81c95cee21d0cd7d92ba30541ffa05cb6296f5dd808b0c1c2a83c0708"
ap_connector = "eyJ0eXAiOiJkcHBDb24iLCJraWQiOiJwYWtZbXVzd1dCdWpSYTl5OEsweDViaTVrT3VNT3dzZHRlaml2UG55ZHZzIiwiYWxnIjoiRVMyNTYifQ.eyJncm91cHMiOlt7Imdyb3VwSWQiOiIqIiwibmV0Um9sZSI6ImFwIn1dLCJuZXRBY2Nlc3NLZXkiOnsia3R5IjoiRUMiLCJjcnYiOiJQLTI1NiIsIngiOiIybU5vNXZuRkI5bEw3d1VWb1hJbGVPYzBNSEE1QXZKbnpwZXZULVVTYzVNIiwieSI6IlhzS3dqVHJlLTg5WWdpU3pKaG9CN1haeUttTU05OTl3V2ZaSVl0bi01Q3MifX0.XhjFpZgcSa7G2lHy0OCYTvaZFRo5Hyx6b7g7oYyusLC7C_73AJ4_BxEZQVYJXAtDuGvb3dXSkHEKxREP9Q6Qeg"
ap_netaccesskey = "30770201010420ceba752db2ad5200fa7bc565b9c05c69b7eb006751b0b329b0279de1c19ca67ca00a06082a8648ce3d030107a14403420004da6368e6f9c507d94bef0515a1722578e73430703902f267ce97af4fe51273935ec2b08d3adefbcf588224b3261a01ed76722a630cf7df7059f64862d9fee42b"
params = { "ssid": "DPPNET01",
"wpa": "2",
"ieee80211w": "2",
"wpa_key_mgmt": "DPP",
"rsn_pairwise": "CCMP",
"dpp_connector": ap_connector,
"dpp_csign": csign_pub,
"dpp_netaccesskey": ap_netaccesskey }
try:
hapd = hostapd.add_ap(apdev[0], params)
except:
raise HwsimSkip("DPP not supported")
sigma = start_sigma_dut(dev[0].ifname)
try:
dev[0].set("dpp_config_processing", "2")
cmd = "DPP_CONFIGURATOR_ADD key=" + csign
res = dev[1].request(cmd);
if "FAIL" in res:
raise Exception("Failed to add configurator")
conf_id = int(res)
addr = dev[1].own_addr().replace(':', '')
cmd = "DPP_BOOTSTRAP_GEN type=qrcode chan=81/6 mac=" + addr
res = dev[1].request(cmd)
if "FAIL" in res:
raise Exception("Failed to generate bootstrapping info")
id0 = int(res)
uri0 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
dev[1].set("dpp_configurator_params",
" conf=sta-dpp ssid=%s configurator=%d" % ("DPPNET01".encode("hex"), conf_id));
cmd = "DPP_LISTEN 2437 role=configurator qr=mutual"
if "OK" not in dev[1].request(cmd):
raise Exception("Failed to start listen operation")
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,GetLocalBootstrap,DPPCryptoIdentifier,P-256,DPPBS,QR")
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
hex = res.split(',')[3]
uri = hex.decode('hex')
logger.info("URI from sigma_dut: " + uri)
res = dev[1].request("DPP_QR_CODE " + uri)
if "FAIL" in res:
raise Exception("Failed to parse QR Code URI")
id1 = int(res)
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % uri0.encode('hex'))
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,%sDPPProvisioningRole,Enrollee,DPPBS,QR,DPPTimeout,6,DPPWaitForConnect,Yes" % extra, timeout=10)
if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK,NetworkIntroResult,OK,NetworkConnectResult,OK" not in res:
raise Exception("Unexpected result: " + res)
finally:
dev[0].set("dpp_config_processing", "0")
stop_sigma_dut(sigma)
def dpp_init_conf_mutual(dev, id1, conf_id, own_id=None):
time.sleep(1)
logger.info("Starting DPP initiator/configurator in a thread")
cmd = "DPP_AUTH_INIT peer=%d conf=sta-dpp ssid=%s configurator=%d" % (id1, "DPPNET01".encode("hex"), conf_id)
if own_id is not None:
cmd += " own=%d" % own_id
if "OK" not in dev.request(cmd):
raise Exception("Failed to initiate DPP Authentication")
ev = dev.wait_event(["DPP-CONF-SENT"], timeout=10)
if ev is None:
raise Exception("DPP configuration not completed (Configurator)")
logger.info("DPP initiator/configurator done")
def test_sigma_dut_dpp_qr_mutual_resp_enrollee(dev, apdev):
"""sigma_dut DPP/QR (mutual) responder as Enrollee"""
run_sigma_dut_dpp_qr_mutual_resp_enrollee(dev, apdev)
def test_sigma_dut_dpp_qr_mutual_resp_enrollee_pending(dev, apdev):
"""sigma_dut DPP/QR (mutual) responder as Enrollee (response pending)"""
run_sigma_dut_dpp_qr_mutual_resp_enrollee(dev, apdev, ',DPPDelayQRResponse,1')
def run_sigma_dut_dpp_qr_mutual_resp_enrollee(dev, apdev, extra=None):
check_dpp_capab(dev[0])
check_dpp_capab(dev[1])
csign = "30770201010420768240a3fc89d6662d9782f120527fe7fb9edc6366ab0b9c7dde96125cfd250fa00a06082a8648ce3d030107a144034200042908e1baf7bf413cc66f9e878a03e8bb1835ba94b033dbe3d6969fc8575d5eb5dfda1cb81c95cee21d0cd7d92ba30541ffa05cb6296f5dd808b0c1c2a83c0708"
csign_pub = "3059301306072a8648ce3d020106082a8648ce3d030107034200042908e1baf7bf413cc66f9e878a03e8bb1835ba94b033dbe3d6969fc8575d5eb5dfda1cb81c95cee21d0cd7d92ba30541ffa05cb6296f5dd808b0c1c2a83c0708"
ap_connector = "eyJ0eXAiOiJkcHBDb24iLCJraWQiOiJwYWtZbXVzd1dCdWpSYTl5OEsweDViaTVrT3VNT3dzZHRlaml2UG55ZHZzIiwiYWxnIjoiRVMyNTYifQ.eyJncm91cHMiOlt7Imdyb3VwSWQiOiIqIiwibmV0Um9sZSI6ImFwIn1dLCJuZXRBY2Nlc3NLZXkiOnsia3R5IjoiRUMiLCJjcnYiOiJQLTI1NiIsIngiOiIybU5vNXZuRkI5bEw3d1VWb1hJbGVPYzBNSEE1QXZKbnpwZXZULVVTYzVNIiwieSI6IlhzS3dqVHJlLTg5WWdpU3pKaG9CN1haeUttTU05OTl3V2ZaSVl0bi01Q3MifX0.XhjFpZgcSa7G2lHy0OCYTvaZFRo5Hyx6b7g7oYyusLC7C_73AJ4_BxEZQVYJXAtDuGvb3dXSkHEKxREP9Q6Qeg"
ap_netaccesskey = "30770201010420ceba752db2ad5200fa7bc565b9c05c69b7eb006751b0b329b0279de1c19ca67ca00a06082a8648ce3d030107a14403420004da6368e6f9c507d94bef0515a1722578e73430703902f267ce97af4fe51273935ec2b08d3adefbcf588224b3261a01ed76722a630cf7df7059f64862d9fee42b"
params = { "ssid": "DPPNET01",
"wpa": "2",
"ieee80211w": "2",
"wpa_key_mgmt": "DPP",
"rsn_pairwise": "CCMP",
"dpp_connector": ap_connector,
"dpp_csign": csign_pub,
"dpp_netaccesskey": ap_netaccesskey }
try:
hapd = hostapd.add_ap(apdev[0], params)
except:
raise HwsimSkip("DPP not supported")
sigma = start_sigma_dut(dev[0].ifname)
try:
dev[0].set("dpp_config_processing", "2")
cmd = "DPP_CONFIGURATOR_ADD key=" + csign
res = dev[1].request(cmd);
if "FAIL" in res:
raise Exception("Failed to add configurator")
conf_id = int(res)
addr = dev[1].own_addr().replace(':', '')
cmd = "DPP_BOOTSTRAP_GEN type=qrcode chan=81/6 mac=" + addr
res = dev[1].request(cmd)
if "FAIL" in res:
raise Exception("Failed to generate bootstrapping info")
id0 = int(res)
uri0 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,GetLocalBootstrap,DPPCryptoIdentifier,P-256,DPPBS,QR")
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
hex = res.split(',')[3]
uri = hex.decode('hex')
logger.info("URI from sigma_dut: " + uri)
res = dev[1].request("DPP_QR_CODE " + uri)
if "FAIL" in res:
raise Exception("Failed to parse QR Code URI")
id1 = int(res)
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % uri0.encode('hex'))
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
t = threading.Thread(target=dpp_init_conf_mutual,
args=(dev[1], id1, conf_id, id0))
t.start()
cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Responder,DPPAuthDirection,Mutual,DPPProvisioningRole,Enrollee,DPPBS,QR,DPPTimeout,20,DPPWaitForConnect,Yes"
if extra:
cmd += extra
res = sigma_dut_cmd(cmd, timeout=25)
t.join()
if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK,NetworkIntroResult,OK,NetworkConnectResult,OK" not in res:
raise Exception("Unexpected result: " + res)
finally:
dev[0].set("dpp_config_processing", "0")
stop_sigma_dut(sigma)
def dpp_resp_conf_mutual(dev, conf_id, uri):
logger.info("Starting DPP responder/configurator in a thread")
dev.set("dpp_configurator_params",
" conf=sta-dpp ssid=%s configurator=%d" % ("DPPNET01".encode("hex"), conf_id));
cmd = "DPP_LISTEN 2437 role=configurator qr=mutual"
if "OK" not in dev.request(cmd):
raise Exception("Failed to initiate DPP listen")
if uri:
ev = dev.wait_event(["DPP-SCAN-PEER-QR-CODE"], timeout=10)
if ev is None:
raise Exception("QR Code scan for mutual authentication not requested")
res = dev.request("DPP_QR_CODE " + uri)
if "FAIL" in res:
raise Exception("Failed to parse QR Code URI")
ev = dev.wait_event(["DPP-CONF-SENT"], timeout=10)
if ev is None:
raise Exception("DPP configuration not completed (Configurator)")
logger.info("DPP responder/configurator done")
def test_sigma_dut_dpp_qr_mutual_init_enrollee(dev, apdev):
"""sigma_dut DPP/QR (mutual) initiator as Enrollee"""
run_sigma_dut_dpp_qr_mutual_init_enrollee(dev, apdev, False)
def test_sigma_dut_dpp_qr_mutual_init_enrollee_pending(dev, apdev):
"""sigma_dut DPP/QR (mutual) initiator as Enrollee (response pending)"""
run_sigma_dut_dpp_qr_mutual_init_enrollee(dev, apdev, True)
def run_sigma_dut_dpp_qr_mutual_init_enrollee(dev, apdev, resp_pending):
check_dpp_capab(dev[0])
check_dpp_capab(dev[1])
csign = "30770201010420768240a3fc89d6662d9782f120527fe7fb9edc6366ab0b9c7dde96125cfd250fa00a06082a8648ce3d030107a144034200042908e1baf7bf413cc66f9e878a03e8bb1835ba94b033dbe3d6969fc8575d5eb5dfda1cb81c95cee21d0cd7d92ba30541ffa05cb6296f5dd808b0c1c2a83c0708"
csign_pub = "3059301306072a8648ce3d020106082a8648ce3d030107034200042908e1baf7bf413cc66f9e878a03e8bb1835ba94b033dbe3d6969fc8575d5eb5dfda1cb81c95cee21d0cd7d92ba30541ffa05cb6296f5dd808b0c1c2a83c0708"
ap_connector = "eyJ0eXAiOiJkcHBDb24iLCJraWQiOiJwYWtZbXVzd1dCdWpSYTl5OEsweDViaTVrT3VNT3dzZHRlaml2UG55ZHZzIiwiYWxnIjoiRVMyNTYifQ.eyJncm91cHMiOlt7Imdyb3VwSWQiOiIqIiwibmV0Um9sZSI6ImFwIn1dLCJuZXRBY2Nlc3NLZXkiOnsia3R5IjoiRUMiLCJjcnYiOiJQLTI1NiIsIngiOiIybU5vNXZuRkI5bEw3d1VWb1hJbGVPYzBNSEE1QXZKbnpwZXZULVVTYzVNIiwieSI6IlhzS3dqVHJlLTg5WWdpU3pKaG9CN1haeUttTU05OTl3V2ZaSVl0bi01Q3MifX0.XhjFpZgcSa7G2lHy0OCYTvaZFRo5Hyx6b7g7oYyusLC7C_73AJ4_BxEZQVYJXAtDuGvb3dXSkHEKxREP9Q6Qeg"
ap_netaccesskey = "30770201010420ceba752db2ad5200fa7bc565b9c05c69b7eb006751b0b329b0279de1c19ca67ca00a06082a8648ce3d030107a14403420004da6368e6f9c507d94bef0515a1722578e73430703902f267ce97af4fe51273935ec2b08d3adefbcf588224b3261a01ed76722a630cf7df7059f64862d9fee42b"
params = { "ssid": "DPPNET01",
"wpa": "2",
"ieee80211w": "2",
"wpa_key_mgmt": "DPP",
"rsn_pairwise": "CCMP",
"dpp_connector": ap_connector,
"dpp_csign": csign_pub,
"dpp_netaccesskey": ap_netaccesskey }
try:
hapd = hostapd.add_ap(apdev[0], params)
except:
raise HwsimSkip("DPP not supported")
sigma = start_sigma_dut(dev[0].ifname)
try:
dev[0].set("dpp_config_processing", "2")
cmd = "DPP_CONFIGURATOR_ADD key=" + csign
res = dev[1].request(cmd);
if "FAIL" in res:
raise Exception("Failed to add configurator")
conf_id = int(res)
addr = dev[1].own_addr().replace(':', '')
cmd = "DPP_BOOTSTRAP_GEN type=qrcode chan=81/6 mac=" + addr
res = dev[1].request(cmd)
if "FAIL" in res:
raise Exception("Failed to generate bootstrapping info")
id0 = int(res)
uri0 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,GetLocalBootstrap,DPPCryptoIdentifier,P-256,DPPBS,QR")
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
hex = res.split(',')[3]
uri = hex.decode('hex')
logger.info("URI from sigma_dut: " + uri)
if not resp_pending:
res = dev[1].request("DPP_QR_CODE " + uri)
if "FAIL" in res:
raise Exception("Failed to parse QR Code URI")
uri = None
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % uri0.encode('hex'))
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
t = threading.Thread(target=dpp_resp_conf_mutual,
args=(dev[1], conf_id, uri))
t.start()
time.sleep(1)
cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPProvisioningRole,Enrollee,DPPBS,QR,DPPTimeout,10,DPPWaitForConnect,Yes"
res = sigma_dut_cmd(cmd, timeout=15)
t.join()
if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK,NetworkIntroResult,OK,NetworkConnectResult,OK" not in res:
raise Exception("Unexpected result: " + res)
finally:
dev[0].set("dpp_config_processing", "0")
stop_sigma_dut(sigma)
def test_sigma_dut_dpp_qr_init_enrollee_psk(dev, apdev):
"""sigma_dut DPP/QR initiator as Enrollee (PSK)"""
check_dpp_capab(dev[0])
check_dpp_capab(dev[1])
params = hostapd.wpa2_params(ssid="DPPNET01",
passphrase="ThisIsDppPassphrase")
hapd = hostapd.add_ap(apdev[0], params)
sigma = start_sigma_dut(dev[0].ifname)
try:
dev[0].set("dpp_config_processing", "2")
cmd = "DPP_CONFIGURATOR_ADD"
res = dev[1].request(cmd);
if "FAIL" in res:
raise Exception("Failed to add configurator")
conf_id = int(res)
addr = dev[1].own_addr().replace(':', '')
cmd = "DPP_BOOTSTRAP_GEN type=qrcode chan=81/6 mac=" + addr
res = dev[1].request(cmd)
if "FAIL" in res:
raise Exception("Failed to generate bootstrapping info")
id0 = int(res)
uri0 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
dev[1].set("dpp_configurator_params",
" conf=sta-psk ssid=%s pass=%s configurator=%d" % ("DPPNET01".encode("hex"), "ThisIsDppPassphrase".encode("hex"), conf_id));
cmd = "DPP_LISTEN 2437 role=configurator"
if "OK" not in dev[1].request(cmd):
raise Exception("Failed to start listen operation")
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % uri0.encode('hex'))
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,Enrollee,DPPBS,QR,DPPTimeout,6,DPPWaitForConnect,Yes", timeout=10)
if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK,NetworkConnectResult,OK" not in res:
raise Exception("Unexpected result: " + res)
finally:
dev[0].set("dpp_config_processing", "0")
stop_sigma_dut(sigma)
def test_sigma_dut_dpp_qr_init_configurator_1(dev, apdev):
"""sigma_dut DPP/QR initiator as Configurator (conf index 1)"""
run_sigma_dut_dpp_qr_init_configurator(dev, apdev, 1)
def test_sigma_dut_dpp_qr_init_configurator_2(dev, apdev):
"""sigma_dut DPP/QR initiator as Configurator (conf index 2)"""
run_sigma_dut_dpp_qr_init_configurator(dev, apdev, 2)
def test_sigma_dut_dpp_qr_init_configurator_3(dev, apdev):
"""sigma_dut DPP/QR initiator as Configurator (conf index 3)"""
run_sigma_dut_dpp_qr_init_configurator(dev, apdev, 3)
def test_sigma_dut_dpp_qr_init_configurator_4(dev, apdev):
"""sigma_dut DPP/QR initiator as Configurator (conf index 4)"""
run_sigma_dut_dpp_qr_init_configurator(dev, apdev, 4)
def test_sigma_dut_dpp_qr_init_configurator_5(dev, apdev):
"""sigma_dut DPP/QR initiator as Configurator (conf index 5)"""
run_sigma_dut_dpp_qr_init_configurator(dev, apdev, 5)
def test_sigma_dut_dpp_qr_init_configurator_6(dev, apdev):
"""sigma_dut DPP/QR initiator as Configurator (conf index 6)"""
run_sigma_dut_dpp_qr_init_configurator(dev, apdev, 6)
def test_sigma_dut_dpp_qr_init_configurator_7(dev, apdev):
"""sigma_dut DPP/QR initiator as Configurator (conf index 7)"""
run_sigma_dut_dpp_qr_init_configurator(dev, apdev, 7)
def test_sigma_dut_dpp_qr_init_configurator_both(dev, apdev):
"""sigma_dut DPP/QR initiator as Configurator or Enrollee (conf index 1)"""
run_sigma_dut_dpp_qr_init_configurator(dev, apdev, 1, "Both")
def test_sigma_dut_dpp_qr_init_configurator_neg_freq(dev, apdev):
"""sigma_dut DPP/QR initiator as Configurator (neg_freq)"""
run_sigma_dut_dpp_qr_init_configurator(dev, apdev, 1, extra='DPPSubsequentChannel,81/11')
def run_sigma_dut_dpp_qr_init_configurator(dev, apdev, conf_idx,
prov_role="Configurator",
extra=None):
check_dpp_capab(dev[0])
check_dpp_capab(dev[1])
sigma = start_sigma_dut(dev[0].ifname)
try:
addr = dev[1].own_addr().replace(':', '')
cmd = "DPP_BOOTSTRAP_GEN type=qrcode chan=81/6 mac=" + addr
res = dev[1].request(cmd)
if "FAIL" in res:
raise Exception("Failed to generate bootstrapping info")
id0 = int(res)
uri0 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
cmd = "DPP_LISTEN 2437 role=enrollee"
if "OK" not in dev[1].request(cmd):
raise Exception("Failed to start listen operation")
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % uri0.encode('hex'))
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,%s,DPPConfIndex,%d,DPPSigningKeyECC,P-256,DPPConfEnrolleeRole,STA,DPPBS,QR,DPPTimeout,6" % (prov_role, conf_idx)
if extra:
cmd += "," + extra
res = sigma_dut_cmd(cmd)
if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
raise Exception("Unexpected result: " + res)
finally:
stop_sigma_dut(sigma)
def test_sigma_dut_dpp_incompatible_roles_init(dev, apdev):
"""sigma_dut DPP roles incompatible (Initiator)"""
check_dpp_capab(dev[0])
check_dpp_capab(dev[1])
sigma = start_sigma_dut(dev[0].ifname)
try:
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,GetLocalBootstrap,DPPCryptoIdentifier,P-256,DPPBS,QR")
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
hex = res.split(',')[3]
uri = hex.decode('hex')
logger.info("URI from sigma_dut: " + uri)
res = dev[1].request("DPP_QR_CODE " + uri)
if "FAIL" in res:
raise Exception("Failed to parse QR Code URI")
id1 = int(res)
addr = dev[1].own_addr().replace(':', '')
cmd = "DPP_BOOTSTRAP_GEN type=qrcode chan=81/6 mac=" + addr
res = dev[1].request(cmd)
if "FAIL" in res:
raise Exception("Failed to generate bootstrapping info")
id0 = int(res)
uri0 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
cmd = "DPP_LISTEN 2437 role=enrollee"
if "OK" not in dev[1].request(cmd):
raise Exception("Failed to start listen operation")
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % uri0.encode('hex'))
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Mutual,DPPProvisioningRole,Enrollee,DPPBS,QR,DPPTimeout,6"
res = sigma_dut_cmd(cmd)
if "BootstrapResult,OK,AuthResult,ROLES_NOT_COMPATIBLE" not in res:
raise Exception("Unexpected result: " + res)
finally:
stop_sigma_dut(sigma)
def dpp_init_enrollee_mutual(dev, id1, own_id):
logger.info("Starting DPP initiator/enrollee in a thread")
time.sleep(1)
cmd = "DPP_AUTH_INIT peer=%d own=%d role=enrollee" % (id1, own_id)
if "OK" not in dev.request(cmd):
raise Exception("Failed to initiate DPP Authentication")
ev = dev.wait_event(["DPP-CONF-RECEIVED",
"DPP-NOT-COMPATIBLE"], timeout=5)
if ev is None:
raise Exception("DPP configuration not completed (Enrollee)")
logger.info("DPP initiator/enrollee done")
def test_sigma_dut_dpp_incompatible_roles_resp(dev, apdev):
"""sigma_dut DPP roles incompatible (Responder)"""
check_dpp_capab(dev[0])
check_dpp_capab(dev[1])
sigma = start_sigma_dut(dev[0].ifname)
try:
cmd = "dev_exec_action,program,DPP,DPPActionType,GetLocalBootstrap,DPPCryptoIdentifier,P-256,DPPBS,QR"
res = sigma_dut_cmd(cmd)
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
hex = res.split(',')[3]
uri = hex.decode('hex')
logger.info("URI from sigma_dut: " + uri)
res = dev[1].request("DPP_QR_CODE " + uri)
if "FAIL" in res:
raise Exception("Failed to parse QR Code URI")
id1 = int(res)
addr = dev[1].own_addr().replace(':', '')
cmd = "DPP_BOOTSTRAP_GEN type=qrcode chan=81/6 mac=" + addr
res = dev[1].request(cmd)
if "FAIL" in res:
raise Exception("Failed to generate bootstrapping info")
id0 = int(res)
uri0 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % uri0.encode('hex'))
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
t = threading.Thread(target=dpp_init_enrollee_mutual, args=(dev[1], id1, id0))
t.start()
cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Responder,DPPAuthDirection,Mutual,DPPProvisioningRole,Enrollee,DPPBS,QR,DPPTimeout,6"
res = sigma_dut_cmd(cmd, timeout=10)
t.join()
if "BootstrapResult,OK,AuthResult,ROLES_NOT_COMPATIBLE" not in res:
raise Exception("Unexpected result: " + res)
finally:
stop_sigma_dut(sigma)
def test_sigma_dut_dpp_pkex_init_configurator(dev, apdev):
"""sigma_dut DPP/PKEX initiator as Configurator"""
check_dpp_capab(dev[0])
check_dpp_capab(dev[1])
sigma = start_sigma_dut(dev[0].ifname)
try:
cmd = "DPP_BOOTSTRAP_GEN type=pkex"
res = dev[1].request(cmd)
if "FAIL" in res:
raise Exception("Failed to generate bootstrapping info")
id1 = int(res)
cmd = "DPP_PKEX_ADD own=%d identifier=test code=secret" % (id1)
res = dev[1].request(cmd)
if "FAIL" in res:
raise Exception("Failed to set PKEX data (responder)")
cmd = "DPP_LISTEN 2437 role=enrollee"
if "OK" not in dev[1].request(cmd):
raise Exception("Failed to start listen operation")
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPProvisioningRole,Configurator,DPPConfIndex,1,DPPSigningKeyECC,P-256,DPPConfEnrolleeRole,STA,DPPBS,PKEX,DPPPKEXCodeIdentifier,test,DPPPKEXCode,secret,DPPTimeout,6")
if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
raise Exception("Unexpected result: " + res)
finally:
stop_sigma_dut(sigma)
def dpp_init_conf(dev, id1, conf, conf_id, extra):
logger.info("Starting DPP initiator/configurator in a thread")
cmd = "DPP_AUTH_INIT peer=%d conf=%s %s configurator=%d" % (id1, conf, extra, conf_id)
if "OK" not in dev.request(cmd):
raise Exception("Failed to initiate DPP Authentication")
ev = dev.wait_event(["DPP-CONF-SENT"], timeout=5)
if ev is None:
raise Exception("DPP configuration not completed (Configurator)")
logger.info("DPP initiator/configurator done")
def test_sigma_dut_ap_dpp_qr(dev, apdev, params):
"""sigma_dut controlled AP (DPP)"""
run_sigma_dut_ap_dpp_qr(dev, apdev, params, "ap-dpp", "sta-dpp")
def test_sigma_dut_ap_dpp_qr_legacy(dev, apdev, params):
"""sigma_dut controlled AP (legacy)"""
run_sigma_dut_ap_dpp_qr(dev, apdev, params, "ap-psk", "sta-psk",
extra="pass=%s" % "qwertyuiop".encode("hex"))
def test_sigma_dut_ap_dpp_qr_legacy_psk(dev, apdev, params):
"""sigma_dut controlled AP (legacy)"""
run_sigma_dut_ap_dpp_qr(dev, apdev, params, "ap-psk", "sta-psk",
extra="psk=%s" % (32*"12"))
def run_sigma_dut_ap_dpp_qr(dev, apdev, params, ap_conf, sta_conf, extra=""):
check_dpp_capab(dev[0])
logdir = os.path.join(params['logdir'], "sigma_dut_ap_dpp_qr.sigma-hostapd")
with HWSimRadio() as (radio, iface):
sigma = start_sigma_dut(iface, hostapd_logdir=logdir)
try:
sigma_dut_cmd_check("ap_reset_default,program,DPP")
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,GetLocalBootstrap,DPPCryptoIdentifier,P-256,DPPBS,QR")
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
hex = res.split(',')[3]
uri = hex.decode('hex')
logger.info("URI from sigma_dut: " + uri)
cmd = "DPP_CONFIGURATOR_ADD"
res = dev[0].request(cmd);
if "FAIL" in res:
raise Exception("Failed to add configurator")
conf_id = int(res)
res = dev[0].request("DPP_QR_CODE " + uri)
if "FAIL" in res:
raise Exception("Failed to parse QR Code URI")
id1 = int(res)
t = threading.Thread(target=dpp_init_conf,
args=(dev[0], id1, ap_conf, conf_id, extra))
t.start()
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Responder,DPPAuthDirection,Single,DPPProvisioningRole,Enrollee,DPPBS,QR,DPPTimeout,6")
t.join()
if "ConfResult,OK" not in res:
raise Exception("Unexpected result: " + res)
addr = dev[1].own_addr().replace(':', '')
cmd = "DPP_BOOTSTRAP_GEN type=qrcode chan=81/1 mac=" + addr
res = dev[1].request(cmd)
if "FAIL" in res:
raise Exception("Failed to generate bootstrapping info")
id1 = int(res)
uri1 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id1)
res = dev[0].request("DPP_QR_CODE " + uri1)
if "FAIL" in res:
raise Exception("Failed to parse QR Code URI")
id0b = int(res)
dev[1].set("dpp_config_processing", "2")
cmd = "DPP_LISTEN 2412"
if "OK" not in dev[1].request(cmd):
raise Exception("Failed to start listen operation")
cmd = "DPP_AUTH_INIT peer=%d conf=%s %s configurator=%d" % (id0b, sta_conf, extra, conf_id)
if "OK" not in dev[0].request(cmd):
raise Exception("Failed to initiate DPP Authentication")
dev[1].wait_connected()
sigma_dut_cmd_check("ap_reset_default")
finally:
dev[1].set("dpp_config_processing", "0")
stop_sigma_dut(sigma)
def test_sigma_dut_ap_dpp_pkex_responder(dev, apdev, params):
"""sigma_dut controlled AP as DPP PKEX responder"""
check_dpp_capab(dev[0])
logdir = os.path.join(params['logdir'],
"sigma_dut_ap_dpp_pkex_responder.sigma-hostapd")
with HWSimRadio() as (radio, iface):
sigma = start_sigma_dut(iface, hostapd_logdir=logdir)
try:
run_sigma_dut_ap_dpp_pkex_responder(dev, apdev)
finally:
stop_sigma_dut(sigma)
def dpp_init_conf_pkex(dev, conf_id, check_config=True):
logger.info("Starting DPP PKEX initiator/configurator in a thread")
time.sleep(1.5)
cmd = "DPP_BOOTSTRAP_GEN type=pkex"
res = dev.request(cmd)
if "FAIL" in res:
raise Exception("Failed to generate bootstrapping info")
id = int(res)
cmd = "DPP_PKEX_ADD own=%d init=1 conf=ap-dpp configurator=%d code=password" % (id, conf_id)
res = dev.request(cmd)
if "FAIL" in res:
raise Exception("Failed to initiate DPP PKEX")
if not check_config:
return
ev = dev.wait_event(["DPP-CONF-SENT"], timeout=5)
if ev is None:
raise Exception("DPP configuration not completed (Configurator)")
logger.info("DPP initiator/configurator done")
def run_sigma_dut_ap_dpp_pkex_responder(dev, apdev):
sigma_dut_cmd_check("ap_reset_default,program,DPP")
cmd = "DPP_CONFIGURATOR_ADD"
res = dev[0].request(cmd);
if "FAIL" in res:
raise Exception("Failed to add configurator")
conf_id = int(res)
t = threading.Thread(target=dpp_init_conf_pkex, args=(dev[0], conf_id))
t.start()
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Responder,DPPAuthDirection,Mutual,DPPProvisioningRole,Enrollee,DPPBS,PKEX,DPPPKEXCode,password,DPPTimeout,6,DPPWaitForConnect,No", timeout=10)
t.join()
if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
raise Exception("Unexpected result: " + res)
sigma_dut_cmd_check("ap_reset_default")
def test_sigma_dut_dpp_pkex_responder_proto(dev, apdev):
"""sigma_dut controlled STA as DPP PKEX responder and error case"""
check_dpp_capab(dev[0])
sigma = start_sigma_dut(dev[0].ifname)
try:
run_sigma_dut_dpp_pkex_responder_proto(dev, apdev)
finally:
stop_sigma_dut(sigma)
def run_sigma_dut_dpp_pkex_responder_proto(dev, apdev):
cmd = "DPP_CONFIGURATOR_ADD"
res = dev[1].request(cmd);
if "FAIL" in res:
raise Exception("Failed to add configurator")
conf_id = int(res)
dev[1].set("dpp_test", "44")
t = threading.Thread(target=dpp_init_conf_pkex, args=(dev[1], conf_id,
False))
t.start()
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Responder,DPPProvisioningRole,Enrollee,DPPBS,PKEX,DPPPKEXCode,password,DPPTimeout,6", timeout=10)
t.join()
if "BootstrapResult,Timeout" not in res:
raise Exception("Unexpected result: " + res)
def dpp_proto_init(dev, id1):
time.sleep(1)
logger.info("Starting DPP initiator/configurator in a thread")
cmd = "DPP_CONFIGURATOR_ADD"
res = dev.request(cmd);
if "FAIL" in res:
raise Exception("Failed to add configurator")
conf_id = int(res)
cmd = "DPP_AUTH_INIT peer=%d conf=sta-dpp configurator=%d" % (id1, conf_id)
if "OK" not in dev.request(cmd):
raise Exception("Failed to initiate DPP Authentication")
def test_sigma_dut_dpp_proto_initiator(dev, apdev):
"""sigma_dut DPP protocol testing - Initiator"""
check_dpp_capab(dev[0])
check_dpp_capab(dev[1])
tests = [ ("InvalidValue", "AuthenticationRequest", "WrappedData",
"BootstrapResult,OK,AuthResult,Errorsent",
None),
("InvalidValue", "AuthenticationConfirm", "WrappedData",
"BootstrapResult,OK,AuthResult,Errorsent",
None),
("MissingAttribute", "AuthenticationRequest", "InitCapabilities",
"BootstrapResult,OK,AuthResult,Errorsent",
"Missing or invalid I-capabilities"),
("InvalidValue", "AuthenticationConfirm", "InitAuthTag",
"BootstrapResult,OK,AuthResult,Errorsent",
"Mismatching Initiator Authenticating Tag"),
("MissingAttribute", "ConfigurationResponse", "EnrolleeNonce",
"BootstrapResult,OK,AuthResult,OK,ConfResult,Errorsent",
"Missing or invalid Enrollee Nonce attribute") ]
for step, frame, attr, result, fail in tests:
dev[0].request("FLUSH")
dev[1].request("FLUSH")
sigma = start_sigma_dut(dev[0].ifname)
try:
run_sigma_dut_dpp_proto_initiator(dev, step, frame, attr, result,
fail)
finally:
stop_sigma_dut(sigma)
def run_sigma_dut_dpp_proto_initiator(dev, step, frame, attr, result, fail):
addr = dev[1].own_addr().replace(':', '')
cmd = "DPP_BOOTSTRAP_GEN type=qrcode chan=81/6 mac=" + addr
res = dev[1].request(cmd)
if "FAIL" in res:
raise Exception("Failed to generate bootstrapping info")
id0 = int(res)
uri0 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
cmd = "DPP_LISTEN 2437 role=enrollee"
if "OK" not in dev[1].request(cmd):
raise Exception("Failed to start listen operation")
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % uri0.encode('hex'))
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,Configurator,DPPConfIndex,1,DPPSigningKeyECC,P-256,DPPConfEnrolleeRole,STA,DPPBS,QR,DPPTimeout,6,DPPStep,%s,DPPFrameType,%s,DPPIEAttribute,%s" % (step, frame, attr),
timeout=10)
if result not in res:
raise Exception("Unexpected result: " + res)
if fail:
ev = dev[1].wait_event(["DPP-FAIL"], timeout=5)
if ev is None or fail not in ev:
raise Exception("Failure not reported correctly: " + str(ev))
dev[1].request("DPP_STOP_LISTEN")
dev[0].dump_monitor()
dev[1].dump_monitor()
def test_sigma_dut_dpp_proto_responder(dev, apdev):
"""sigma_dut DPP protocol testing - Responder"""
check_dpp_capab(dev[0])
check_dpp_capab(dev[1])
tests = [ ("MissingAttribute", "AuthenticationResponse", "DPPStatus",
"BootstrapResult,OK,AuthResult,Errorsent",
"Missing or invalid required DPP Status attribute"),
("MissingAttribute", "ConfigurationRequest", "EnrolleeNonce",
"BootstrapResult,OK,AuthResult,OK,ConfResult,Errorsent",
"Missing or invalid Enrollee Nonce attribute") ]
for step, frame, attr, result, fail in tests:
dev[0].request("FLUSH")
dev[1].request("FLUSH")
sigma = start_sigma_dut(dev[0].ifname)
try:
run_sigma_dut_dpp_proto_responder(dev, step, frame, attr, result,
fail)
finally:
stop_sigma_dut(sigma)
def run_sigma_dut_dpp_proto_responder(dev, step, frame, attr, result, fail):
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,GetLocalBootstrap,DPPCryptoIdentifier,P-256,DPPBS,QR")
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
hex = res.split(',')[3]
uri = hex.decode('hex')
logger.info("URI from sigma_dut: " + uri)
res = dev[1].request("DPP_QR_CODE " + uri)
if "FAIL" in res:
raise Exception("Failed to parse QR Code URI")
id1 = int(res)
t = threading.Thread(target=dpp_proto_init, args=(dev[1], id1))
t.start()
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Responder,DPPAuthDirection,Single,DPPProvisioningRole,Enrollee,DPPConfIndex,1,DPPSigningKeyECC,P-256,DPPConfEnrolleeRole,STA,DPPBS,QR,DPPTimeout,6,DPPStep,%s,DPPFrameType,%s,DPPIEAttribute,%s" % (step, frame, attr), timeout=10)
t.join()
if result not in res:
raise Exception("Unexpected result: " + res)
if fail:
ev = dev[1].wait_event(["DPP-FAIL"], timeout=5)
if ev is None or fail not in ev:
raise Exception("Failure not reported correctly:" + str(ev))
dev[1].request("DPP_STOP_LISTEN")
dev[0].dump_monitor()
dev[1].dump_monitor()
def test_sigma_dut_dpp_proto_stop_at_initiator(dev, apdev):
"""sigma_dut DPP protocol testing - Stop at RX on Initiator"""
check_dpp_capab(dev[0])
check_dpp_capab(dev[1])
tests = [ ("AuthenticationResponse",
"BootstrapResult,OK,AuthResult,Errorsent",
None),
("ConfigurationRequest",
"BootstrapResult,OK,AuthResult,OK,ConfResult,Errorsent",
None)]
for frame, result, fail in tests:
dev[0].request("FLUSH")
dev[1].request("FLUSH")
sigma = start_sigma_dut(dev[0].ifname)
try:
run_sigma_dut_dpp_proto_stop_at_initiator(dev, frame, result, fail)
finally:
stop_sigma_dut(sigma)
def run_sigma_dut_dpp_proto_stop_at_initiator(dev, frame, result, fail):
addr = dev[1].own_addr().replace(':', '')
cmd = "DPP_BOOTSTRAP_GEN type=qrcode chan=81/6 mac=" + addr
res = dev[1].request(cmd)
if "FAIL" in res:
raise Exception("Failed to generate bootstrapping info")
id0 = int(res)
uri0 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
cmd = "DPP_LISTEN 2437 role=enrollee"
if "OK" not in dev[1].request(cmd):
raise Exception("Failed to start listen operation")
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % uri0.encode('hex'))
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,Configurator,DPPConfIndex,1,DPPSigningKeyECC,P-256,DPPConfEnrolleeRole,STA,DPPBS,QR,DPPTimeout,6,DPPStep,Timeout,DPPFrameType,%s" % (frame))
if result not in res:
raise Exception("Unexpected result: " + res)
if fail:
ev = dev[1].wait_event(["DPP-FAIL"], timeout=5)
if ev is None or fail not in ev:
raise Exception("Failure not reported correctly: " + str(ev))
dev[1].request("DPP_STOP_LISTEN")
dev[0].dump_monitor()
dev[1].dump_monitor()
def test_sigma_dut_dpp_proto_stop_at_initiator_enrollee(dev, apdev):
"""sigma_dut DPP protocol testing - Stop at TX on Initiator/Enrollee"""
check_dpp_capab(dev[0])
check_dpp_capab(dev[1])
tests = [ ("AuthenticationConfirm",
"BootstrapResult,OK,AuthResult,Errorsent,LastFrameReceived,AuthenticationResponse",
None) ]
for frame, result, fail in tests:
dev[0].request("FLUSH")
dev[1].request("FLUSH")
sigma = start_sigma_dut(dev[0].ifname, debug=True)
try:
run_sigma_dut_dpp_proto_stop_at_initiator_enrollee(dev, frame,
result, fail)
finally:
stop_sigma_dut(sigma)
def run_sigma_dut_dpp_proto_stop_at_initiator_enrollee(dev, frame, result,
fail):
addr = dev[1].own_addr().replace(':', '')
cmd = "DPP_BOOTSTRAP_GEN type=qrcode chan=81/6 mac=" + addr
res = dev[1].request(cmd)
if "FAIL" in res:
raise Exception("Failed to generate bootstrapping info")
id0 = int(res)
uri0 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
cmd = "DPP_LISTEN 2437 role=configurator"
if "OK" not in dev[1].request(cmd):
raise Exception("Failed to start listen operation")
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % uri0.encode('hex'))
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,Enrollee,DPPBS,QR,DPPTimeout,6,DPPStep,Timeout,DPPFrameType,%s" % (frame), timeout=10)
if result not in res:
raise Exception("Unexpected result: " + res)
if fail:
ev = dev[1].wait_event(["DPP-FAIL"], timeout=5)
if ev is None or fail not in ev:
raise Exception("Failure not reported correctly: " + str(ev))
dev[1].request("DPP_STOP_LISTEN")
dev[0].dump_monitor()
dev[1].dump_monitor()
def test_sigma_dut_dpp_proto_stop_at_responder(dev, apdev):
"""sigma_dut DPP protocol testing - Stop at RX on Responder"""
check_dpp_capab(dev[0])
check_dpp_capab(dev[1])
tests = [ ("AuthenticationRequest",
"BootstrapResult,OK,AuthResult,Errorsent",
None),
("AuthenticationConfirm",
"BootstrapResult,OK,AuthResult,Errorsent",
None) ]
for frame, result, fail in tests:
dev[0].request("FLUSH")
dev[1].request("FLUSH")
sigma = start_sigma_dut(dev[0].ifname)
try:
run_sigma_dut_dpp_proto_stop_at_responder(dev, frame, result, fail)
finally:
stop_sigma_dut(sigma)
def run_sigma_dut_dpp_proto_stop_at_responder(dev, frame, result, fail):
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,GetLocalBootstrap,DPPCryptoIdentifier,P-256,DPPBS,QR")
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
hex = res.split(',')[3]
uri = hex.decode('hex')
logger.info("URI from sigma_dut: " + uri)
res = dev[1].request("DPP_QR_CODE " + uri)
if "FAIL" in res:
raise Exception("Failed to parse QR Code URI")
id1 = int(res)
t = threading.Thread(target=dpp_proto_init, args=(dev[1], id1))
t.start()
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Responder,DPPAuthDirection,Single,DPPProvisioningRole,Enrollee,DPPConfIndex,1,DPPSigningKeyECC,P-256,DPPConfEnrolleeRole,STA,DPPBS,QR,DPPTimeout,6,DPPStep,Timeout,DPPFrameType,%s" % (frame), timeout=10)
t.join()
if result not in res:
raise Exception("Unexpected result: " + res)
if fail:
ev = dev[1].wait_event(["DPP-FAIL"], timeout=5)
if ev is None or fail not in ev:
raise Exception("Failure not reported correctly:" + str(ev))
dev[1].request("DPP_STOP_LISTEN")
dev[0].dump_monitor()
dev[1].dump_monitor()
def dpp_proto_init_pkex(dev):
time.sleep(1)
logger.info("Starting DPP PKEX initiator/configurator in a thread")
cmd = "DPP_CONFIGURATOR_ADD"
res = dev.request(cmd);
if "FAIL" in res:
raise Exception("Failed to add configurator")
conf_id = int(res)
cmd = "DPP_BOOTSTRAP_GEN type=pkex"
res = dev.request(cmd)
if "FAIL" in res:
raise Exception("Failed to generate bootstrapping info")
id = int(res)
cmd = "DPP_PKEX_ADD own=%d init=1 conf=sta-dpp configurator=%d code=secret" % (id, conf_id)
if "FAIL" in dev.request(cmd):
raise Exception("Failed to initiate DPP PKEX")
def test_sigma_dut_dpp_proto_initiator_pkex(dev, apdev):
"""sigma_dut DPP protocol testing - Initiator (PKEX)"""
check_dpp_capab(dev[0])
check_dpp_capab(dev[1])
tests = [ ("InvalidValue", "PKEXCRRequest", "WrappedData",
"BootstrapResult,Errorsent",
None),
("MissingAttribute", "PKEXExchangeRequest", "FiniteCyclicGroup",
"BootstrapResult,Errorsent",
"Missing or invalid Finite Cyclic Group attribute"),
("MissingAttribute", "PKEXCRRequest", "BSKey",
"BootstrapResult,Errorsent",
"No valid peer bootstrapping key found") ]
for step, frame, attr, result, fail in tests:
dev[0].request("FLUSH")
dev[1].request("FLUSH")
sigma = start_sigma_dut(dev[0].ifname)
try:
run_sigma_dut_dpp_proto_initiator_pkex(dev, step, frame, attr,
result, fail)
finally:
stop_sigma_dut(sigma)
def run_sigma_dut_dpp_proto_initiator_pkex(dev, step, frame, attr, result, fail):
cmd = "DPP_BOOTSTRAP_GEN type=pkex"
res = dev[1].request(cmd)
if "FAIL" in res:
raise Exception("Failed to generate bootstrapping info")
id1 = int(res)
cmd = "DPP_PKEX_ADD own=%d code=secret" % (id1)
res = dev[1].request(cmd)
if "FAIL" in res:
raise Exception("Failed to set PKEX data (responder)")
cmd = "DPP_LISTEN 2437 role=enrollee"
if "OK" not in dev[1].request(cmd):
raise Exception("Failed to start listen operation")
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,Configurator,DPPConfIndex,1,DPPSigningKeyECC,P-256,DPPConfEnrolleeRole,STA,DPPBS,PKEX,DPPPKEXCode,secret,DPPTimeout,6,DPPStep,%s,DPPFrameType,%s,DPPIEAttribute,%s" % (step, frame, attr))
if result not in res:
raise Exception("Unexpected result: " + res)
if fail:
ev = dev[1].wait_event(["DPP-FAIL"], timeout=5)
if ev is None or fail not in ev:
raise Exception("Failure not reported correctly: " + str(ev))
dev[1].request("DPP_STOP_LISTEN")
dev[0].dump_monitor()
dev[1].dump_monitor()
def test_sigma_dut_dpp_proto_responder_pkex(dev, apdev):
"""sigma_dut DPP protocol testing - Responder (PKEX)"""
check_dpp_capab(dev[0])
check_dpp_capab(dev[1])
tests = [ ("InvalidValue", "PKEXCRResponse", "WrappedData",
"BootstrapResult,Errorsent",
None),
("MissingAttribute", "PKEXExchangeResponse", "DPPStatus",
"BootstrapResult,Errorsent",
"No DPP Status attribute"),
("MissingAttribute", "PKEXCRResponse", "BSKey",
"BootstrapResult,Errorsent",
"No valid peer bootstrapping key found") ]
for step, frame, attr, result, fail in tests:
dev[0].request("FLUSH")
dev[1].request("FLUSH")
sigma = start_sigma_dut(dev[0].ifname)
try:
run_sigma_dut_dpp_proto_responder_pkex(dev, step, frame, attr,
result, fail)
finally:
stop_sigma_dut(sigma)
def run_sigma_dut_dpp_proto_responder_pkex(dev, step, frame, attr, result, fail):
t = threading.Thread(target=dpp_proto_init_pkex, args=(dev[1],))
t.start()
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Responder,DPPAuthDirection,Single,DPPProvisioningRole,Enrollee,DPPConfIndex,1,DPPSigningKeyECC,P-256,DPPConfEnrolleeRole,STA,DPPBS,PKEX,DPPPKEXCode,secret,DPPTimeout,6,DPPStep,%s,DPPFrameType,%s,DPPIEAttribute,%s" % (step, frame, attr), timeout=10)
t.join()
if result not in res:
raise Exception("Unexpected result: " + res)
if fail:
ev = dev[1].wait_event(["DPP-FAIL"], timeout=5)
if ev is None or fail not in ev:
raise Exception("Failure not reported correctly:" + str(ev))
dev[1].request("DPP_STOP_LISTEN")
dev[0].dump_monitor()
dev[1].dump_monitor()
def init_sigma_dut_dpp_proto_peer_disc_req(dev, apdev):
check_dpp_capab(dev[0])
check_dpp_capab(dev[1])
csign = "30770201010420768240a3fc89d6662d9782f120527fe7fb9edc6366ab0b9c7dde96125cfd250fa00a06082a8648ce3d030107a144034200042908e1baf7bf413cc66f9e878a03e8bb1835ba94b033dbe3d6969fc8575d5eb5dfda1cb81c95cee21d0cd7d92ba30541ffa05cb6296f5dd808b0c1c2a83c0708"
csign_pub = "3059301306072a8648ce3d020106082a8648ce3d030107034200042908e1baf7bf413cc66f9e878a03e8bb1835ba94b033dbe3d6969fc8575d5eb5dfda1cb81c95cee21d0cd7d92ba30541ffa05cb6296f5dd808b0c1c2a83c0708"
ap_connector = "eyJ0eXAiOiJkcHBDb24iLCJraWQiOiJwYWtZbXVzd1dCdWpSYTl5OEsweDViaTVrT3VNT3dzZHRlaml2UG55ZHZzIiwiYWxnIjoiRVMyNTYifQ.eyJncm91cHMiOlt7Imdyb3VwSWQiOiIqIiwibmV0Um9sZSI6ImFwIn1dLCJuZXRBY2Nlc3NLZXkiOnsia3R5IjoiRUMiLCJjcnYiOiJQLTI1NiIsIngiOiIybU5vNXZuRkI5bEw3d1VWb1hJbGVPYzBNSEE1QXZKbnpwZXZULVVTYzVNIiwieSI6IlhzS3dqVHJlLTg5WWdpU3pKaG9CN1haeUttTU05OTl3V2ZaSVl0bi01Q3MifX0.XhjFpZgcSa7G2lHy0OCYTvaZFRo5Hyx6b7g7oYyusLC7C_73AJ4_BxEZQVYJXAtDuGvb3dXSkHEKxREP9Q6Qeg"
ap_netaccesskey = "30770201010420ceba752db2ad5200fa7bc565b9c05c69b7eb006751b0b329b0279de1c19ca67ca00a06082a8648ce3d030107a14403420004da6368e6f9c507d94bef0515a1722578e73430703902f267ce97af4fe51273935ec2b08d3adefbcf588224b3261a01ed76722a630cf7df7059f64862d9fee42b"
params = { "ssid": "DPPNET01",
"wpa": "2",
"ieee80211w": "2",
"wpa_key_mgmt": "DPP",
"rsn_pairwise": "CCMP",
"dpp_connector": ap_connector,
"dpp_csign": csign_pub,
"dpp_netaccesskey": ap_netaccesskey }
try:
hapd = hostapd.add_ap(apdev[0], params)
except:
raise HwsimSkip("DPP not supported")
dev[0].set("dpp_config_processing", "2")
cmd = "DPP_CONFIGURATOR_ADD key=" + csign
res = dev[1].request(cmd);
if "FAIL" in res:
raise Exception("Failed to add configurator")
conf_id = int(res)
addr = dev[1].own_addr().replace(':', '')
cmd = "DPP_BOOTSTRAP_GEN type=qrcode chan=81/6 mac=" + addr
res = dev[1].request(cmd)
if "FAIL" in res:
raise Exception("Failed to generate bootstrapping info")
id0 = int(res)
uri0 = dev[1].request("DPP_BOOTSTRAP_GET_URI %d" % id0)
dev[1].set("dpp_configurator_params",
" conf=sta-dpp ssid=%s configurator=%d" % ("DPPNET01".encode("hex"), conf_id));
cmd = "DPP_LISTEN 2437 role=configurator"
if "OK" not in dev[1].request(cmd):
raise Exception("Failed to start listen operation")
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % uri0.encode('hex'))
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
def test_sigma_dut_dpp_proto_peer_disc_req(dev, apdev):
"""sigma_dut DPP protocol testing - Peer Discovery Request"""
sigma = start_sigma_dut(dev[0].ifname)
try:
init_sigma_dut_dpp_proto_peer_disc_req(dev, apdev)
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,Enrollee,DPPBS,QR,DPPTimeout,6,DPPWaitForConnect,Yes,DPPStep,MissingAttribute,DPPFrameType,PeerDiscoveryRequest,DPPIEAttribute,TransactionID", timeout=10)
if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK,NetworkIntroResult,Errorsent" not in res:
raise Exception("Unexpected result: " + res)
finally:
dev[0].set("dpp_config_processing", "0")
stop_sigma_dut(sigma)
def test_sigma_dut_dpp_self_config(dev, apdev):
"""sigma_dut DPP Configurator enrolling an AP and using self-configuration"""
check_dpp_capab(dev[0])
hapd = hostapd.add_ap(apdev[0], { "ssid": "unconfigured" })
check_dpp_capab(hapd)
sigma = start_sigma_dut(dev[0].ifname)
try:
dev[0].set("dpp_config_processing", "2")
addr = hapd.own_addr().replace(':', '')
cmd = "DPP_BOOTSTRAP_GEN type=qrcode chan=81/1 mac=" + addr
res = hapd.request(cmd)
if "FAIL" in res:
raise Exception("Failed to generate bootstrapping info")
id = int(res)
uri = hapd.request("DPP_BOOTSTRAP_GET_URI %d" % id)
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % uri.encode('hex'))
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,Configurator,DPPConfIndex,1,DPPSigningKeyECC,P-256,DPPConfEnrolleeRole,AP,DPPBS,QR,DPPTimeout,6")
if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
raise Exception("Unexpected result: " + res)
update_hapd_config(hapd)
cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPCryptoIdentifier,P-256,DPPBS,QR,DPPAuthRole,Initiator,DPPProvisioningRole,Configurator,DPPAuthDirection,Single,DPPConfIndex,1,DPPTimeout,6,DPPWaitForConnect,Yes,DPPSelfConfigure,Yes"
res = sigma_dut_cmd(cmd, timeout=10)
if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK,NetworkIntroResult,OK,NetworkConnectResult,OK" not in res:
raise Exception("Unexpected result: " + res)
finally:
stop_sigma_dut(sigma)
dev[0].set("dpp_config_processing", "0")
def test_sigma_dut_ap_dpp_self_config(dev, apdev, params):
"""sigma_dut DPP AP Configurator using self-configuration"""
logdir = os.path.join(params['logdir'],
"sigma_dut_ap_dpp_self_config.sigma-hostapd")
with HWSimRadio() as (radio, iface):
sigma = start_sigma_dut(iface, hostapd_logdir=logdir)
try:
run_sigma_dut_ap_dpp_self_config(dev, apdev)
finally:
stop_sigma_dut(sigma)
dev[0].set("dpp_config_processing", "0")
def run_sigma_dut_ap_dpp_self_config(dev, apdev):
check_dpp_capab(dev[0])
sigma_dut_cmd_check("ap_reset_default,program,DPP")
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,Configurator,DPPConfEnrolleeRole,AP,DPPBS,QR,DPPConfIndex,1,DPPSelfConfigure,Yes,DPPTimeout,6", timeout=10)
if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
raise Exception("Unexpected result: " + res)
dev[0].set("dpp_config_processing", "2")
addr = dev[0].own_addr().replace(':', '')
cmd = "DPP_BOOTSTRAP_GEN type=qrcode chan=81/11 mac=" + addr
res = dev[0].request(cmd)
if "FAIL" in res:
raise Exception("Failed to generate bootstrapping info")
id = int(res)
uri = dev[0].request("DPP_BOOTSTRAP_GET_URI %d" % id)
cmd = "DPP_LISTEN 2462 role=enrollee"
if "OK" not in dev[0].request(cmd):
raise Exception("Failed to start listen operation")
res = sigma_dut_cmd("dev_exec_action,program,DPP,DPPActionType,SetPeerBootstrap,DPPBootstrappingdata,%s,DPPBS,QR" % uri.encode('hex'))
if "status,COMPLETE" not in res:
raise Exception("dev_exec_action did not succeed: " + res)
cmd = "dev_exec_action,program,DPP,DPPActionType,AutomaticDPP,DPPAuthRole,Initiator,DPPAuthDirection,Single,DPPProvisioningRole,Configurator,DPPConfIndex,1,DPPSigningKeyECC,P-256,DPPConfEnrolleeRole,STA,DPPBS,QR,DPPTimeout,6"
res = sigma_dut_cmd(cmd)
if "BootstrapResult,OK,AuthResult,OK,ConfResult,OK" not in res:
raise Exception("Unexpected result: " + res)
dev[0].wait_connected()
dev[0].request("DISCONNECT")
dev[0].wait_disconnected()
sigma_dut_cmd_check("ap_reset_default")
def test_sigma_dut_preconfigured_profile(dev, apdev):
"""sigma_dut controlled connection using preconfigured profile"""
try:
run_sigma_dut_preconfigured_profile(dev, apdev)
finally:
dev[0].set("ignore_old_scan_res", "0")
def run_sigma_dut_preconfigured_profile(dev, apdev):
ifname = dev[0].ifname
sigma = start_sigma_dut(ifname)
params = hostapd.wpa2_params(ssid="test-psk", passphrase="12345678")
hapd = hostapd.add_ap(apdev[0], params)
dev[0].connect("test-psk", psk="12345678", scan_freq="2412",
only_add_network=True)
sigma_dut_cmd_check("sta_set_ip_config,interface,%s,dhcp,0,ip,127.0.0.11,mask,255.255.255.0" % ifname)
sigma_dut_cmd_check("sta_associate,interface,%s,ssid,%s" % (ifname, "test-psk"))
sigma_dut_wait_connected(ifname)
sigma_dut_cmd_check("sta_get_ip_config,interface," + ifname)
sigma_dut_cmd_check("sta_disconnect,interface," + ifname)
sigma_dut_cmd_check("sta_reset_default,interface," + ifname)
stop_sigma_dut(sigma)
def test_sigma_dut_wps_pbc(dev, apdev):
"""sigma_dut and WPS PBC Enrollee"""
try:
run_sigma_dut_wps_pbc(dev, apdev)
finally:
dev[0].set("ignore_old_scan_res", "0")
def run_sigma_dut_wps_pbc(dev, apdev):
ssid = "test-wps-conf"
hapd = hostapd.add_ap(apdev[0],
{ "ssid": "wps", "eap_server": "1", "wps_state": "2",
"wpa_passphrase": "12345678", "wpa": "2",
"wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP" })
hapd.request("WPS_PBC")
ifname = dev[0].ifname
sigma = start_sigma_dut(ifname)
cmd = "start_wps_registration,interface,%s" % ifname
cmd += ",WpsRole,Enrollee"
cmd += ",WpsConfigMethod,PBC"
sigma_dut_cmd_check(cmd, timeout=15)
sigma_dut_cmd_check("sta_disconnect,interface," + ifname)
hapd.disable()
sigma_dut_cmd_check("sta_reset_default,interface," + ifname)
stop_sigma_dut(sigma)
dev[0].flush_scan_cache()
def test_sigma_dut_sta_scan_bss(dev, apdev):
"""sigma_dut sta_scan_bss"""
hapd = hostapd.add_ap(apdev[0], { "ssid": "test" })
sigma = start_sigma_dut(dev[0].ifname)
try:
cmd = "sta_scan_bss,Interface,%s,BSSID,%s" % (dev[0].ifname, \
hapd.own_addr())
res = sigma_dut_cmd(cmd, timeout=10)
if "ssid,test,bsschannel,1" not in res:
raise Exception("Unexpected result: " + res)
finally:
stop_sigma_dut(sigma)
|
lankadeepa.py | import tweepy
import os
import time
import threading
from elasticsearch import Elasticsearch, helpers
from datetime import datetime
from dotenv import load_dotenv
load_dotenv()
consumer_key = os.getenv('consumer_key')
consumer_secret = os.getenv('consumer_secret')
access_key = os.getenv('access_key')
access_secret = os.getenv('access_secret')
es = Elasticsearch([{'host': 'localhost', 'port': 9200}])
es.indices.create(index='twitter_index', ignore=400)
def get_all_tweets(screen_name):
# authorize twitter, initialize tweepy
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)
# initialize a list to hold all the tweepy Tweets
alltweets = []
# make initial request for most recent tweets (200 is the maximum allowed count)
new_tweets = api.user_timeline(screen_name=screen_name, count=200)
# save most recent tweets
alltweets.extend(new_tweets)
# save the id of the oldest tweet less one
oldest = alltweets[-1].id - 1
# keep grabbing tweets until there are no tweets left to grab
while len(new_tweets) > 0:
#print
#"getting tweets before %s" % (oldest)
# all subsiquent requests use the max_id param to prevent duplicates
new_tweets = api.user_timeline(screen_name=screen_name, count=200, max_id=oldest)
# save most recent tweets
alltweets.extend(new_tweets)
# update the id of the oldest tweet less one
oldest = alltweets[-1].id - 1
#print
#"...%s tweets downloaded so far" % (len(alltweets))
outtweets = [{'ID': tweet.id_str, 'Text': tweet.text, 'Date': tweet.created_at, 'author': tweet.user.screen_name} for tweet in alltweets]
def save_es(outtweets, es): # Peps8 convention
data = [ # Please without s in data
{
"_index": "twitter_index",
"_type": "LankadeepaNews",
"_id": index,
"_source": ID
}
for index, ID in enumerate(outtweets)
]
helpers.bulk(es, data)
save_es(outtweets, es)
print('Run at:')
print(datetime.now())
print("\n")
if __name__ == '__main__':
# pass in the username of the account you want to download
get_all_tweets("LankadeepaNews")
if __name__ == "__main__":
time.sleep(60)
while True:
thr = threading.Thread(target=get_all_tweets("LankadeepaNews"))
thr.start()
time.sleep(3600) # do work every one hour
|
commanding.py | #A* -------------------------------------------------------------------
#B* This file contains source code for the PyMOL computer program
#C* Copyright (c) Schrodinger, LLC.
#D* -------------------------------------------------------------------
#E* It is unlawful to modify or remove this copyright notice.
#F* -------------------------------------------------------------------
#G* Please see the accompanying LICENSE file for further information.
#H* -------------------------------------------------------------------
#I* Additional authors of this source file include:
#-*
#-*
#-*
#Z* -------------------------------------------------------------------
from __future__ import print_function, absolute_import
if __name__=='pymol.commanding':
import sys
if sys.version_info[0] == 2:
import thread
import urllib2
else:
import _thread as thread
import urllib.request as urllib2
from io import FileIO as file
import re
import os
import time
import threading
import traceback
from . import parsing
cmd = sys.modules["pymol.cmd"]
import pymol
from .cmd import _cmd, Shortcut, QuietException, \
fb_module, fb_mask, is_list, \
DEFAULT_ERROR, DEFAULT_SUCCESS, is_ok, is_error, is_string
def resume(filename, _self=cmd):
'''
DESCRIPTION
"resume" executes a log file and opens it for recording of
additional commands.
USAGE
resume filename
SEE ALSO
log, log_close
'''
r = DEFAULT_ERROR
if os.path.exists(filename):
if(re.search(r"\.py$|\.PY$|\.pym$|.PYM$",filename)):
r = _self.do("run %s"%filename)
else:
r = _self.do("@%s"%filename)
if is_ok(r):
r = _self.do("log_open %s,a"%filename)
if _self._raising(r,_self): raise pymol.CmdException
return r
class QueueFile:
def __init__(self,queue):
self.queue = queue
def write(self,command):
self.queue.put(command)
def flush(self):
pass
def close(self):
del self.queue
re_fetch = re.compile(r'(\bfetch\s+\w[^;\r\n\'"]+)')
class LogFile(file):
def _append_async0(self, m):
s = m.group()
if 'async' in s:
return s
return s.rstrip(',') + ', async=0'
def write(self, s):
s = re_fetch.sub(self._append_async0, s)
file.write(self, s.encode())
def log_open(filename='log.pml', mode='w', _self=cmd):
'''
DESCRIPTION
"log_open" opens a log file for writing.
USAGE
log_open filename
SEE ALSO
log, log_close
'''
pymol=_self._pymol
if not is_string(filename): # we're logging to Queue, not a file.
pymol._log_file = QueueFile(filename)
_self.set("logging",1,quiet=1)
else:
try:
try:
if hasattr(pymol,"_log_file"):
if pymol._log_file!=None:
pymol._log_file.close()
del pymol._log_file
except:
pass
pymol._log_file = LogFile(filename,mode)
if _self._feedback(fb_module.cmd,fb_mask.details): # redundant
if mode!='a':
print(" Cmd: logging to '%s'."%filename)
else:
print(" Cmd: appending to '%s'."%filename)
if mode=='a':
pymol._log_file.write("\n") # always start on a new line
if(re.search(r"\.py$|\.PY$|\.pym$|\.PYM$",filename)):
_self.set("logging",2,quiet=1)
else:
_self.set("logging",1,quiet=1)
except:
print("Error: unable to open log file '%s'"%filename)
pymol._log_file = None
_self.set("logging",0,quiet=1)
traceback.print_exc()
raise QuietException
def log(text, alt_text=None, _self=cmd):
'''
DESCRIPTION
"log" writes a command to the log file (if one is open).
`text` and/or `alt_text` must include the terminating line feed.
ARGUMENTS
text = str: PyMOL command (optional if alt_text is given)
alt_text = str: Python expression (optional)
SEE ALSO
log_open, log_close
'''
# See also equivalent C impelemtation: PLog
log_file = getattr(_self._pymol, "_log_file", None)
if log_file is None:
return
mode = _self.get_setting_int("logging")
if mode == 1:
# .pml
if not text and alt_text:
text = '/' + alt_text
elif mode == 2:
# .py
if alt_text:
text = alt_text
elif text.startswith('/'):
text = text[1:]
else:
text = "cmd.do(" + repr(text.strip()) + ")\n"
else:
return
if text:
log_file.write(text)
log_file.flush()
def log_close(_self=cmd):
'''
DESCRIPTION
"log_close" closes the current log file (if one is open).
USAGE
log_close
SEE ALSO
log, log_open
'''
pymol=_self._pymol
cmd=_self
if hasattr(pymol,"_log_file"):
if pymol._log_file!=None:
pymol._log_file.close()
del pymol._log_file
_self.set("logging",0,quiet=1)
if _self._feedback(fb_module.cmd,fb_mask.details): # redundant
print(" Cmd: log closed.")
def cls(_self=cmd):
'''
DESCRIPTION
"cls" clears the output buffer.
USAGE
cls
'''
r = DEFAULT_ERROR
try:
_self.lock(_self)
r = _cmd.cls(_self._COb)
finally:
_self.unlock(r,_self)
if _self._raising(r,_self): raise pymol.CmdException
return r
def _load_splash_image(filename, url, _self=cmd):
import tempfile
import struct
tmp_filename = ""
contents = None
if url:
try:
handle = urllib2.urlopen(url)
contents = handle.read()
handle.close()
# png magic number
if contents[:4] != b'\x89\x50\x4e\x47':
raise IOError
shape = struct.unpack('>II', contents[16:24])
tmp_filename = tempfile.mktemp('.png')
with open(tmp_filename, 'wb') as handle:
handle.write(contents)
filename = tmp_filename
except IOError:
pass
if os.path.exists(filename) and not _self.get_names():
# hide text splash
print()
# fit window to image
try:
if not contents:
contents = open(filename, 'rb').read(24)
shape = struct.unpack('>II', contents[16:24])
scale = _self.get_setting_int('display_scale_factor')
_self.viewport(shape[0] * scale, shape[1] * scale)
except Exception as e:
print(e)
# load image
_self.load_png(filename, 0, quiet=1)
if tmp_filename:
os.unlink(tmp_filename)
def splash(mode=0, _self=cmd):
cmd=_self
'''
DESCRIPTION
"splash" shows the splash screen information.
USAGE
splash
'''
r = DEFAULT_ERROR
mode = int(mode)
if mode == 2: # query
try:
_self.lock(_self)
r = _cmd.splash(_self._COb,1)
finally:
_self.unlock(0,_self)
elif mode == 1: # just show PNG
show_splash = 1
try:
_self.lock(_self)
show_splash = _cmd.splash(_self._COb,1)
finally:
_self.unlock(0,_self)
r = DEFAULT_SUCCESS
png_url = ""
if show_splash==1: # generic / open-source
png_path = _self.exp_path("$PYMOL_DATA/pymol/splash.png")
elif show_splash==2: # evaluation builds
png_path = _self.exp_path("$PYMOL_DATA/pymol/epymol.png")
elif show_splash==3: # edu builds
png_path = _self.exp_path("$PYMOL_DATA/pymol/splash_edu.png")
png_url = "http://pymol.org/splash/splash_edu_2.png"
else: # incentive builds
png_path = _self.exp_path("$PYMOL_DATA/pymol/ipymol.png")
t = threading.Thread(target=_load_splash_image, args=(png_path, png_url, _self))
t.setDaemon(1)
t.start()
else:
if _self.get_setting_int("internal_feedback") > 0:
_self.set("text","1",quiet=1)
print()
try:
_self.lock(_self)
r = _cmd.splash(_self._COb,0)
finally:
_self.unlock(r,_self)
if _self._raising(r,_self): raise pymol.CmdException
return r
reinit_code = {
'everything' : 0,
'settings' : 1,
'store_defaults' : 2,
'original_settings' : 3,
'purge_defaults' : 4,
}
reinit_sc = Shortcut(reinit_code.keys())
def reinitialize(what='everything', object='', _self=cmd):
'''
DESCRIPTION
"reinitialize" reinitializes the program by deleting all objects
and restoring the default program settings.
USAGE
reinitialize
'''
r = DEFAULT_ERROR
what = reinit_code[reinit_sc.auto_err(str(what),'option')]
try:
_self.lock(_self)
r = _cmd.reinitialize(_self._COb,int(what),str(object))
finally:
_self.unlock(r,_self)
if _self._raising(r,_self): raise pymol.CmdException
return r
def sync(timeout=1.0,poll=0.05,_self=cmd):
'''
DESCRIPTION
"sync" is an API-only function which waits until all current
commmands have been executed before returning. A timeout
can be used to insure that this command eventually returns.
PYMOL API
cmd.sync(float timeout=1.0,float poll=0.05)
SEE ALSO
frame
'''
for t in async_threads:
t.join()
now = time.time()
timeout = float(timeout)
poll = float(poll)
# first, make sure there aren't any commands waiting...
if _cmd.wait_queue(_self._COb): # commands waiting to be executed?
while 1:
if not _cmd.wait_queue(_self._COb):
break
e = threading.Event() # using this for portable delay
e.wait(poll)
del e
if (timeout>=0.0) and ((time.time()-now)>timeout):
break
if _cmd.wait_deferred(_self._COb):
# deferred tasks waiting for a display event?
if thread.get_ident() == pymol.glutThread:
_self.refresh()
else:
while 1:
if not _cmd.wait_queue(_self._COb):
break
e = threading.Event() # using this for portable delay
e.wait(poll)
del e
if (timeout>=0.0) and ((time.time()-now)>timeout):
break
# then make sure we can grab the API
while 1:
if _self.lock_attempt(_self):
_self.unlock(_self)
break
e = threading.Event() # using this for portable delay
e.wait(poll)
del e
if (timeout>=0.0) and ((time.time()-now)>timeout):
break
def do(commands,log=1,echo=1,flush=0,_self=cmd):
# WARNING: don't call this routine if you already have the API lock
# use cmd._do instead
'''
DESCRIPTION
"do" makes it possible for python programs to issue simple PyMOL
commands as if they were entered on the command line.
PYMOL API
cmd.do( commands )
USAGE (PYTHON)
from pymol import cmd
cmd.do("load file.pdb")
'''
r = DEFAULT_SUCCESS
log = int(log)
if is_list(commands):
cmmd_list = commands
else:
cmmd_list = [ commands ]
n_cmmd = len(cmmd_list)
if n_cmmd>1: # if processing a list of commands, defer updates
defer = _self.get_setting_int("defer_updates")
_self.set('defer_updates',1)
for cmmd in cmmd_list:
lst = cmmd.splitlines()
if len(lst)<2:
for a in lst:
if(len(a)):
try:
_self.lock(_self)
r = _cmd.do(_self._COb,a,log,echo)
finally:
_self.unlock(r,_self)
else:
try:
_self.lock(_self)
do_flush = flush or ((thread.get_ident() == _self._pymol.glutThread)
and _self.lock_api_allow_flush)
for a in lst:
if len(a):
r = _cmd.do(_self._COb,a,log,echo)
if do_flush:
_self.unlock(r,_self) # flushes
_self.lock(_self)
finally:
_self.unlock(r,_self)
if n_cmmd>1:
_self.set('defer_updates',defer)
if _self._raising(r,_self): raise pymol.CmdException
return r
def quit(code=0, _self=cmd):
'''
DESCRIPTION
"quit" terminates the program.
USAGE
quit [code]
ARGUMENTS
code = int: exit the application with status "code" {default: 0}
PYMOL API
cmd.quit(int code)
'''
code = int(code)
if thread.get_ident() == pymol.glutThread:
_self._quit(code, _self)
else:
try:
_self.lock(_self)
_cmd.do(_self._COb,"_ time.sleep(0.100);cmd._quit(%d)" % (code),0,0)
# allow time for a graceful exit from the calling thread
try:
thread.exit()
except SystemExit:
pass
finally:
_self.unlock(-1,_self=_self)
return None
def delete(name,_self=cmd):
'''
DESCRIPTION
"delete" removes objects and named selections
USAGE
delete name
ARGUMENTS
name = name(s) of object(s) or selection(s), supports wildcards (*)
EXAMPLES
delete measure* # delete all objects which names start with "measure"
delete all # delete all objects and selections
PYMOL API
cmd.delete (string name = object-or-selection-name )
SEE ALSO
remove
'''
r = DEFAULT_ERROR
try:
_self.lock(_self)
r = _cmd.delete(_self._COb,str(name))
finally:
_self.unlock(r,_self)
if _self._raising(r,_self): raise pymol.CmdException
return r
def extend(name, function=None, _self=cmd):
'''
DESCRIPTION
"extend" is an API-only function which binds a new external
function as a command into the PyMOL scripting language.
PYMOL API
cmd.extend(string name,function function)
PYTHON EXAMPLE
def foo(moo=2): print moo
cmd.extend('foo',foo)
The following would now work within PyMOL:
PyMOL>foo
2
PyMOL>foo 3
3
PyMOL>foo moo=5
5
PyMOL>foo ?
Usage: foo [ moo ]
NOTES
For security reasons, new PyMOL commands created using "extend" are
not saved or restored in sessions.
SEE ALSO
alias, api
'''
if function is None:
name, function = name.__name__, name
_self.keyword[name] = [function, 0,0,',',parsing.STRICT]
_self.kwhash.append(name)
_self.help_sc.append(name)
return function
# for aliasing compound commands to a single keyword
def extendaa(*arg, **kw):
'''
DESCRIPTION
API-only function to decorate a function as a PyMOL command with
argument auto-completion.
EXAMPLE
@cmd.extendaa(cmd.auto_arg[0]['zoom'])
def zoom_organic(selection='*'):
cmd.zoom('organic & (%s)' % selection)
'''
_self = kw.get('_self', cmd)
auto_arg = _self.auto_arg
def wrapper(func):
name = func.__name__
_self.extend(name, func)
for (i, aa) in enumerate(arg):
if i == len(auto_arg):
auto_arg.append({})
if aa is not None:
auto_arg[i][name] = aa
return func
return wrapper
def alias(name, command, _self=cmd):
'''
DESCRIPTION
"alias" binds routinely-used command inputs to a new command
keyword.
USAGE
alias name, command
ARGUMENTS
name = string: new keyword
command = string: literal input with commands separated by semicolons.
EXAMPLE
alias my_scene, hide; show ribbon, polymer; show sticks, organic; show nonbonded, solvent
my_scene
NOTES
For security reasons, aliased commands are not saved or restored
in sessions.
SEE ALSO
cmd.extend, api
'''
_self.keyword[name] = [eval("lambda :do('''%s ''')"%command.replace("'''","")),
0,0,',',parsing.STRICT]
_self.kwhash.append(name)
async_threads = []
def async_(func, *args, **kwargs):
'''
DESCRIPTION
Run function threaded and show "please wait..." message.
'''
from .wizard.message import Message
_self = kwargs.pop('_self', cmd)
wiz = Message(['please wait ...'], dismiss=0, _self=_self)
try:
_self.set_wizard(wiz)
except:
wiz = None
if isinstance(func, str):
func = _self.keyword[func][0]
def wrapper():
async_threads.append(t)
try:
func(*args, **kwargs)
except (pymol.CmdException, cmd.QuietException) as e:
if e.args:
print(e)
finally:
if wiz is not None:
try:
_self.set_wizard_stack([w
for w in _self.get_wizard_stack() if w != wiz])
except:
_self.do('_ wizard')
else:
_self.refresh_wizard()
async_threads.remove(t)
t = threading.Thread(target=wrapper)
t.setDaemon(1)
t.start()
|
fifo_queue_test.py | # Copyright 2015 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 by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for tensorflow.ops.data_flow_ops.FIFOQueue."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import random
import re
import time
import numpy as np
from six.moves import xrange # pylint: disable=redefined-builtin
import tensorflow as tf
class FIFOQueueTest(tf.test.TestCase):
def testConstructor(self):
with tf.Graph().as_default():
q = tf.FIFOQueue(10, tf.float32, name="Q")
self.assertTrue(isinstance(q.queue_ref, tf.Tensor))
self.assertEquals(tf.string_ref, q.queue_ref.dtype)
self.assertProtoEquals("""
name:'Q' op:'FIFOQueue'
attr { key: 'component_types' value { list { type: DT_FLOAT } } }
attr { key: 'shapes' value { list {} } }
attr { key: 'capacity' value { i: 10 } }
attr { key: 'container' value { s: '' } }
attr { key: 'shared_name' value { s: '' } }
""", q.queue_ref.op.node_def)
def testMultiQueueConstructor(self):
with tf.Graph().as_default():
q = tf.FIFOQueue(5, (tf.int32, tf.float32), shared_name="foo", name="Q")
self.assertTrue(isinstance(q.queue_ref, tf.Tensor))
self.assertEquals(tf.string_ref, q.queue_ref.dtype)
self.assertProtoEquals("""
name:'Q' op:'FIFOQueue'
attr { key: 'component_types' value { list {
type: DT_INT32 type : DT_FLOAT
} } }
attr { key: 'shapes' value { list {} } }
attr { key: 'capacity' value { i: 5 } }
attr { key: 'container' value { s: '' } }
attr { key: 'shared_name' value { s: 'foo' } }
""", q.queue_ref.op.node_def)
def testConstructorWithShapes(self):
with tf.Graph().as_default():
q = tf.FIFOQueue(5, (tf.int32, tf.float32),
shapes=(tf.TensorShape([1, 1, 2, 3]),
tf.TensorShape([5, 8])), name="Q")
self.assertTrue(isinstance(q.queue_ref, tf.Tensor))
self.assertEquals(tf.string_ref, q.queue_ref.dtype)
self.assertProtoEquals("""
name:'Q' op:'FIFOQueue'
attr { key: 'component_types' value { list {
type: DT_INT32 type : DT_FLOAT
} } }
attr { key: 'shapes' value { list {
shape { dim { size: 1 }
dim { size: 1 }
dim { size: 2 }
dim { size: 3 } }
shape { dim { size: 5 }
dim { size: 8 } }
} } }
attr { key: 'capacity' value { i: 5 } }
attr { key: 'container' value { s: '' } }
attr { key: 'shared_name' value { s: '' } }
""", q.queue_ref.op.node_def)
def testEnqueue(self):
with self.test_session():
q = tf.FIFOQueue(10, tf.float32)
enqueue_op = q.enqueue((10.0,))
enqueue_op.run()
def testEnqueueWithShape(self):
with self.test_session():
q = tf.FIFOQueue(10, tf.float32, shapes=(3, 2))
enqueue_correct_op = q.enqueue(([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]],))
enqueue_correct_op.run()
with self.assertRaises(ValueError):
q.enqueue(([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]],))
self.assertEqual(1, q.size().eval())
def testEnqueueManyWithShape(self):
with self.test_session():
q = tf.FIFOQueue(10, [tf.int32, tf.int32],
shapes=[(), (2,)])
q.enqueue_many([[1, 2, 3, 4], [[1, 1], [2, 2], [3, 3], [4, 4]]]).run()
self.assertEqual(4, q.size().eval())
def testEnqueueDictWithoutNames(self):
with self.test_session():
q = tf.FIFOQueue(10, tf.float32)
with self.assertRaisesRegexp(ValueError, "must have names"):
q.enqueue({"a": 12.0})
with self.assertRaisesRegexp(ValueError, "must have names"):
q.enqueue_many({"a": [12.0, 13.0]})
def testParallelEnqueue(self):
with self.test_session() as sess:
q = tf.FIFOQueue(10, tf.float32)
elems = [10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0]
enqueue_ops = [q.enqueue((x,)) for x in elems]
dequeued_t = q.dequeue()
# Run one producer thread for each element in elems.
def enqueue(enqueue_op):
sess.run(enqueue_op)
threads = [self.checkedThread(target=enqueue, args=(e,))
for e in enqueue_ops]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
# Dequeue every element using a single thread.
results = []
for _ in xrange(len(elems)):
results.append(dequeued_t.eval())
self.assertItemsEqual(elems, results)
def testParallelDequeue(self):
with self.test_session() as sess:
q = tf.FIFOQueue(10, tf.float32)
elems = [10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0]
enqueue_ops = [q.enqueue((x,)) for x in elems]
dequeued_t = q.dequeue()
# Enqueue every element using a single thread.
for enqueue_op in enqueue_ops:
enqueue_op.run()
# Run one consumer thread for each element in elems.
results = []
def dequeue():
results.append(sess.run(dequeued_t))
threads = [self.checkedThread(target=dequeue) for _ in enqueue_ops]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
self.assertItemsEqual(elems, results)
def testDequeue(self):
with self.test_session():
q = tf.FIFOQueue(10, tf.float32)
elems = [10.0, 20.0, 30.0]
enqueue_ops = [q.enqueue((x,)) for x in elems]
dequeued_t = q.dequeue()
for enqueue_op in enqueue_ops:
enqueue_op.run()
for i in xrange(len(elems)):
vals = dequeued_t.eval()
self.assertEqual([elems[i]], vals)
def testEnqueueAndBlockingDequeue(self):
with self.test_session() as sess:
q = tf.FIFOQueue(3, tf.float32)
elems = [10.0, 20.0, 30.0]
enqueue_ops = [q.enqueue((x,)) for x in elems]
dequeued_t = q.dequeue()
def enqueue():
# The enqueue_ops should run after the dequeue op has blocked.
# TODO(mrry): Figure out how to do this without sleeping.
time.sleep(0.1)
for enqueue_op in enqueue_ops:
sess.run(enqueue_op)
results = []
def dequeue():
for _ in xrange(len(elems)):
results.append(sess.run(dequeued_t))
enqueue_thread = self.checkedThread(target=enqueue)
dequeue_thread = self.checkedThread(target=dequeue)
enqueue_thread.start()
dequeue_thread.start()
enqueue_thread.join()
dequeue_thread.join()
for elem, result in zip(elems, results):
self.assertEqual([elem], result)
def testMultiEnqueueAndDequeue(self):
with self.test_session() as sess:
q = tf.FIFOQueue(10, (tf.int32, tf.float32))
elems = [(5, 10.0), (10, 20.0), (15, 30.0)]
enqueue_ops = [q.enqueue((x, y)) for x, y in elems]
dequeued_t = q.dequeue()
for enqueue_op in enqueue_ops:
enqueue_op.run()
for i in xrange(len(elems)):
x_val, y_val = sess.run(dequeued_t)
x, y = elems[i]
self.assertEqual([x], x_val)
self.assertEqual([y], y_val)
def testQueueSizeEmpty(self):
with self.test_session():
q = tf.FIFOQueue(10, tf.float32)
self.assertEqual([0], q.size().eval())
def testQueueSizeAfterEnqueueAndDequeue(self):
with self.test_session():
q = tf.FIFOQueue(10, tf.float32)
enqueue_op = q.enqueue((10.0,))
dequeued_t = q.dequeue()
size = q.size()
self.assertEqual([], size.get_shape())
enqueue_op.run()
self.assertEqual(1, size.eval())
dequeued_t.op.run()
self.assertEqual(0, size.eval())
def testEnqueueMany(self):
with self.test_session():
q = tf.FIFOQueue(10, tf.float32)
elems = [10.0, 20.0, 30.0, 40.0]
enqueue_op = q.enqueue_many((elems,))
dequeued_t = q.dequeue()
enqueue_op.run()
enqueue_op.run()
for i in range(8):
vals = dequeued_t.eval()
self.assertEqual([elems[i % 4]], vals)
def testEmptyEnqueueMany(self):
with self.test_session():
q = tf.FIFOQueue(10, tf.float32)
empty_t = tf.constant([], dtype=tf.float32,
shape=[0, 2, 3])
enqueue_op = q.enqueue_many((empty_t,))
size_t = q.size()
self.assertEqual([0], size_t.eval())
enqueue_op.run()
self.assertEqual([0], size_t.eval())
def testEmptyDequeueMany(self):
with self.test_session():
q = tf.FIFOQueue(10, tf.float32, shapes=())
enqueue_op = q.enqueue((10.0,))
dequeued_t = q.dequeue_many(0)
self.assertEqual([], dequeued_t.eval().tolist())
enqueue_op.run()
self.assertEqual([], dequeued_t.eval().tolist())
def testEmptyDequeueManyWithNoShape(self):
with self.test_session():
q = tf.FIFOQueue(10, tf.float32)
# Expect the operation to fail due to the shape not being constrained.
with self.assertRaisesOpError("specified shapes"):
q.dequeue_many(0).eval()
def testMultiEnqueueMany(self):
with self.test_session() as sess:
q = tf.FIFOQueue(10, (tf.float32, tf.int32))
float_elems = [10.0, 20.0, 30.0, 40.0]
int_elems = [[1, 2], [3, 4], [5, 6], [7, 8]]
enqueue_op = q.enqueue_many((float_elems, int_elems))
dequeued_t = q.dequeue()
enqueue_op.run()
enqueue_op.run()
for i in range(8):
float_val, int_val = sess.run(dequeued_t)
self.assertEqual(float_elems[i % 4], float_val)
self.assertAllEqual(int_elems[i % 4], int_val)
def testDequeueMany(self):
with self.test_session():
q = tf.FIFOQueue(10, tf.float32, ())
elems = [10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0]
enqueue_op = q.enqueue_many((elems,))
dequeued_t = q.dequeue_many(4)
enqueue_op.run()
self.assertAllEqual(elems[0:4], dequeued_t.eval())
self.assertAllEqual(elems[4:8], dequeued_t.eval())
def testMultiDequeueMany(self):
with self.test_session() as sess:
q = tf.FIFOQueue(10, (tf.float32, tf.int32),
shapes=((), (2,)))
float_elems = [
10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0]
int_elems = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10],
[11, 12], [13, 14], [15, 16], [17, 18], [19, 20]]
enqueue_op = q.enqueue_many((float_elems, int_elems))
dequeued_t = q.dequeue_many(4)
dequeued_single_t = q.dequeue()
enqueue_op.run()
float_val, int_val = sess.run(dequeued_t)
self.assertAllEqual(float_elems[0:4], float_val)
self.assertAllEqual(int_elems[0:4], int_val)
self.assertEqual(float_val.shape, dequeued_t[0].get_shape())
self.assertEqual(int_val.shape, dequeued_t[1].get_shape())
float_val, int_val = sess.run(dequeued_t)
self.assertAllEqual(float_elems[4:8], float_val)
self.assertAllEqual(int_elems[4:8], int_val)
float_val, int_val = sess.run(dequeued_single_t)
self.assertAllEqual(float_elems[8], float_val)
self.assertAllEqual(int_elems[8], int_val)
self.assertEqual(float_val.shape, dequeued_single_t[0].get_shape())
self.assertEqual(int_val.shape, dequeued_single_t[1].get_shape())
def testHighDimension(self):
with self.test_session():
q = tf.FIFOQueue(10, tf.int32, (4, 4, 4, 4))
elems = np.array([[[[[x] * 4] * 4] * 4] * 4 for x in range(10)], np.int32)
enqueue_op = q.enqueue_many((elems,))
dequeued_t = q.dequeue_many(10)
enqueue_op.run()
self.assertAllEqual(dequeued_t.eval(), elems)
def testEnqueueWrongShape(self):
q = tf.FIFOQueue(10, (tf.int32, tf.int32), ((), (2)))
with self.assertRaises(ValueError):
q.enqueue(([1, 2], [2, 2]))
with self.assertRaises(ValueError):
q.enqueue_many((7, [[1, 2], [3, 4], [5, 6]]))
def testBatchSizeMismatch(self):
q = tf.FIFOQueue(10, (tf.int32, tf.int32, tf.int32), ((), (), ()))
with self.assertRaises(ValueError):
q.enqueue_many(([1, 2, 3], [1, 2], [1, 2, 3]))
with self.assertRaises(ValueError):
q.enqueue_many(([1, 2, 3], [1, 2], tf.placeholder(tf.int32)))
with self.assertRaises(ValueError):
q.enqueue_many((tf.placeholder(tf.int32), [1, 2], [1, 2, 3]))
def testEnqueueManyEmptyTypeConversion(self):
q = tf.FIFOQueue(10, (tf.int32, tf.float32), ((), ()))
enq = q.enqueue_many(([], []))
self.assertEqual(tf.int32, enq.inputs[1].dtype)
self.assertEqual(tf.float32, enq.inputs[2].dtype)
def testEnqueueWrongType(self):
q = tf.FIFOQueue(10, (tf.int32, tf.float32), ((), ()))
with self.assertRaises(ValueError):
q.enqueue((tf.placeholder(tf.int32), tf.placeholder(tf.int32)))
with self.assertRaises(ValueError):
q.enqueue_many((tf.placeholder(tf.int32), tf.placeholder(tf.int32)))
def testEnqueueWrongShapeAtRuntime(self):
with self.test_session() as sess:
q = tf.FIFOQueue(10, (tf.int32, tf.int32), ((2, 2), (3, 3)))
elems_ok = np.array([1] * 4).reshape((2, 2)).astype(np.int32)
elems_bad = tf.placeholder(tf.int32)
enqueue_op = q.enqueue((elems_ok, elems_bad))
with self.assertRaisesRegexp(
tf.errors.InvalidArgumentError, r"Expected \[3,3\], got \[3,4\]"):
sess.run([enqueue_op],
feed_dict={elems_bad: np.array([1] * 12).reshape((3, 4))})
def testEnqueueDequeueManyWrongShape(self):
with self.test_session() as sess:
q = tf.FIFOQueue(10, (tf.int32, tf.int32), ((2, 2), (3, 3)))
elems_ok = np.array([1] * 8).reshape((2, 2, 2)).astype(np.int32)
elems_bad = tf.placeholder(tf.int32)
enqueue_op = q.enqueue_many((elems_ok, elems_bad))
dequeued_t = q.dequeue_many(2)
with self.assertRaisesRegexp(
tf.errors.InvalidArgumentError,
"Shape mismatch in tuple component 1. "
r"Expected \[2,3,3\], got \[2,3,4\]"):
sess.run([enqueue_op],
feed_dict={elems_bad: np.array([1] * 24).reshape((2, 3, 4))})
dequeued_t.eval()
def testParallelEnqueueMany(self):
with self.test_session() as sess:
q = tf.FIFOQueue(1000, tf.float32, shapes=())
elems = [10.0 * x for x in range(100)]
enqueue_op = q.enqueue_many((elems,))
dequeued_t = q.dequeue_many(1000)
# Enqueue 100 items in parallel on 10 threads.
def enqueue():
sess.run(enqueue_op)
threads = [self.checkedThread(target=enqueue) for _ in range(10)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
self.assertItemsEqual(dequeued_t.eval(), elems * 10)
def testParallelDequeueMany(self):
with self.test_session() as sess:
q = tf.FIFOQueue(1000, tf.float32, shapes=())
elems = [10.0 * x for x in range(1000)]
enqueue_op = q.enqueue_many((elems,))
dequeued_t = q.dequeue_many(100)
enqueue_op.run()
# Dequeue 100 items in parallel on 10 threads.
dequeued_elems = []
def dequeue():
dequeued_elems.extend(sess.run(dequeued_t))
threads = [self.checkedThread(target=dequeue) for _ in range(10)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
self.assertItemsEqual(elems, dequeued_elems)
def testParallelEnqueueAndDequeue(self):
with self.test_session() as sess:
q = tf.FIFOQueue(50, tf.float32, shapes=())
initial_elements = [10.0] * 49
q.enqueue_many((initial_elements,)).run()
enqueue_op = q.enqueue((20.0,))
dequeued_t = q.dequeue()
def enqueue():
for _ in xrange(100):
sess.run(enqueue_op)
def dequeue():
for _ in xrange(100):
self.assertTrue(sess.run(dequeued_t) in (10.0, 20.0))
enqueue_threads = [self.checkedThread(target=enqueue) for _ in range(10)]
dequeue_threads = [self.checkedThread(target=dequeue) for _ in range(10)]
for enqueue_thread in enqueue_threads:
enqueue_thread.start()
for dequeue_thread in dequeue_threads:
dequeue_thread.start()
for enqueue_thread in enqueue_threads:
enqueue_thread.join()
for dequeue_thread in dequeue_threads:
dequeue_thread.join()
# Dequeue the initial count of elements to clean up.
cleanup_elems = q.dequeue_many(49).eval()
for elem in cleanup_elems:
self.assertTrue(elem in (10.0, 20.0))
def testMixtureOfEnqueueAndEnqueueMany(self):
with self.test_session() as sess:
q = tf.FIFOQueue(10, tf.int32, shapes=())
enqueue_placeholder = tf.placeholder(tf.int32, shape=())
enqueue_op = q.enqueue((enqueue_placeholder,))
enqueuemany_placeholder = tf.placeholder(
tf.int32, shape=(None,))
enqueuemany_op = q.enqueue_many((enqueuemany_placeholder,))
dequeued_t = q.dequeue()
close_op = q.close()
def dequeue():
for i in xrange(250):
self.assertEqual(i, sess.run(dequeued_t))
dequeue_thread = self.checkedThread(target=dequeue)
dequeue_thread.start()
elements_enqueued = 0
while elements_enqueued < 250:
# With equal probability, run Enqueue or enqueue_many.
if random.random() > 0.5:
enqueue_op.run({enqueue_placeholder: elements_enqueued})
elements_enqueued += 1
else:
count = random.randint(0, min(20, 250 - elements_enqueued))
range_to_enqueue = np.arange(elements_enqueued,
elements_enqueued + count,
dtype=np.int32)
enqueuemany_op.run({enqueuemany_placeholder: range_to_enqueue})
elements_enqueued += count
close_op.run()
dequeue_thread.join()
self.assertEqual(0, q.size().eval())
def testMixtureOfDequeueAndDequeueMany(self):
with self.test_session() as sess:
q = tf.FIFOQueue(10, tf.int32, shapes=())
enqueue_op = q.enqueue_many((np.arange(250, dtype=np.int32),))
dequeued_t = q.dequeue()
count_placeholder = tf.placeholder(tf.int32, shape=())
dequeuemany_t = q.dequeue_many(count_placeholder)
def enqueue():
sess.run(enqueue_op)
enqueue_thread = self.checkedThread(target=enqueue)
enqueue_thread.start()
elements_dequeued = 0
while elements_dequeued < 250:
# With equal probability, run Dequeue or dequeue_many.
if random.random() > 0.5:
self.assertEqual(elements_dequeued, dequeued_t.eval())
elements_dequeued += 1
else:
count = random.randint(0, min(20, 250 - elements_dequeued))
expected_range = np.arange(elements_dequeued,
elements_dequeued + count,
dtype=np.int32)
self.assertAllEqual(
expected_range, dequeuemany_t.eval({count_placeholder: count}))
elements_dequeued += count
q.close().run()
enqueue_thread.join()
self.assertEqual(0, q.size().eval())
def testBlockingDequeueMany(self):
with self.test_session() as sess:
q = tf.FIFOQueue(10, tf.float32, ())
elems = [10.0, 20.0, 30.0, 40.0]
enqueue_op = q.enqueue_many((elems,))
dequeued_t = q.dequeue_many(4)
dequeued_elems = []
def enqueue():
# The enqueue_op should run after the dequeue op has blocked.
# TODO(mrry): Figure out how to do this without sleeping.
time.sleep(0.1)
sess.run(enqueue_op)
def dequeue():
dequeued_elems.extend(sess.run(dequeued_t).tolist())
enqueue_thread = self.checkedThread(target=enqueue)
dequeue_thread = self.checkedThread(target=dequeue)
enqueue_thread.start()
dequeue_thread.start()
enqueue_thread.join()
dequeue_thread.join()
self.assertAllEqual(elems, dequeued_elems)
def testDequeueManyWithTensorParameter(self):
with self.test_session():
# Define a first queue that contains integer counts.
dequeue_counts = [random.randint(1, 10) for _ in range(100)]
count_q = tf.FIFOQueue(100, tf.int32, ())
enqueue_counts_op = count_q.enqueue_many((dequeue_counts,))
total_count = sum(dequeue_counts)
# Define a second queue that contains total_count elements.
elems = [random.randint(0, 100) for _ in range(total_count)]
q = tf.FIFOQueue(total_count, tf.int32, ())
enqueue_elems_op = q.enqueue_many((elems,))
# Define a subgraph that first dequeues a count, then DequeuesMany
# that number of elements.
dequeued_t = q.dequeue_many(count_q.dequeue())
enqueue_counts_op.run()
enqueue_elems_op.run()
dequeued_elems = []
for _ in dequeue_counts:
dequeued_elems.extend(dequeued_t.eval())
self.assertEqual(elems, dequeued_elems)
def testDequeueFromClosedQueue(self):
with self.test_session():
q = tf.FIFOQueue(10, tf.float32)
elems = [10.0, 20.0, 30.0, 40.0]
enqueue_op = q.enqueue_many((elems,))
close_op = q.close()
dequeued_t = q.dequeue()
enqueue_op.run()
close_op.run()
for elem in elems:
self.assertEqual([elem], dequeued_t.eval())
# Expect the operation to fail due to the queue being closed.
with self.assertRaisesRegexp(tf.errors.OutOfRangeError,
"is closed and has insufficient"):
dequeued_t.eval()
def testBlockingDequeueFromClosedQueue(self):
with self.test_session() as sess:
q = tf.FIFOQueue(10, tf.float32)
elems = [10.0, 20.0, 30.0, 40.0]
enqueue_op = q.enqueue_many((elems,))
close_op = q.close()
dequeued_t = q.dequeue()
enqueue_op.run()
def dequeue():
for elem in elems:
self.assertEqual([elem], sess.run(dequeued_t))
# Expect the operation to fail due to the queue being closed.
with self.assertRaisesRegexp(tf.errors.OutOfRangeError,
"is closed and has insufficient"):
sess.run(dequeued_t)
dequeue_thread = self.checkedThread(target=dequeue)
dequeue_thread.start()
# The close_op should run after the dequeue_thread has blocked.
# TODO(mrry): Figure out how to do this without sleeping.
time.sleep(0.1)
close_op.run()
dequeue_thread.join()
def testBlockingDequeueFromClosedEmptyQueue(self):
with self.test_session() as sess:
q = tf.FIFOQueue(10, tf.float32)
close_op = q.close()
dequeued_t = q.dequeue()
def dequeue():
# Expect the operation to fail due to the queue being closed.
with self.assertRaisesRegexp(tf.errors.OutOfRangeError,
"is closed and has insufficient"):
sess.run(dequeued_t)
dequeue_thread = self.checkedThread(target=dequeue)
dequeue_thread.start()
# The close_op should run after the dequeue_thread has blocked.
# TODO(mrry): Figure out how to do this without sleeping.
time.sleep(0.1)
close_op.run()
dequeue_thread.join()
def testBlockingDequeueManyFromClosedQueue(self):
with self.test_session() as sess:
q = tf.FIFOQueue(10, tf.float32, ())
elems = [10.0, 20.0, 30.0, 40.0]
enqueue_op = q.enqueue_many((elems,))
close_op = q.close()
dequeued_t = q.dequeue_many(4)
enqueue_op.run()
def dequeue():
self.assertAllEqual(elems, sess.run(dequeued_t))
# Expect the operation to fail due to the queue being closed.
with self.assertRaisesRegexp(tf.errors.OutOfRangeError,
"is closed and has insufficient"):
sess.run(dequeued_t)
dequeue_thread = self.checkedThread(target=dequeue)
dequeue_thread.start()
# The close_op should run after the dequeue_thread has blocked.
# TODO(mrry): Figure out how to do this without sleeping.
time.sleep(0.1)
close_op.run()
dequeue_thread.join()
def testEnqueueManyLargerThanCapacityWithConcurrentDequeueMany(self):
with self.test_session() as sess:
q = tf.FIFOQueue(4, tf.float32, ())
elems = [10.0, 20.0, 30.0, 40.0]
enqueue_op = q.enqueue_many((elems,))
close_op = q.close()
dequeued_t = q.dequeue_many(3)
cleanup_dequeue_t = q.dequeue()
def enqueue():
sess.run(enqueue_op)
def dequeue():
self.assertAllEqual(elems[0:3], sess.run(dequeued_t))
with self.assertRaises(tf.errors.OutOfRangeError):
sess.run(dequeued_t)
self.assertEqual(elems[3], sess.run(cleanup_dequeue_t))
def close():
sess.run(close_op)
enqueue_thread = self.checkedThread(target=enqueue)
enqueue_thread.start()
dequeue_thread = self.checkedThread(target=dequeue)
dequeue_thread.start()
# The close_op should run after the dequeue_thread has blocked.
# TODO(mrry): Figure out how to do this without sleeping.
time.sleep(0.1)
close_thread = self.checkedThread(target=close)
close_thread.start()
enqueue_thread.join()
dequeue_thread.join()
close_thread.join()
def testClosedBlockingDequeueManyRestoresPartialBatch(self):
with self.test_session() as sess:
q = tf.FIFOQueue(4, (tf.float32, tf.float32), ((), ()))
elems_a = [1.0, 2.0, 3.0]
elems_b = [10.0, 20.0, 30.0]
enqueue_op = q.enqueue_many((elems_a, elems_b))
dequeued_a_t, dequeued_b_t = q.dequeue_many(4)
cleanup_dequeue_a_t, cleanup_dequeue_b_t = q.dequeue()
close_op = q.close()
enqueue_op.run()
def dequeue():
with self.assertRaises(tf.errors.OutOfRangeError):
sess.run([dequeued_a_t, dequeued_b_t])
dequeue_thread = self.checkedThread(target=dequeue)
dequeue_thread.start()
# The close_op should run after the dequeue_thread has blocked.
# TODO(mrry): Figure out how to do this without sleeping.
time.sleep(0.1)
close_op.run()
dequeue_thread.join()
# Test that the elements in the partially-dequeued batch are
# restored in the correct order.
for elem_a, elem_b in zip(elems_a, elems_b):
val_a, val_b = sess.run([cleanup_dequeue_a_t, cleanup_dequeue_b_t])
self.assertEqual(elem_a, val_a)
self.assertEqual(elem_b, val_b)
self.assertEqual(0, q.size().eval())
def testBlockingDequeueManyFromClosedEmptyQueue(self):
with self.test_session() as sess:
q = tf.FIFOQueue(10, tf.float32, ())
close_op = q.close()
dequeued_t = q.dequeue_many(4)
def dequeue():
# Expect the operation to fail due to the queue being closed.
with self.assertRaisesRegexp(tf.errors.OutOfRangeError,
"is closed and has insufficient"):
sess.run(dequeued_t)
dequeue_thread = self.checkedThread(target=dequeue)
dequeue_thread.start()
# The close_op should run after the dequeue_thread has blocked.
# TODO(mrry): Figure out how to do this without sleeping.
time.sleep(0.1)
close_op.run()
dequeue_thread.join()
def testEnqueueToClosedQueue(self):
with self.test_session():
q = tf.FIFOQueue(10, tf.float32)
enqueue_op = q.enqueue((10.0,))
close_op = q.close()
enqueue_op.run()
close_op.run()
# Expect the operation to fail due to the queue being closed.
with self.assertRaisesRegexp(tf.errors.AbortedError, "is closed"):
enqueue_op.run()
def testEnqueueManyToClosedQueue(self):
with self.test_session():
q = tf.FIFOQueue(10, tf.float32)
elems = [10.0, 20.0, 30.0, 40.0]
enqueue_op = q.enqueue_many((elems,))
close_op = q.close()
enqueue_op.run()
close_op.run()
# Expect the operation to fail due to the queue being closed.
with self.assertRaisesRegexp(tf.errors.AbortedError, "is closed"):
enqueue_op.run()
def testBlockingEnqueueToFullQueue(self):
with self.test_session() as sess:
q = tf.FIFOQueue(4, tf.float32)
elems = [10.0, 20.0, 30.0, 40.0]
enqueue_op = q.enqueue_many((elems,))
blocking_enqueue_op = q.enqueue((50.0,))
dequeued_t = q.dequeue()
enqueue_op.run()
def blocking_enqueue():
sess.run(blocking_enqueue_op)
thread = self.checkedThread(target=blocking_enqueue)
thread.start()
# The dequeue ops should run after the blocking_enqueue_op has blocked.
# TODO(mrry): Figure out how to do this without sleeping.
time.sleep(0.1)
for elem in elems:
self.assertEqual([elem], dequeued_t.eval())
self.assertEqual([50.0], dequeued_t.eval())
thread.join()
def testBlockingEnqueueManyToFullQueue(self):
with self.test_session() as sess:
q = tf.FIFOQueue(4, tf.float32)
elems = [10.0, 20.0, 30.0, 40.0]
enqueue_op = q.enqueue_many((elems,))
blocking_enqueue_op = q.enqueue_many(([50.0, 60.0],))
dequeued_t = q.dequeue()
enqueue_op.run()
def blocking_enqueue():
sess.run(blocking_enqueue_op)
thread = self.checkedThread(target=blocking_enqueue)
thread.start()
# The dequeue ops should run after the blocking_enqueue_op has blocked.
# TODO(mrry): Figure out how to do this without sleeping.
time.sleep(0.1)
for elem in elems:
self.assertEqual([elem], dequeued_t.eval())
time.sleep(0.01)
self.assertEqual([50.0], dequeued_t.eval())
self.assertEqual([60.0], dequeued_t.eval())
def testBlockingEnqueueBeforeClose(self):
with self.test_session() as sess:
q = tf.FIFOQueue(4, tf.float32)
elems = [10.0, 20.0, 30.0, 40.0]
enqueue_op = q.enqueue_many((elems,))
blocking_enqueue_op = q.enqueue((50.0,))
close_op = q.close()
dequeued_t = q.dequeue()
enqueue_op.run()
def blocking_enqueue():
# Expect the operation to succeed once the dequeue op runs.
sess.run(blocking_enqueue_op)
enqueue_thread = self.checkedThread(target=blocking_enqueue)
enqueue_thread.start()
# The close_op should run after the blocking_enqueue_op has blocked.
# TODO(mrry): Figure out how to do this without sleeping.
time.sleep(0.1)
def close():
sess.run(close_op)
close_thread = self.checkedThread(target=close)
close_thread.start()
# The dequeue will unblock both threads.
self.assertEqual(10.0, dequeued_t.eval())
enqueue_thread.join()
close_thread.join()
for elem in [20.0, 30.0, 40.0, 50.0]:
self.assertEqual(elem, dequeued_t.eval())
self.assertEqual(0, q.size().eval())
def testBlockingEnqueueManyBeforeClose(self):
with self.test_session() as sess:
q = tf.FIFOQueue(4, tf.float32)
elems = [10.0, 20.0, 30.0]
enqueue_op = q.enqueue_many((elems,))
blocking_enqueue_op = q.enqueue_many(([50.0, 60.0],))
close_op = q.close()
dequeued_t = q.dequeue()
enqueue_op.run()
def blocking_enqueue():
sess.run(blocking_enqueue_op)
enqueue_thread = self.checkedThread(target=blocking_enqueue)
enqueue_thread.start()
# The close_op should run after the blocking_enqueue_op has blocked.
# TODO(mrry): Figure out how to do this without sleeping.
time.sleep(0.1)
def close():
sess.run(close_op)
close_thread = self.checkedThread(target=close)
close_thread.start()
# The dequeue will unblock both threads.
self.assertEqual(10.0, dequeued_t.eval())
enqueue_thread.join()
close_thread.join()
for elem in [20.0, 30.0, 50.0, 60.0]:
self.assertEqual(elem, dequeued_t.eval())
def testDoesNotLoseValue(self):
with self.test_session():
q = tf.FIFOQueue(1, tf.float32)
enqueue_op = q.enqueue((10.0,))
size_t = q.size()
enqueue_op.run()
for _ in range(500):
self.assertEqual(size_t.eval(), [1])
def testSharedQueueSameSession(self):
with self.test_session():
q1 = tf.FIFOQueue(
1, tf.float32, shared_name="shared_queue")
q1.enqueue((10.0,)).run()
q2 = tf.FIFOQueue(
1, tf.float32, shared_name="shared_queue")
q1_size_t = q1.size()
q2_size_t = q2.size()
self.assertEqual(q1_size_t.eval(), [1])
self.assertEqual(q2_size_t.eval(), [1])
self.assertEqual(q2.dequeue().eval(), [10.0])
self.assertEqual(q1_size_t.eval(), [0])
self.assertEqual(q2_size_t.eval(), [0])
q2.enqueue((20.0,)).run()
self.assertEqual(q1_size_t.eval(), [1])
self.assertEqual(q2_size_t.eval(), [1])
self.assertEqual(q1.dequeue().eval(), [20.0])
self.assertEqual(q1_size_t.eval(), [0])
self.assertEqual(q2_size_t.eval(), [0])
def testIncompatibleSharedQueueErrors(self):
with self.test_session():
q_a_1 = tf.FIFOQueue(10, tf.float32, shared_name="q_a")
q_a_2 = tf.FIFOQueue(15, tf.float32, shared_name="q_a")
q_a_1.queue_ref.eval()
with self.assertRaisesOpError("capacity"):
q_a_2.queue_ref.eval()
q_b_1 = tf.FIFOQueue(10, tf.float32, shared_name="q_b")
q_b_2 = tf.FIFOQueue(10, tf.int32, shared_name="q_b")
q_b_1.queue_ref.eval()
with self.assertRaisesOpError("component types"):
q_b_2.queue_ref.eval()
q_c_1 = tf.FIFOQueue(10, tf.float32, shared_name="q_c")
q_c_2 = tf.FIFOQueue(
10, tf.float32, shapes=[(1, 1, 2, 3)], shared_name="q_c")
q_c_1.queue_ref.eval()
with self.assertRaisesOpError("component shapes"):
q_c_2.queue_ref.eval()
q_d_1 = tf.FIFOQueue(
10, tf.float32, shapes=[(1, 1, 2, 3)], shared_name="q_d")
q_d_2 = tf.FIFOQueue(10, tf.float32, shared_name="q_d")
q_d_1.queue_ref.eval()
with self.assertRaisesOpError("component shapes"):
q_d_2.queue_ref.eval()
q_e_1 = tf.FIFOQueue(
10, tf.float32, shapes=[(1, 1, 2, 3)], shared_name="q_e")
q_e_2 = tf.FIFOQueue(
10, tf.float32, shapes=[(1, 1, 2, 4)], shared_name="q_e")
q_e_1.queue_ref.eval()
with self.assertRaisesOpError("component shapes"):
q_e_2.queue_ref.eval()
q_f_1 = tf.FIFOQueue(10, tf.float32, shared_name="q_f")
q_f_2 = tf.FIFOQueue(
10, (tf.float32, tf.int32), shared_name="q_f")
q_f_1.queue_ref.eval()
with self.assertRaisesOpError("component types"):
q_f_2.queue_ref.eval()
def testSelectQueue(self):
with self.test_session():
num_queues = 10
qlist = list()
for _ in xrange(num_queues):
qlist.append(tf.FIFOQueue(10, tf.float32))
# Enqueue/Dequeue into a dynamically selected queue
for _ in xrange(20):
index = np.random.randint(num_queues)
q = tf.FIFOQueue.from_list(index, qlist)
q.enqueue((10.,)).run()
self.assertEqual(q.dequeue().eval(), 10.0)
def testSelectQueueOutOfRange(self):
with self.test_session():
q1 = tf.FIFOQueue(10, tf.float32)
q2 = tf.FIFOQueue(15, tf.float32)
enq_q = tf.FIFOQueue.from_list(3, [q1, q2])
with self.assertRaisesOpError("Index must be in the range"):
enq_q.dequeue().eval()
def _blockingDequeue(self, sess, dequeue_op):
with self.assertRaisesOpError("Dequeue operation was cancelled"):
sess.run(dequeue_op)
def _blockingDequeueMany(self, sess, dequeue_many_op):
with self.assertRaisesOpError("Dequeue operation was cancelled"):
sess.run(dequeue_many_op)
def _blockingEnqueue(self, sess, enqueue_op):
with self.assertRaisesOpError("Enqueue operation was cancelled"):
sess.run(enqueue_op)
def _blockingEnqueueMany(self, sess, enqueue_many_op):
with self.assertRaisesOpError("Enqueue operation was cancelled"):
sess.run(enqueue_many_op)
def testResetOfBlockingOperation(self):
with self.test_session() as sess:
q_empty = tf.FIFOQueue(5, tf.float32, ())
dequeue_op = q_empty.dequeue()
dequeue_many_op = q_empty.dequeue_many(1)
q_full = tf.FIFOQueue(5, tf.float32)
sess.run(q_full.enqueue_many(([1.0, 2.0, 3.0, 4.0, 5.0],)))
enqueue_op = q_full.enqueue((6.0,))
enqueue_many_op = q_full.enqueue_many(([6.0],))
threads = [
self.checkedThread(self._blockingDequeue, args=(sess, dequeue_op)),
self.checkedThread(self._blockingDequeueMany, args=(sess,
dequeue_many_op)),
self.checkedThread(self._blockingEnqueue, args=(sess, enqueue_op)),
self.checkedThread(self._blockingEnqueueMany, args=(sess,
enqueue_many_op))]
for t in threads:
t.start()
time.sleep(0.1)
sess.close() # Will cancel the blocked operations.
for t in threads:
t.join()
def testBigEnqueueMany(self):
with self.test_session() as sess:
q = tf.FIFOQueue(5, tf.int32, ((),))
elem = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
enq = q.enqueue_many((elem,))
deq = q.dequeue()
size_op = q.size()
enq_done = []
def blocking_enqueue():
enq_done.append(False)
# This will fill the queue and then block until enough dequeues happen.
sess.run(enq)
enq_done.append(True)
thread = self.checkedThread(target=blocking_enqueue)
thread.start()
# The enqueue should start and then block.
results = []
results.append(deq.eval()) # Will only complete after the enqueue starts.
self.assertEqual(len(enq_done), 1)
self.assertEqual(sess.run(size_op), 5)
for _ in range(3):
results.append(deq.eval())
time.sleep(0.1)
self.assertEqual(len(enq_done), 1)
self.assertEqual(sess.run(size_op), 5)
# This dequeue will unblock the thread.
results.append(deq.eval())
time.sleep(0.1)
self.assertEqual(len(enq_done), 2)
thread.join()
for i in range(5):
self.assertEqual(size_op.eval(), 5 - i)
results.append(deq.eval())
self.assertEqual(size_op.eval(), 5 - i - 1)
self.assertAllEqual(elem, results)
def testBigDequeueMany(self):
with self.test_session() as sess:
q = tf.FIFOQueue(2, tf.int32, ((),))
elem = np.arange(4, dtype=np.int32)
enq_list = [q.enqueue((e,)) for e in elem]
deq = q.dequeue_many(4)
results = []
def blocking_dequeue():
# Will only complete after 4 enqueues complete.
results.extend(sess.run(deq))
thread = self.checkedThread(target=blocking_dequeue)
thread.start()
# The dequeue should start and then block.
for enq in enq_list:
# TODO(mrry): Figure out how to do this without sleeping.
time.sleep(0.1)
self.assertEqual(len(results), 0)
sess.run(enq)
# Enough enqueued to unblock the dequeue
thread.join()
self.assertAllEqual(elem, results)
def testDtypes(self):
with self.test_session() as sess:
dtypes = [tf.float32, tf.float64, tf.int32, tf.uint8, tf.int16, tf.int8,
tf.int64, tf.bool, tf.complex64, tf.complex128]
shape = (32, 4, 128)
q = tf.FIFOQueue(32, dtypes, [shape[1:]] * len(dtypes))
input_tuple = []
for dtype in dtypes:
np_dtype = dtype.as_numpy_dtype
np_array = np.random.randint(-10, 10, shape)
if dtype == tf.bool:
np_array = np_array > 0
elif dtype in (tf.complex64, tf.complex128):
np_array = np.sqrt(np_array.astype(np_dtype))
else:
np_array = np_array.astype(np_dtype)
input_tuple.append(np_array)
q.enqueue_many(input_tuple).run()
output_tuple_t = q.dequeue_many(32)
output_tuple = sess.run(output_tuple_t)
for (input_elem, output_elem) in zip(input_tuple, output_tuple):
self.assertAllEqual(input_elem, output_elem)
def testDeviceColocation(self):
with tf.device("/job:ps"):
q = tf.FIFOQueue(32, [tf.int32], name="q")
with tf.device("/job:worker/task:7"):
dequeued_t = q.dequeue()
self.assertDeviceEqual("/job:ps", dequeued_t.device)
self.assertEqual([b"loc:@q"], dequeued_t.op.colocation_groups())
class FIFOQueueDictTest(tf.test.TestCase):
def testConstructor(self):
with tf.Graph().as_default():
q = tf.FIFOQueue(5, (tf.int32, tf.float32), names=("i", "j"),
shared_name="foo", name="Q")
self.assertTrue(isinstance(q.queue_ref, tf.Tensor))
self.assertEquals(tf.string_ref, q.queue_ref.dtype)
self.assertProtoEquals("""
name:'Q' op:'FIFOQueue'
attr { key: 'component_types' value { list {
type: DT_INT32 type : DT_FLOAT
} } }
attr { key: 'shapes' value { list {} } }
attr { key: 'capacity' value { i: 5 } }
attr { key: 'container' value { s: '' } }
attr { key: 'shared_name' value { s: 'foo' } }
""", q.queue_ref.op.node_def)
self.assertEqual(["i", "j"], q.names)
def testConstructorWithShapes(self):
with tf.Graph().as_default():
q = tf.FIFOQueue(5, (tf.int32, tf.float32), names=("i", "f"),
shapes=(tf.TensorShape([1, 1, 2, 3]),
tf.TensorShape([5, 8])), name="Q")
self.assertTrue(isinstance(q.queue_ref, tf.Tensor))
self.assertEquals(tf.string_ref, q.queue_ref.dtype)
self.assertProtoEquals("""
name:'Q' op:'FIFOQueue'
attr { key: 'component_types' value { list {
type: DT_INT32 type : DT_FLOAT
} } }
attr { key: 'shapes' value { list {
shape { dim { size: 1 }
dim { size: 1 }
dim { size: 2 }
dim { size: 3 } }
shape { dim { size: 5 }
dim { size: 8 } }
} } }
attr { key: 'capacity' value { i: 5 } }
attr { key: 'container' value { s: '' } }
attr { key: 'shared_name' value { s: '' } }
""", q.queue_ref.op.node_def)
self.assertEqual(["i", "f"], q.names)
def testEnqueueDequeueOneComponent(self):
with self.test_session() as sess:
q = tf.FIFOQueue(10, tf.float32, shapes=((),), names="f")
# Verify that enqueue() checks that when using names we must enqueue a
# dictionary.
with self.assertRaisesRegexp(ValueError, "enqueue a dictionary"):
enqueue_op = q.enqueue(10.0)
with self.assertRaisesRegexp(ValueError, "enqueue a dictionary"):
enqueue_op = q.enqueue((10.0,))
# The dictionary keys must match the queue component names.
with self.assertRaisesRegexp(ValueError, "match names of Queue"):
enqueue_op = q.enqueue({})
with self.assertRaisesRegexp(ValueError, "match names of Queue"):
enqueue_op = q.enqueue({"x": 12})
with self.assertRaisesRegexp(ValueError, "match names of Queue"):
enqueue_op = q.enqueue({"f": 10.0, "s": "aa"})
enqueue_op = q.enqueue({"f": 10.0})
enqueue_op2 = q.enqueue({"f": 20.0})
enqueue_op3 = q.enqueue({"f": 30.0})
# Verify that enqueue_many() checks that when using names we must enqueue
# a dictionary.
with self.assertRaisesRegexp(ValueError, "enqueue a dictionary"):
enqueue_op4 = q.enqueue_many([40.0, 50.0])
# The dictionary keys must match the queue component names.
with self.assertRaisesRegexp(ValueError, "match names of Queue"):
enqueue_op4 = q.enqueue_many({})
with self.assertRaisesRegexp(ValueError, "match names of Queue"):
enqueue_op4 = q.enqueue_many({"x": 12})
with self.assertRaisesRegexp(ValueError, "match names of Queue"):
enqueue_op4 = q.enqueue_many({"f": [40.0, 50.0], "s": ["aa", "bb"]})
enqueue_op4 = q.enqueue_many({"f": [40.0, 50.0]})
dequeue = q.dequeue()
dequeue_2 = q.dequeue_many(2)
sess.run(enqueue_op)
sess.run(enqueue_op2)
sess.run(enqueue_op3)
sess.run(enqueue_op4)
f = sess.run(dequeue["f"])
self.assertEqual(10.0, f)
f = sess.run(dequeue_2["f"])
self.assertEqual([20.0, 30.0], list(f))
f = sess.run(dequeue_2["f"])
self.assertEqual([40.0, 50.0], list(f))
def testEnqueueDequeueMultipleComponent(self):
with self.test_session() as sess:
q = tf.FIFOQueue(10, (tf.float32, tf.int32, tf.string),
shapes=((), (), ()), names=("f", "i", "s"))
# Verify that enqueue() checks that when using names we must enqueue a
# dictionary.
with self.assertRaisesRegexp(ValueError, "enqueue a dictionary"):
enqueue_op = q.enqueue((10.0, 123, "aa"))
# The dictionary keys must match the queue component names.
with self.assertRaisesRegexp(ValueError, "match names of Queue"):
enqueue_op = q.enqueue({})
with self.assertRaisesRegexp(ValueError, "match names of Queue"):
enqueue_op = q.enqueue({"x": 10.0})
with self.assertRaisesRegexp(ValueError, "match names of Queue"):
enqueue_op = q.enqueue({"i": 12, "s": "aa"})
with self.assertRaisesRegexp(ValueError, "match names of Queue"):
enqueue_op = q.enqueue({"i": 123, "s": "aa", "f": 10.0, "x": 10.0})
enqueue_op = q.enqueue({"i": 123, "s": "aa", "f": 10.0})
enqueue_op2 = q.enqueue({"i": 124, "s": "bb", "f": 20.0})
enqueue_op3 = q.enqueue({"i": 125, "s": "cc", "f": 30.0})
# Verify that enqueue_many() checks that when using names we must enqueue
# a dictionary.
with self.assertRaisesRegexp(ValueError, "enqueue a dictionary"):
enqueue_op4 = q.enqueue_many(([40.0, 50.0], [126, 127], ["dd", "ee"]))
# The dictionary keys must match the queue component names.
with self.assertRaisesRegexp(ValueError, "match names of Queue"):
enqueue_op4 = q.enqueue_many({})
with self.assertRaisesRegexp(ValueError, "match names of Queue"):
enqueue_op4 = q.enqueue_many({"x": [10.0, 20.0]})
with self.assertRaisesRegexp(ValueError, "match names of Queue"):
enqueue_op4 = q.enqueue_many({"i": [12, 12], "s": ["aa", "bb"]})
with self.assertRaisesRegexp(ValueError, "match names of Queue"):
enqueue_op4 = q.enqueue_many({"f": [40.0, 50.0], "i": [126, 127],
"s": ["dd", "ee"], "x": [1, 2]})
enqueue_op4 = q.enqueue_many({"f": [40.0, 50.0], "i": [126, 127],
"s": ["dd", "ee"]})
dequeue = q.dequeue()
dequeue_2 = q.dequeue_many(2)
sess.run(enqueue_op)
sess.run(enqueue_op2)
sess.run(enqueue_op3)
sess.run(enqueue_op4)
i, f, s = sess.run([dequeue["i"], dequeue["f"], dequeue["s"]])
self.assertEqual(123, i)
self.assertEqual(10.0, f)
self.assertEqual(tf.compat.as_bytes("aa"), s)
i, f, s = sess.run([dequeue_2["i"], dequeue_2["f"], dequeue_2["s"]])
self.assertEqual([124, 125], list(i))
self.assertTrue([20.0, 30.0], list(f))
self.assertTrue([tf.compat.as_bytes("bb"), tf.compat.as_bytes("cc")],
list(s))
i, f, s = sess.run([dequeue_2["i"], dequeue_2["f"], dequeue_2["s"]])
self.assertEqual([126, 127], list(i))
self.assertTrue([40.0, 50.0], list(f))
self.assertTrue([tf.compat.as_bytes("dd"), tf.compat.as_bytes("ee")],
list(s))
class FIFOQueueWithTimeoutTest(tf.test.TestCase):
def testDequeueWithTimeout(self):
with self.test_session(
config=tf.ConfigProto(operation_timeout_in_ms=20)) as sess:
q = tf.FIFOQueue(10, tf.float32)
dequeued_t = q.dequeue()
# Intentionally do not run any enqueue_ops so that dequeue will block
# until operation_timeout_in_ms.
with self.assertRaisesRegexp(tf.errors.DeadlineExceededError,
"Timed out waiting for notification"):
sess.run(dequeued_t)
if __name__ == "__main__":
tf.test.main()
|
http_server.py | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Runs http(s) server in the background."""
import BaseHTTPServer
import mimetypes
import os
import socket
import threading
from system import environment
def get_absolute_testcase_file(request_path):
"""Search the input directory and additional paths for the requested file."""
# Gather the list of search path directories.
current_working_directory = os.getcwd()
data_directory = environment.get_value('FUZZ_DATA')
input_directory = environment.get_value('INPUT_DIR')
fuzzer_directory = environment.get_value('FUZZERS_DIR')
layout_tests_directory = os.path.join(data_directory, 'LayoutTests')
layout_tests_http_tests_directory = os.path.join(layout_tests_directory,
'http', 'tests')
layout_tests_wpt_tests_directory = os.path.join(layout_tests_directory,
'external', 'wpt')
# TODO(mbarbella): Add support for aliasing and directories from
# https://cs.chromium.org/chromium/src/third_party/blink/tools/blinkpy/web_tests/servers/apache_http.py?q=apache_http.py&sq=package:chromium&dr&l=60
# Check all search paths for the requested file.
search_paths = [
current_working_directory,
fuzzer_directory,
input_directory,
layout_tests_directory,
layout_tests_http_tests_directory,
layout_tests_wpt_tests_directory,
]
for search_path in search_paths:
base_string = search_path + os.path.sep
path = request_path.lstrip('/')
if not path or path.endswith('/'):
path += 'index.html'
absolute_path = os.path.abspath(os.path.join(search_path, path))
if (absolute_path.startswith(base_string) and
os.path.exists(absolute_path) and not os.path.isdir(absolute_path)):
return absolute_path
return None
def guess_mime_type(filename):
"""Guess mime type based of file extension."""
if not mimetypes.inited:
mimetypes.init()
return mimetypes.guess_type(filename)[0]
class BotHTTPServer(BaseHTTPServer.HTTPServer):
"""Host the bot's test case directories over HTTP."""
def __init__(self, server_address, handler_class):
BaseHTTPServer.HTTPServer.__init__(self, server_address, handler_class)
def _handle_request_noblock(self):
"""Process a single http request."""
try:
request, client_address = self.get_request()
except socket.error:
return
if self.verify_request(request, client_address):
try:
self.process_request(request, client_address)
except:
self.close_request(request)
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
"""Handler for get requests to test cases."""
def do_get(self):
"""Handle a GET request."""
absolute_path = get_absolute_testcase_file(self.path)
if not absolute_path:
self.send_response(404)
self.end_headers()
return
try:
with open(absolute_path) as file_handle:
data = file_handle.read()
except IOError:
self.send_response(403)
self.end_headers()
return
self.send_response(200, 'OK')
# Send a content type header if applicable.
mime_type = guess_mime_type(absolute_path)
if mime_type:
self.send_header('Content-type', mime_type)
self.end_headers()
self.wfile.write(data)
def log_message(self, fmt, *args): # pylint: disable=arguments-differ
"""Do not output a log entry to stderr for every request made."""
pass
def run_server(host, port):
"""Run the HTTP server on the given port."""
httpd = BotHTTPServer((host, port), RequestHandler)
httpd.serve_forever()
def port_is_open(host, port):
socket_handle = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = socket_handle.connect_ex((host, port))
socket_handle.close()
return result == 0
def start_server_thread(host, port):
server = threading.Thread(target=run_server, args=(host, port))
server.daemon = True
server.start()
def start():
"""Initialize the HTTP server on the specified ports."""
http_host = 'localhost'
http_port_1 = environment.get_value('HTTP_PORT_1', 8000)
http_port_2 = environment.get_value('HTTP_PORT_2', 8080)
if not port_is_open(http_host, http_port_1):
start_server_thread(http_host, http_port_1)
if not port_is_open(http_host, http_port_2):
start_server_thread(http_host, http_port_2)
|
build.py | #!/usr/bin/env python
# -*- coding: utf-8
import logging
import re
import tempfile
from collections import namedtuple
from datetime import datetime
from threading import Thread
from .image import Image
LOG = logging.getLogger(__name__)
FROM_PATTERN = re.compile(r"FROM\s+(?P<name>[\w./-]+)(:(?P<tag>[\w.-]+))?(\s+(?:AS|as) (?P<alias>\w+))?")
ARCH_PATTERN = re.compile(r"# dockerma archs:(?P<archs>.+):")
# Map from docker archs to monsonnl/qemu-wrap-build-files
SUPPORTED_ARCHS = {
"amd64": "x86_64",
"arm": "arm32v7",
"arm64": "arm64v8",
}
def _parse_archs(line):
m = ARCH_PATTERN.match(line)
if m:
archs = m.group("archs")
return re.split(r"\s*,\s*", archs)
return tuple()
class Builder(object):
name = "build"
def __init__(self, parser):
parser.add_argument("-f", "--file", help="Name of the Dockerfile", default="Dockerfile")
parser.add_argument("-t", "--tag", action="append", help="Name and optionally a tag in the 'name:tag' format")
parser.add_argument("path", help="Docker context", metavar="PATH|URL")
self._docker = None
self._options = None
self._remaining = []
self._base_images = set()
self._alias_lookup = {}
self._archs = set()
self._template = [BuildToolStage()]
self._work_dir = namedtuple("_", ["name"])(None)
def __call__(self, docker, options, remaining_args):
self._secondary_init(docker, options, remaining_args)
self._parse_dockerfile()
self._check_for_problems()
threads = []
for arch in self._archs:
t = Thread(target=self._build, name="Build-Thread-{}".format(arch), args=(arch,))
t.daemon = True
t.start()
threads.append(t)
for t in threads:
t.join()
def _secondary_init(self, docker, options, remaining_args):
self._docker = docker
self._options = options
self._remaining = remaining_args
if not self._options.debug:
self._work_dir = tempfile.TemporaryDirectory(prefix="dockerma-")
def _check_for_problems(self):
if not self._archs:
raise InvalidConfigurationError("No arch requested, did you forgot the dockerma directive?")
supported = set(SUPPORTED_ARCHS.keys())
if not self._archs.issubset(supported):
missing = self._archs - supported
raise UnsupportedArchError("dockerma does not support requested arch: {}".format(", ".join(missing)))
for image in self._base_images:
if image.name in self._alias_lookup:
continue
if not self._archs.issubset(image.get_supported_archs()):
missing = self._archs - image.get_supported_archs()
raise UnsupportedBaseError("{} does not support requested arch: {}".format(image, ", ".join(missing)))
def _parse_dockerfile(self):
with open(self._options.file) as fobj:
for line in fobj:
try:
image = self._parse_from(line)
self._template.extend((FromMarker(image), CopyTools(), CrossBuild()))
self._base_images.add(image)
if image.alias:
self._alias_lookup[image.alias] = image
continue
except ValueError:
pass
archs = _parse_archs(line)
if archs:
self._archs.update(archs)
continue
self._template.append(Identity(line))
self._template.append(CrossBuild("end"))
def _parse_from(self, line):
m = FROM_PATTERN.match(line)
if m:
groups = m.groupdict()
name = groups["name"]
return Image(self._docker, name, groups["tag"], groups["alias"], name in self._alias_lookup)
raise ValueError("Unable to parse image reference from line %r" % line)
def _build(self, arch):
LOG.info("Building image for %s", arch)
dockerfile = tempfile.NamedTemporaryFile(mode="w+", suffix=".{}".format(arch),
prefix="Dockerfile-", dir=self._work_dir.name, delete=False)
dockerfile.write("".join(r.render(arch) for r in self._template))
dockerfile.flush()
LOG.debug("Rendered {} for {}".format(dockerfile.name, arch))
args = []
for tag in self._options.tag:
arch_tag = "{}-{}".format(tag, arch)
args.extend(("-t", arch_tag))
args.extend(("-f", dockerfile.name))
args.extend(self._remaining)
args.append(self._options.path)
start = datetime.now()
self._docker.execute("build", *args)
time_spent = datetime.now() - start
LOG.info("Building %s took %s", arch, time_spent)
class Renderable(object):
def render(self, arch):
raise NotImplementedError()
class Identity(Renderable):
def __init__(self, value):
self._value = value
def render(self, arch):
return self._value
class FromMarker(Renderable):
def __init__(self, image):
self._image = image
def render(self, arch):
return "FROM {} AS {}\n".format(self._image.sha(arch), self._image.alias)
class BuildToolStage(Identity):
def __init__(self):
super(BuildToolStage, self).__init__("FROM monsonnl/qemu-wrap-build-files AS dockerma_build_files\n")
class CopyTools(Renderable):
def render(self, arch):
qemu_arch = SUPPORTED_ARCHS[arch]
return "COPY --from=dockerma_build_files /cross-build/{}/bin /bin\n".format(qemu_arch)
class CrossBuild(Renderable):
def __init__(self, kind="start"):
self._kind = kind
def render(self, arch):
return "RUN [ \"cross-build-{}\" ]\n".format(self._kind)
class BuildError(Exception):
pass
class UnsupportedArchError(BuildError):
pass
class UnsupportedBaseError(BuildError):
pass
class InvalidConfigurationError(BuildError):
pass
|
test_mp_plugin.py | import sys
from nose2 import session
from nose2.compat import unittest
from nose2.plugins.mp import MultiProcess, procserver
from nose2.plugins import buffer
from nose2.plugins.loader import discovery, testcases
from nose2.tests._common import FunctionalTestCase, support_file, Conn
import multiprocessing
import threading
import time
from multiprocessing import connection
class TestMpPlugin(FunctionalTestCase):
def setUp(self):
super(TestMpPlugin, self).setUp()
self.session = session.Session()
self.plugin = MultiProcess(session=self.session)
def test_flatten_without_fixtures(self):
sys.path.append(support_file('scenario/slow'))
import test_slow as mod
suite = unittest.TestSuite()
suite.addTest(mod.TestSlow('test_ok'))
suite.addTest(mod.TestSlow('test_fail'))
suite.addTest(mod.TestSlow('test_err'))
flat = list(self.plugin._flatten(suite))
self.assertEqual(len(flat), 3)
def test_flatten_nested_suites(self):
sys.path.append(support_file('scenario/slow'))
import test_slow as mod
suite = unittest.TestSuite()
suite.addTest(mod.TestSlow('test_ok'))
suite.addTest(mod.TestSlow('test_fail'))
suite.addTest(mod.TestSlow('test_err'))
suite2 = unittest.TestSuite()
suite2.addTest(suite)
flat = list(self.plugin._flatten(suite2))
self.assertEqual(len(flat), 3)
def test_flatten_respects_module_fixtures(self):
sys.path.append(support_file('scenario/module_fixtures'))
import test_mf_testcase as mod
suite = unittest.TestSuite()
suite.addTest(mod.Test('test_1'))
suite.addTest(mod.Test('test_2'))
flat = list(self.plugin._flatten(suite))
self.assertEqual(flat, ['test_mf_testcase'])
def test_flatten_respects_class_fixtures(self):
sys.path.append(support_file('scenario/class_fixtures'))
import test_cf_testcase as mod
suite = unittest.TestSuite()
suite.addTest(mod.Test('test_1'))
suite.addTest(mod.Test('test_2'))
suite.addTest(mod.Test2('test_1'))
suite.addTest(mod.Test2('test_2'))
suite.addTest(mod.Test3('test_3'))
flat = list(self.plugin._flatten(suite))
self.assertEqual(flat, ['test_cf_testcase.Test2.test_1',
'test_cf_testcase.Test2.test_2',
'test_cf_testcase.Test',
'test_cf_testcase.Test3',
])
def test_conn_prep(self):
self.plugin.bind_host = None
(parent_conn, child_conn) = self.plugin._prepConns()
(parent_pipe, child_pipe) = multiprocessing.Pipe()
self.assertIsInstance(parent_conn, type(parent_pipe))
self.assertIsInstance(child_conn, type(child_pipe))
self.plugin.bind_host = "127.0.0.1"
self.plugin.bind_port = 0
(parent_conn, child_conn) = self.plugin._prepConns()
self.assertIsInstance(parent_conn, connection.Listener)
self.assertIsInstance(child_conn, tuple)
self.assertEqual(parent_conn.address, child_conn[:2])
def test_conn_accept(self):
(parent_conn, child_conn) = multiprocessing.Pipe()
self.assertEqual(self.plugin._acceptConns(parent_conn), parent_conn)
listener = connection.Listener(('127.0.0.1', 0))
with self.assertRaises(RuntimeError):
self.plugin._acceptConns(listener)
def fake_client(address):
client = connection.Client(address)
time.sleep(10)
client.close()
t = threading.Thread(target=fake_client, args=(listener.address,))
t.start()
conn = self.plugin._acceptConns(listener)
self.assertTrue(hasattr(conn, "send"))
self.assertTrue(hasattr(conn, "recv"))
class TestProcserver(FunctionalTestCase):
def setUp(self):
super(TestProcserver, self).setUp()
self.session = session.Session()
def test_dispatch_tests_receive_events(self):
ssn = {
'config': self.session.config,
'verbosity': 1,
'startDir': support_file('scenario/tests_in_package'),
'topLevelDir': support_file('scenario/tests_in_package'),
'logLevel': 100,
'pluginClasses': [discovery.DiscoveryLoader,
testcases.TestCaseLoader,
buffer.OutputBufferPlugin]
}
conn = Conn(['pkg1.test.test_things.SomeTests.test_ok',
'pkg1.test.test_things.SomeTests.test_failed'])
procserver(ssn, conn)
# check conn calls
expect = [('pkg1.test.test_things.SomeTests.test_ok',
[('startTest', {}),
('setTestOutcome', {'outcome': 'passed'}),
('testOutcome', {'outcome': 'passed'}),
('stopTest', {})]
),
('pkg1.test.test_things.SomeTests.test_failed',
[('startTest', {}),
('setTestOutcome', {
'outcome': 'failed',
'expected': False,
'metadata': {'stdout': 'Hello stdout\n'}}),
('testOutcome', {
'outcome': 'failed',
'expected': False,
'metadata': {'stdout': 'Hello stdout\n'}}),
('stopTest', {})]
),
]
for val in conn.sent:
if val is None:
break
test, events = val
exp_test, exp_events = expect.pop(0)
self.assertEqual(test, exp_test)
for method, event in events:
exp_meth, exp_attr = exp_events.pop(0)
self.assertEqual(method, exp_meth)
for attr, val in exp_attr.items():
self.assertEqual(getattr(event, attr), val)
class MPPluginTestRuns(FunctionalTestCase):
def test_tests_in_package(self):
proc = self.runIn(
'scenario/tests_in_package',
'-v',
'--plugin=nose2.plugins.mp',
'-N=2')
self.assertTestRunOutputMatches(proc, stderr='Ran 25 tests')
self.assertEqual(proc.poll(), 1)
def test_package_in_lib(self):
proc = self.runIn(
'scenario/package_in_lib',
'-v',
'--plugin=nose2.plugins.mp',
'-N=2')
self.assertTestRunOutputMatches(proc, stderr='Ran 3 tests')
self.assertEqual(proc.poll(), 1)
def test_module_fixtures(self):
proc = self.runIn(
'scenario/module_fixtures',
'-v',
'--plugin=nose2.plugins.mp',
'-N=2')
self.assertTestRunOutputMatches(proc, stderr='Ran 5 tests')
self.assertEqual(proc.poll(), 0)
def test_class_fixtures(self):
proc = self.runIn(
'scenario/class_fixtures',
'-v',
'--plugin=nose2.plugins.mp',
'-N=2')
self.assertTestRunOutputMatches(proc, stderr='Ran 7 tests')
self.assertEqual(proc.poll(), 0)
def test_large_number_of_tests_stresstest(self):
proc = self.runIn(
'scenario/many_tests',
'-v',
'--plugin=nose2.plugins.mp',
'--plugin=nose2.plugins.loader.generators',
'-N=1')
self.assertTestRunOutputMatches(proc, stderr='Ran 600 tests')
self.assertEqual(proc.poll(), 0)
def test_socket_stresstest(self):
proc = self.runIn(
'scenario/many_tests_socket',
'-v',
'-c scenario/many_test_socket/nose2.cfg',
'--plugin=nose2.plugins.mp',
'--plugin=nose2.plugins.loader.generators',
'-N=1')
self.assertTestRunOutputMatches(proc, stderr='Ran 600 tests')
self.assertEqual(proc.poll(), 0)
|
cliIM.py | #!/usr/bin/python3
# -*- coding: utf-8 -*-
import fbchat ## github fbchat python
from threading import Thread
import sys,time,termios,tty,re,os
import logging, traceback
try:
from termcolor import colored
except:
def colored(text,color):
return text
class dummyExample(): # module example
last_tid = '' ## current talkto tid/uid
last_tname = '' ## current talkto thread
def __init__(self):
## include login
pass
self._roster = dict() ## {id : name}
def roster(self,uid): # get name of user/thread id
return self._roster.get(str(uid))
def listen(self):
while self.listening:
time.sleep(60)
## receive messages
## TBD
def searchUser(self,user):
''' for /whois'''
pass
def recentChats(self,limit=5):
''' for /history'''
pass
class FBChat(fbchat.Client):
savepath = './'
fbcookiefile = savepath+'/'+'fbcookies.txt'
fbrosterfile = savepath+'/'+'fbroster.txt'
last_tid = ''
last_tname = ''
last_mid = ""
name_color = "yellow"
thread_color = "yellow"
time_color = "blue"
_roster = dict()
def __init__(self,USERNAME,PASSWD):
''' login or read cookies, and read roster'''
fbcookiefile = self.fbcookiefile
if os.path.isfile(fbcookiefile):
fbcookies = eval(open(fbcookiefile,'r').read())
else:
fbcookies = dict()
try:
s = Spinner()
s.start_spin('[fb] '+USERNAME+' logging in...')
if fbcookies:
super().__init__(USERNAME, PASSWD, session_cookies=fbcookies, logging_level=logging.WARNING)
else:
super().__init__(USERNAME, PASSWD, logging_level=logging.WARNING)
except:
e = sys.exc_info()
print(e)
finally:
s.stop_spin()
print('\r[fb] '+USERNAME+' login success \033[K')
fbcookies = self.getSession()
open(fbcookiefile,'w').write(str(fbcookies))
## read saved roster
try:
if os.path.isfile(self.fbrosterfile): self._roster= eval(open(self.fbrosterfile,'r').read())
except:
print('[fb] read roster file failed: '+self.fbrosterfile)
self.prompt = colored('[fb] ','red')
''' actions for cliIM '''
def roster(self,itid):
tid = str(itid)
name = self._roster.get(tid)
if name: return name
thread = self.fetchThreadInfo(tid)
name = thread.get('name')
if name:
self.roster_add({tid : name})
return name
name = thread[tid].name
if name:
self.roster_add(tid, name)
return name
name = thread[tid].nickname
if name:
self.roster_add(tid, name)
return name
name = thread[tid].last_name
if name:
self.roster_add(tid, name)
return name
return str(tid)
def roster_add(self,uid,name):
self._roster.update({str(uid) : name})
open(self.fbrosterfile,'w').write(str(self._roster))
''' end of actions for cliIM '''
''' callback for cliIM '''
def onMessage(self, mid=None, author_id=None, message=None, message_object=None, thread_id=None, thread_type=fbchat.ThreadType.USER, ts=None, metadata=None, msg=None):
timestamp = time.strftime('%H:%M',time.localtime(ts/1000.))
msgtext = message
tid = thread_id or author_id
self.markAsDelivered(tid, mid)
#self.markAsRead(tid)
sender_name = colored(self.roster(author_id),self.name_color)
thread_name = colored(self.roster(thread_id),self.thread_color)
msgtime = colored('['+timestamp+']',self.time_color)
if thread_id or str(author_id) != str(self.uid) :
self.last_tid = thread_id or author_id
self.last_tname = self.roster(self.last_tid)
self.prompt = colored('[fb]','red')+colored('['+self.last_tname+'] ',self.name_color)
if not message: ## for ่ฒผๅ
msgtext = colored("้ๅบ่ฒผๅ","cyan")
try: # try to get image url
imgurl = msg['delta']['attachments'][0]['large_preview']['uri']
imgfn = msg['delta']['attachments'][0]['filename']
msgtext += colored(str(imgurl),"blue")
except: # if failed...
pass
#msgtext += colored(str(msg),"blue")
#msgtext += colored(str(metadata),"blue")
try:
if not sender_name == thread_name:
tt = "%s %s to %s: %s"%(msgtime,sender_name,thread_name,msgtext)
else:
tt = "%s %s: %s"%(msgtime,sender_name,msgtext)
self.output(tt) ## self.output() is assigned in cliInterface
except UnicodeDecodeError:
pass
''' end of callback for cliIM '''
class Spinner():
Box1 = u'โ โ โ นโ ธโ ผโ ดโ ฆโ งโ โ '
Box2 = u'โ โ โ โ โ โ ฆโ ดโ ฒโ ณโ '
Box3 = u'โ โ โ โ โ โ ธโ ฐโ โ ฐโ ธโ โ โ โ '
Box4 = u'โ โ โ โ โ โ โ โ ฒโ ดโ ฆโ โ โ โ โ โ โ '
Box5 = u'โ โ โ โ โ โ โ โ โ ฒโ ดโ คโ โ โ คโ ดโ ฒโ โ โ โ โ โ โ โ '
Box6 = u'โ โ โ โ โ โ โ โ โ โ ฆโ คโ โ โ คโ ฆโ โ โ โ โ โ โ โ โ '
Box7 = u'โ โ โ โ โ โ โ โ โ โ ฒโ ดโ คโ โ โ คโ โ โ คโ ฆโ โ โ โ โ โ โ โ โ โ '
Spin1 = u'|/-\\'
Spin2 = u'โดโทโถโต'
Spin3 = u'โฐโณโฒโฑ'
Spin4 = u'โโโโ'
Spin5 = u'โโโโโโโโโโโโโ'
Spin6 = u'โโโโ'
Spin7 = u'โซโช'
Spin8 = u'โ โกโชโซ'
Spin9 = u'โโโโ'
default = Spin2
running = 0
text = ''
def spinning(self):
spinstring = self.default
slen = len(spinstring)
i = 0
while self.running:
sys.stdout.write("\r"+self.text+' '+spinstring[(i%slen)])
sys.stdout.flush()
time.sleep(0.1)
i = i+1
#sys.stdout.write("\r")
#sys.stdout.flush()
def start_spin(self,text):
if text : self.text = text
self.running = 1
#self.spinning() ## should use threading
a = Thread(target=self.spinning)
a.start()
def stop_spin(self):
self.running = 0
class cliInterface(): ## get hotkeys, control cmd line and insert text above it
def __init__(self,mods):
self.cmd_prompt = ''
self.cmd = ''
self.exitkey = [3] # ord(keys) to exit, [C-c]
self.curPos = 0 ## cursor position in cmd line
self.curEOL = 1 ## is cursor follow end of line
self.actived_mods = list() # modules to operate
self.threads = list() # module threads
self.c = None # current modules to operate
for m in mods:
th = Thread(target=m.listen)
th.start()
self.actived_mods.append(m)
self.threads.append(th)
self.c = self.actived_mods[0]
self.cmd_history = ['']
self.cmd_now = 0 ## 0 means using new cmd, cmd_history is negative
self.cmd_typing = ''
# _cmd_actions dict()
self.cmd_actions = dict()
for i in dir(self):
if re.match("^_cmd_[A-Za-z]*",i): self.cmd_actions.update({re.sub(r"^_cmd_",r"/",i,1) : eval("self."+i)})
# spinner
self.spinner = Spinner()
def _cmd_whois(self,a):
''' /whois <user name> : find user'''
c = self.c
users = c.searchForUsers(a[7:],limit=5)
if users:
c.last_users = users
nuser = len(users)
for i in range(nuser):
c.roster_add(users[i].uid , users[i].name)
self.output(" %s : %s %s"%
(i,colored(users[i].name,'cyan')
,colored(re.sub("www\.","m.",users[i].url),'blue')))
self.output(colored("/talkto [number]",'red'))
else:
pass
return
def fbchat_parse_message_and_outpt(self,message,timef='%m-%d %H:%M'):
author = colored(message.author,'yellow')
timestamp = time.strftime(timef,time.localtime(int(message.timestamp)/1000.))
timestamp = colored('['+timestamp+']','blue')
text = message.text
if not text:
if message.sticker: text = "[่ฒผๅ'"+message.sticker.url+" ']"
if message.attachments: text = "[ๆชๆก'"+message.attachment.url+" ']"
self.output(timestamp+' '+self.c.roster(message.author)+': '+text)
def _cmd_talkto(self,a):
r''' /talkto <list number> : set thread to chat'''
c = self.c
try:
i = int(a[8:])
except:
self.output(colored("/talkto [number]",'red'))
return
if c.last_users:
if i > len(c.last_users)-1:
self.output(colored("/talkto [0-"+str(len(c.last_users)-1)+"]",'red'))
return
c.last_tid = c.last_users[i].uid
c.last_tname = c.roster(c.last_tid)
c.prompt = colored('[fb]','red')+colored('['+c.last_tname+'] ','cyan')
try:
#self.output("fetching old message with "+c.roster(c.last_tid)+" = "+str(c.last_tid))
oldmsgs = c.fetchThreadMessages(thread_id=str(c.last_tid),before=0,limit=5)
oldmsgs.reverse()
for i in oldmsgs:
self.fbchat_parse_message_and_outpt(i,timef='%m-%d %H:%M')
except:
pass
self.output(colored('fetch old messages failed.','red'))
e = sys.exc_info()
print(e)
self.output(colored("talking to ","red")+colored(c.last_tname,"yellow"))
else:
pass
return
def _cmd_history(self,a):
r''' /history [n items] : list chat threads '''
c = self.c
i = 5
if len(a) > 8:
try:
i = int(a[8:])
except:
self.output(colored("/history [number]",'red'))
return
threads = c.fetchThreadList(limit=i)
if threads:
'''
for t in threads:
if not t.name: t.name = t.other_user_name
for t in threads:
t.uid = t.thread_fbid
'''
nthreads = len(threads)
c.last_users = threads
for i in range(nthreads):
self.output(" %s : %s "%
(i,colored(threads[i].name,'yellow')))
c.roster_add(threads[i].uid,threads[i].name)
#self.output("use /talkto [number] ")
self.output(colored("use /talkto [number] ",'red'))
else:
self.output(colored("Find no chat",'red'))
return
def _cmd_roster(self,a):
r''' /roster : list roster'''
c = self.c
if not c.roster: self.output("no roster yet")
for i in c._roster.keys():
self.output("%s : %s "%
(colored(c.roster(i),'yellow')
,colored(i,'cyan') ))
return
def _cmd_clear(self,a):
''' /clear : clear screen and current talkto '''
self.c.last_tid = ''
self.c.last_tname = ''
self.c.prompt = colored('[fb] ','red')
self.output(chr(27) + "[2J")
return
def _cmd_cls(self,a):
''' /cls : clear screen '''
self.output(chr(27) + "[2J")
return
def _cmd_quit(self,a):
''' /quit : quit cliIM '''
self._exit()
return
def _cmd_help(self,a):
''' /help : list commands'''
for i in sorted(self.cmd_actions.keys()):
self.output(self.cmd_actions[i].__doc__)
def _getch(self): ## grab keycode
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
def _do_cmd(self,cmd):
''' when get command '''
a = cmd
c = self.c
tid = c.last_tid
firstWord = a.split(' ')[0]
if firstWord in self.cmd_actions.keys():
self.cmd_actions[firstWord](a)
return
if re.match("^\/",a):
self.output("%s"%(colored("Want to use command? "+a,"red")))
return
if tid and a:
#self.output(colored("[%s] send %s to %s "%(('ok' if c.send(thread_id=tid,message=fbchat.Message(text=a)) else 'failed'),a,c.roster(tid)),"blue"))
c.send(thread_id=tid,message=fbchat.Message(text=a))
return
if not tid:
self.output(colored("Talk to who? Try use /history or /whois find someone: "+a,"red"))
return
if not a:
self.output("say something to %s ?" %(colored(c.roster(tid),"yellow")))
return
def _keyact(self,ch): ## action for keypress
''' action when key pressed '''
## TBD hotkeys, dict() style keyact
if ord(ch) in self.exitkey:
self._exit()
return
if ord(ch) in [10,13,15]: ## press enter,C-m,C-o,C-j
cmd = self.cmd[:]
if cmd: self.cmd_history.append(cmd)
self.cmd_now = 0
self.curEOL=1 ## put cursor to end of line
try:
self.output(spinner=True)
self._do_cmd(cmd)
except:
self.output(cmd+" error")
self.output(str(sys.exc_info()))
finally:
pass
self.cmd = ''
self.output() ## refresh cmd_line
return
if ord(ch) in [4]: ## press C-d (delete)
self.cmd = self.cmd[:self.curPos]+self.cmd[self.curPos+1:]
self.output()
return
if ord(ch) in [127,8]: ## press backspace or C-h
self.cmd = self.cmd[:self.curPos-1]+self.cmd[self.curPos:]
self.curPos += -1
self.output()
return
if ord(ch) in [2]: ## press C-b
self.curEOL = 0
self.curPos += -1
self.output()
return
if ord(ch) in [6]: ## press C-f
self.curEOL = 0
self.curPos += 1
self.output()
return
if ord(ch) in [1]: ## press C-a
self.curEOL = 0
self.curPos = 0
self.output()
return
if ord(ch) in [5]: ## press C-e
self.curEOL = 1
self.output()
return
if ord(ch) in [21]: ## press C-u
self.cmd = self.cmd[self.curPos:]
self.curPos = 0
self.output()
return
if ord(ch) in [23]: ## press C-w
self.output('hotkey C-w not done yet')
return
if ord(ch) in [16]: ## press C-p
if self.cmd_now == 0 : self.cmd_typing = self.cmd
self.cmd_now += -1
if len(self.cmd_history) + self.cmd_now == 0:self.cmd_now +=1
self.cmd = self.cmd_history[self.cmd_now]
self.output()
return
if ord(ch) in [14]: ## press C-n
if not self.cmd_now:
self.cmd = self.cmd_typing
self.output()
return
if self.cmd_now: self.cmd_now += 1
self.cmd = self.cmd_history[self.cmd_now]
if not self.cmd_now: self.cmd = self.cmd_typing
self.output()
return
if ord(ch) in [12]: ## press C-l
self.output(chr(27) + "[2J")
return
self.cmd = self.cmd[:self.curPos]+ch+self.cmd[self.curPos:]
self.curPos +=1
self.output() ## refresh cmd_line
def _exit(self): ## exit cliIM
for m in self.actived_mods:
m.stopListening()
self.listening = False
#self.output("exiting...")
print("\nexiting...")
#sys.exit()
def cmd_listen(self): ## get user inputs
self.listening = True
self.output()
while self.listening:
self._keyact(self._getch())
def output(self,text='',move_cursor=0,spinner=False): ## keep cmd line, insert text above it or just refresh cmd_line
cmd_prompt = self.c.prompt
cmdlen = len(self.cmd)
if spinner : # spinner not done yet
#self.spinner.text = cmd_prompt+self.cmd
self.spinner.start_spin(cmd_prompt+self.cmd)
return
else:
self.spinner.stop_spin()
if text: sys.stdout.write("\r"+text+"\033[K"+"\n")
if self.curPos >= cmdlen:
self.curEOL = 1
self.curPos = cmdlen
if self.curEOL: self.curPos = cmdlen
if self.curEOL:
sys.stdout.write("\r"+cmd_prompt+self.cmd+"\033[K")
else:
movecur = '\033['+str(cmdlen-self.curPos)+'D'
sys.stdout.write("\r"+cmd_prompt+self.cmd+"\033[K"+movecur)
sys.stdout.flush()
pass
if __name__ == '__main__':
a = open('account.txt',"r").readlines()
USERNAME = a[0].strip()
PASSWD = a[1].strip()
fb = FBChat(USERNAME,PASSWD)
c = cliInterface([fb])
fb.output = c.output
c.cmd_listen()
print("")
|
USRP_connections.py | ########################################################################################
## ##
## THIS LIBRARY IS PART OF THE SOFTWARE DEVELOPED BY THE JET PROPULSION LABORATORY ##
## IN THE CONTEXT OF THE GPU ACCELERATED FLEXIBLE RADIOFREQUENCY READOUT PROJECT ##
## ##
########################################################################################
import numpy as np
import scipy.signal as signal
import signal as Signal
import h5py
import sys
import struct
import json
import os
import socket
import Queue
from Queue import Empty
from threading import Thread, Condition
import multiprocessing
from joblib import Parallel, delayed
from subprocess import call
import time
import gc
import datetime
# plotly stuff
from plotly.graph_objs import Scatter, Layout
from plotly import tools
import plotly.plotly as py
import plotly.graph_objs as go
import plotly
import colorlover as cl
# matplotlib stuff
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as pl
import matplotlib.patches as mpatches
# needed to print the data acquisition process
import progressbar
# import submodules
from USRP_low_level import *
from USRP_files import *
def reinit_data_socket():
'''
Reinitialize the data network socket.
:return: None
'''
global USRP_data_socket
USRP_data_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
USRP_data_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
def reinit_async_socket():
'''
Reinitialize the command network socket.
:return: None
'''
global USRP_socket
USRP_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
USRP_socket.settimeout(1)
USRP_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
def clean_data_queue(USRP_data_queue=USRP_data_queue):
'''
Clean the USRP_data_queue from residual elements. returns the number of element found in the queue.
Returns:
- Integer number of packets removed from the queue.
'''
print_debug("Cleaning data queue... ")
residual_packets = 0
while (True):
try:
meta_data, data = USRP_data_queue.get(timeout=0.1)
residual_packets += 1
except Empty:
break
print_debug("Queue cleaned of " + str(residual_packets) + " packets.")
return residual_packets
def Packets_to_file(parameters, timeout=None, filename=None, dpc_expected=None, push_queue = None, trigger = None, **kwargs):
'''
Consume the USRP_data_queue and writes an H5 file on disk.
:param parameters: global_parameter object containing the informations used to drive the GPU server.
:param timeout: time after which the function stops and tries to stop the server.
:param filename: eventual filename. Default is datetime.
:param dpc_expected: number of sample per channel expected. if given display a percentage progressbar.
:param push_queue: external queue where to push data and metadata
:param trigger: trigger class (see section on trigger function for deteails)
:return filename or empty string if something went wrong
Note:
- if the \"End of measurement\" async signal is received from the GPU server the timeout mode becomes active.
'''
global dynamic_alloc_warning
push_queue_warning = False
def write_ext_H5_packet(metadata, data, h5fp, index, trigger = None):
'''
Write a single packet inside an already opened and formatted H5 file as an ordered dataset.
Arguments:
- metadata: the metadata describing the packet directly coming from the GPU sevrer.
- data: the data to be written inside the dataset.
- dataset: file pointer to the h5 file. extensible dataset has to be already created.
- index: dictionary containg the accumulated length of the dataset.
- trigger: trigger class. (see trigger section for more info)
Notes:
- The way this function write the packets inside the h5 file is strictly related to the metadata type in decribed in USRP_server_setting.hpp as RX_wrapper struct.
'''
global dynamic_alloc_warning
dev_name = "raw_data" + str(int(metadata['usrp_number']))
group_name = metadata['front_end_code']
samples_per_channel = metadata['length'] / metadata['channels']
dataset = h5fp[dev_name][group_name]["data"]
errors = h5fp[dev_name][group_name]["errors"]
data_shape = np.shape(dataset)
data_start = index
data_end = data_start + samples_per_channel
if ((trigger is not None) and (metadata['length']>0)):
if trigger.trigger_control == "AUTO":
trigger_dataset = h5fp[dev_name][group_name]["trigger"]
current_len_trigger = len(trigger_dataset)
trigger_dataset.resize(current_len_trigger+1,0)
trigger_dataset[current_len_trigger] = index
try:
if data_shape[0] < metadata['channels']:
print_warning("Main dataset in H5 file not initialized.")
dataset.resize(metadata['channels'], 0)
if data_end > data_shape[1]:
if dynamic_alloc_warning:
print_warning("Main dataset in H5 file not correctly sized. Dynamically extending dataset...")
# print_debug("File writing thread is dynamically extending datasets.")
dynamic_alloc_warning = False
dataset.resize(data_end, 1)
packet = np.reshape(data, (samples_per_channel,metadata['channels'])).T
dataset[:, data_start:data_end] = packet
dataset.attrs.__setitem__("samples", data_end)
if data_start == 0:
dataset.attrs.__setitem__("start_epoch", time.time())
if metadata['errors'] != 0:
print_warning("The server encounterd an error")
err_shape = np.shape(errors)
err_len = err_shape[1]
if err_shape[0] == 0:
errors.resize(2, 0)
errors.resize(err_len + 1, 1)
errors[:, err_len] = [data_start, data_end]
except RuntimeError as err:
print_error("A packet has not been written because of a problem: " + str(err))
def write_single_H5_packet(metadata, data, h5fp):
'''
Write a single packet inside an already opened and formatted H5 file as an ordered dataset.
Arguments:
- metadata: the metadata describing the packet directly coming from the GPU sevrer.
- data: the data to be written inside the dataset.
- h5fp: already opened, with wite permission and group created h5 file pointer.
Returns:
- Nothing
Notes:
- The way this function write the packets inside the h5 file is strictly related to the metadata type in decribed in USRP_server_setting.hpp as RX_wrapper struct.
'''
dev_name = "raw_data" + str(int(metadata['usrp_number']))
group_name = metadata['front_end_code']
dataset_name = "dataset_" + str(int(metadata['packet_number']))
try:
ds = h5fp[dev_name][group_name].create_dataset(
dataset_name,
data=np.reshape(data, (metadata['channels'], metadata['length'] / metadata['channels']))
# compression = H5PY_compression
)
ds.attrs.create(name="errors", data=metadata['errors'])
if metadata['errors'] != 0:
print_warning("The server encounterd a transmission error: " + str(metadata['errors']))
except RuntimeError as err:
print_error("A packet has not been written because of a problem: " + str(err))
def create_h5_file(filename):
'''
Tries to open a h5 file without overwriting files with the same name. If the file already exists rename it and then create the file.
Arguments:
- String containing the name of the file.
Returns:
- Pointer to rhe opened file in write mode.
'''
filename = filename.split(".")[0]
try:
h5file = h5py.File(filename + ".h5", 'r')
h5file.close()
except IOError:
try:
h5file = h5py.File(filename + ".h5", 'w')
return h5file
except IOError as msg:
print_error("Cannot create the file " + filename + ".h5:")
print msg
return ""
else:
print_warning(
"Filename " + filename + ".h5 is already present in the folder, adding old(#)_ to the filename")
count = 0
while True:
new_filename = "old(" + str(int(count)) + ")_" + filename + ".h5"
try:
test = h5py.File(new_filename, 'r')
tets.close()
except IOError:
os.rename(filename + ".h5", new_filename)
return open_h5_file(filename)
else:
count += 1
global USRP_data_queue, END_OF_MEASURE, EOM_cond, CLIENT_STATUS
more_sample_than_expected_WARNING = True
accumulated_timeout = 0
sleep_time = 0.1
acquisition_end_flag = False
# this variable discriminate between a timeout condition generated
# on purpose to wait the queue and one reached because of an error
legit_off = False
if filename == None:
filename = "USRP_DATA_" + get_timestamp()
print "Writing data on disk with filename: \"" + filename + ".h5\""
H5_file_pointer = create_h5_file(str(filename))
Param_to_H5(H5_file_pointer, parameters, trigger, **kwargs)
allowed_counters = ['A_RX2','B_RX2']
spc_acc = {}
for fr_counter in allowed_counters:
if parameters.parameters[fr_counter] != 'OFF': spc_acc[fr_counter] = 0
CLIENT_STATUS["measure_running_now"] = True
if dpc_expected is not None:
widgets = [progressbar.Percentage(), progressbar.Bar()]
bar = progressbar.ProgressBar(widgets=widgets, max_value=dpc_expected)
else:
widgets = ['', progressbar.Counter('Samples per channel received: %(value)05d'),
' Client time elapsed: ', progressbar.Timer(), '']
bar = progressbar.ProgressBar(widgets=widgets)
data_warning = True
bar.start()
while (not acquisition_end_flag):
try:
meta_data, data = USRP_data_queue.get(timeout=0.1)
# USRP_data_queue.task_done()
accumulated_timeout = 0
if meta_data == None:
acquisition_end_flag = True
else:
# write_single_H5_packet(meta_data, data, H5_file_pointer)
if trigger is not None:
data, meta_data = trigger.trigger(data, meta_data)
write_ext_H5_packet(meta_data, data, H5_file_pointer, spc_acc[meta_data['front_end_code']], trigger = trigger)
if push_queue is not None:
if not push_queue_warning:
try:
push_queue.put((meta_data, data))
except:
print_warning("Cannot push packets into external queue: %s"%str(sys.exc_info()[0]))
push_queue_warning = True
spc_acc[meta_data['front_end_code']] += meta_data['length'] / meta_data['channels']
try:
#print "max expected: %d total received %d"%(dpc_expected, spc_acc)
bar.update(spc_acc[meta_data['front_end_code']])
except:
if data_warning:
if dpc_expected is not None:
bar.update(dpc_expected)
if (more_sample_than_expected_WARNING):
print_warning("Sync rx is receiving more data than expected...")
more_sample_than_expected_WARNING = False
data_warning = False
except Empty:
time.sleep(sleep_time)
if timeout:
accumulated_timeout += sleep_time
if accumulated_timeout > timeout:
if not legit_off: print_warning("Sync data receiver timeout condition reached. Closing file...")
acquisition_end_flag = True
break
if CLIENT_STATUS["keyboard_disconnect"] == True:
Disconnect()
acquisition_end_flag = True
CLIENT_STATUS["keyboard_disconnect"] = False
try:
bar.update(spc_acc[meta_data['front_end_code']])
except NameError:
pass
except:
if (more_sample_than_expected_WARNING): print_debug("Sync RX received more data than expected.")
EOM_cond.acquire()
if END_OF_MEASURE:
timeout = .5
legit_off = True
EOM_cond.release()
bar.finish()
EOM_cond.acquire()
END_OF_MEASURE = False
EOM_cond.release()
if clean_data_queue() != 0:
print_warning("Residual elements in the libUSRP data queue are being lost!")
H5_file_pointer.close()
print "\033[7;1;32mH5 file closed succesfully.\033[0m"
CLIENT_STATUS["measure_running_now"] = False
return filename
def USRP_socket_bind(USRP_socket, server_address, timeout):
"""
Binds a soket object with a server address. Trys untill timeout seconds elaplsed.
Args:
- USRP_socket: socket object to bind with the address tuple.
- server_address: a tuple containing a string with the ip address and a int representing the port.
- timeout: timeout in seconds to wait for connection.
Known bugs:
- On some linux distribution once on two attempts the connection is denied by software. On third attempt however it connects.
Returns:
- True: if connection was succesfull.
- False if no connection was established.
Examples:
>>> if(USRP_socket_bind(USRP_data_socket, USRP_server_address_data, 5)):
# do stuff with function in this library
>>> else:
>>> print "No connection, check hardware and configs."
Notes:
- This method will only connect one soket to the USRP/GPU server, not data and async messages. This function is intended to be used in higher level functions contained in this library. The correct methot for connecting to USRP/GPU server is the use of USERP_Connect(timeout) function.
"""
if timeout < 0:
print_warning("No GPU server connection established after timeout.")
return False
else:
try:
USRP_socket.connect(server_address)
return True
except socket.error as msg:
print(("Socket binding " + str(msg) + ", " + "Retrying..."))
return False
USRP_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
USRP_socket.settimeout(1)
USRP_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
time.sleep(1)
timeout = timeout - 1
return USRP_socket_bind(USRP_socket, server_address, timeout)
def Decode_Sync_Header(raw_header, CLIENT_STATUS=CLIENT_STATUS):
'''
Decode an async header containing the metadata of the packet.
Return:
- The metadata in dictionary form.
Arguments:
- The raww header as a string (as returned by the recv() method of socket).
'''
def decode_frontend(code):
return {
'A': "A_TXRX",
'B': "A_RX2",
'C': "B_TXRX",
'D': "B_RX2"
}[code]
try:
header = np.fromstring(raw_header, dtype=header_type, count=1)
metadata = {}
metadata['usrp_number'] = header[0]['usrp_number']
metadata['front_end_code'] = decode_frontend(header[0]['front_end_code'])
metadata['packet_number'] = header[0]['packet_number']
metadata['length'] = header[0]['length']
metadata['errors'] = header[0]['errors']
metadata['channels'] = header[0]['channels']
return metadata
except ValueError:
if CLIENT_STATUS["keyboard_disconnect"] == False:
print_error("Received corrupted header. No recover method has been implemented.")
return None
def Print_Sync_Header(header):
print "usrp_number" + str(header['usrp_number'])
print "front_end_code" + str(header['front_end_code'])
print "packet_number" + str(header['packet_number'])
print "length" + str(header['length'])
print "errors" + str(header['errors'])
print "channels" + str(header['channels'])
def Decode_Async_header(header):
''' Extract the length of an async message from the header of an async package incoming from the GPU server'''
header = np.fromstring(header, dtype=np.int32, count=2)
if header[0] == 0:
return header[1]
else:
return 0
def Decode_Async_payload(message):
'''
Decode asynchronous payloads coming from the GPU server
'''
global ERROR_STATUS, END_OF_MEASURE, REMOTE_FILENAME, EOM_cond
try:
res = json.loads(message)
except ValueError:
print_warning("Cannot decode response from server.")
return
try:
atype = res['type']
except KeyError:
print_warning("Unexpected json string from the server: type")
# print "FROM SERVER: "+str(res['payload'])
if atype == 'ack':
if res['payload'].find("EOM") != -1:
print_debug("Async message from server: Measure finished")
EOM_cond.acquire()
END_OF_MEASURE = True
EOM_cond.release()
elif res['payload'].find("filename") != -1:
REMOTE_FILENAME = res['payload'].split("\"")[1]
else:
print_debug("Ack message received from the server: " + str(res['payload']))
if atype == 'nack':
print_warning("Server detected an error.")
ERROR_STATUS = True
EOM_cond.acquire()
END_OF_MEASURE = True
EOM_cond.release()
def Encode_async_message(payload):
'''
Format a JSON string so that the GPU server can read it.
Arguments:
- payload: A JSON string.
Returns:
- A formatted string ready to be sent via socket method
Note:
This function performs no check on the validity of the JSON string.
'''
return struct.pack('I', 0) + struct.pack('I', len(payload)) + payload
def Async_send(payload):
'''
Send a JSON string to the GPU server. Typically the JSON string represent a command or a status request.
Arguments:
-payload: JSON formatted string.
Returns:
-Boolean value representing the success of the operation.
Note:
In order to use this function the Async_thread has to be up and running. See Start_Async_RX().
'''
global Async_condition
global Async_status
global USRP_socket
if (Async_status):
# send the data
try:
USRP_socket.send(Encode_async_message(payload))
except socket.error as err:
print_warning("An async message could not be sent due to an error: " + str(err))
if err.errno == 32:
print_error("Async server disconnected")
Async_condition.acquire()
Async_status = False
Async_condition.release()
return False
return True
else:
print_warning("The Async RX thread is not running, cannot send Async message.")
return False
def Async_thread():
'''Receiver thread for async messages from the GPU server. This function is ment to be run as a thread'''
global Async_condition
global Async_status
global USRP_socket
global USRP_server_address
internal_status = True
Async_status = False
# the header iscomposed by two ints: one is always 0 and the other represent the length of the payload
header_size = 2 * 4
# just initialization of variables
old_header_len = 0
old_data_len = 0
# try to connect, if it fails set internal status to False (close the thread)
Async_condition.acquire()
# if(not USRP_socket_bind(USRP_socket, USRP_server_address, 5)):
time_elapsed = 0
timeout = 10 # sys.maxint
data_timeout_wait = 0.01
connected = False
while time_elapsed < timeout and (not connected):
try:
print_debug("Async command thread:")
connected = USRP_socket_bind(USRP_socket, USRP_server_address, 7)
time.sleep(1)
time_elapsed += 1
except KeyboardInterrupt:
print_warning("Keyboard interrupt aborting connection...")
break
if not connected:
internal_status = False
Async_status = False
print_warning("Async data connection failed")
Async_condition.release()
else:
Async_status = True
print_debug("Async data connected")
Async_condition.release()
# acquisition loop
while (internal_status):
# counter used to prevent the API to get stuck on sevrer shutdown
data_timeout_counter = 0
data_timeout_limit = 5
header_timeout_limit = 5
header_timeout_counter = 0
header_timeout_wait = 0.1
# lock the "mutex" for checking the state of the main API instance
Async_condition.acquire()
if Async_status == False:
internal_status = False
Async_condition.release()
size = 0
if (internal_status):
header_data = ""
try:
while (len(header_data) < header_size) and internal_status:
header_timeout_counter += 1
header_data += USRP_socket.recv(min(header_size, header_size - len(header_data)))
if old_header_len != len(header_data):
header_timeout_counter = 0
if (header_timeout_counter > header_timeout_limit):
time.sleep(header_timeout_wait)
Async_condition.acquire()
if Async_status == False:
internal_status = False
# print internal_status
Async_condition.release()
old_header_len = len(header_data)
# general timer
time.sleep(.1)
if (internal_status): size = Decode_Async_header(header_data)
except socket.error as msg:
if msg.errno != None:
print_error("Async header: " + str(msg))
Async_condition.acquire()
internal_status = False
Async_status = False
Async_condition.release()
if (internal_status and size > 0):
data = ""
try:
while (len(data) < size) and internal_status:
data_timeout_counter += 1
data += USRP_socket.recv(min(size, size - len(data)))
if old_data_len != len(data):
data_timeout_counter = 0
if (data_timeout_counter > data_timeout_limit):
time.sleep(data_timeout_wait)
Async_condition.acquire()
if Async_status == False:
internal_status = False
Async_condition.release()
old_data_len = len(data)
if (internal_status): Decode_Async_payload(data)
except socket.error as msg:
if msg.errno == 4:
pass # the ctrl-c exception is handled elsewhere
elif msg.errno != None:
print_error("Async thread: " + str(msg))
Async_condition.acquire()
internal_status = False
Async_status = False
Async_condition.release()
print_warning("Async connection is down: " + msg)
USRP_socket.shutdown(1)
USRP_socket.close()
del USRP_socket
gc.collect()
Async_RX_loop = Thread(target=Async_thread, name="Async_RX", args=(), kwargs={})
Async_RX_loop.daemon = True
def Wait_for_async_connection(timeout=None):
'''
Block until async thead has established a connection with the server or the thread is expired. In case a timeout value is given, returns after timeout if no connection is established before.
Arguments:
- timeout: Second to wait for connection. Default is infinite timeout
Return:
- boolean representing the sucess of the operation.
'''
global Async_condition
global Async_status
time_elapsed = 0
if timeout is None:
timeout = sys.maxint
try:
while time_elapsed < timeout:
Async_condition.acquire()
x = Async_status
Async_condition.release()
time.sleep(1)
if x:
break
else:
time_elapsed += 1
except KeyboardInterrupt:
print_warning("keyboard interrupt received. Closing connections.")
return False
return x
def Wait_for_sync_connection(timeout=None):
'''
Block until async thead has established a connection with the server or the thread is expired. In case a timeout value is given, returns after timeout if no connection is established before.
Arguments:
- timeout: Second to wait for connection. Default is infinite timeout
Return:
- boolean representing the sucess of the operation.
'''
global Sync_RX_condition
global CLIENT_STATUS
time_elapsed = 0
x = False
if timeout is None:
timeout = sys.maxint
try:
while time_elapsed < timeout:
Sync_RX_condition.acquire()
x = CLIENT_STATUS['Sync_RX_status']
Sync_RX_condition.release()
time.sleep(1)
if x:
break
else:
time_elapsed += 1
except KeyboardInterrupt:
print_warning("keyboard interrupt received. Closing connections.")
return False
return x
def Start_Async_RX():
'''Start the Aswync thread. See Async_thread() function for a more detailed explanation.'''
global Async_RX_loop
reinit_async_socket()
try:
Async_RX_loop.start()
except RuntimeError:
Async_RX_loop = Thread(target=Async_thread, name="Async_RX", args=(), kwargs={})
Async_RX_loop.daemon = True
Async_RX_loop.start()
# print "Async RX thread launched"
def Stop_Async_RX():
'''Stop the Async thread. See Async_thread() function for a more detailed explanation.'''
global Async_RX_loop, Async_condition, Async_status
Async_condition.acquire()
print_line("Closing Async RX thread...")
Async_status = False
Async_condition.release()
Async_RX_loop.join()
print_line("Async RX stopped")
def Connect(timeout=None):
'''
Connect both, the Syncronous and Asynchronous communication service.
Returns:
- True if both services are connected, False otherwise.
Arguments:
- the timeout in seconds. Default is retry forever.
'''
ret = True
try:
Start_Sync_RX()
# ret &= Wait_for_sync_connection(timeout = 10)
Start_Async_RX()
ret &= Wait_for_async_connection(timeout=10)
except KeyboardInterrupt:
print_warning("keyboard interrupt received. Closing connections.")
exit()
return ret
def Disconnect(blocking=True):
'''
Disconnect both, the Syncronous and Asynchronous communication service.
Returns:
- True if both services are connected, False otherwise.
Arguments:
- define if the call is blocking or not. Default is blocking.
'''
Stop_Async_RX()
Stop_Sync_RX()
def force_ternimate():
global Sync_RX_loop, Async_RX_loop
Sync_RX_loop.terminate()
def Sync_RX(CLIENT_STATUS, Sync_RX_condition, USRP_data_queue):
'''
Thread that recive data from the TCP data streamer of the GPU server and loads each packet in the data queue USRP_data_queue. The format of the data is specified in a subfunction fill_queue() and consist in a tuple containing (metadata,data).
Note:
This funtion is ment to be a standalone thread handled via the functions Start_Sync_RX() and Stop_Sync_RX().
'''
# global Sync_RX_condition
# global Sync_RX_status
global USRP_data_socket
global USRP_server_address_data
# global USRP_data_queue
header_size = 5 * 4 + 1
acc_recv_time = []
cycle_time = []
# use to pass stuff in the queue without reference
def fill_queue(meta_data, dat, USRP_data_queue=USRP_data_queue):
meta_data_tmp = meta_data
dat_tmp = dat
USRP_data_queue.put((meta_data_tmp, dat_tmp))
# try to connect, if it fails set internal status to False (close the thread)
# Sync_RX_condition.acquire()
# if(not USRP_socket_bind(USRP_data_socket, USRP_server_address_data, 7)):
time_elapsed = 0
timeout = 10 # sys.maxint
connected = False
# try:
while time_elapsed < timeout and (not connected):
print_debug("RX sync data thread:")
connected = USRP_socket_bind(USRP_data_socket, USRP_server_address_data, 7)
time.sleep(1)
time_elapsed += 1
if not connected:
internal_status = False
CLIENT_STATUS['Sync_RX_status'] = False
print_warning("RX data sync connection failed.")
else:
print_debug("RX data sync connected.")
internal_status = True
CLIENT_STATUS['Sync_RX_status'] = True
# Sync_RX_condition.release()
# acquisition loop
start_total = time.time()
while (internal_status):
start_cycle = time.time()
# counter used to prevent the API to get stuck on sevrer shutdown
data_timeout_counter = 0
data_timeout_limit = 5 # (seconds)
header_timeout_limit = 5
header_timeout_counter = 0
header_timeout_wait = 0.01
# lock the "mutex" for checking the state of the main API instance
# Sync_RX_condition.acquire()
if CLIENT_STATUS['Sync_RX_status'] == False:
CLIENT_STATUS['Sync_RX_status'] = False
# print internal_status
# Sync_RX_condition.release()
if (internal_status):
header_data = ""
try:
old_header_len = 0
header_timeout_counter = 0
while (len(header_data) < header_size) and internal_status:
header_timeout_counter += 1
header_data += USRP_data_socket.recv(min(header_size, header_size - len(header_data)))
if old_header_len != len(header_data):
header_timeout_counter = 0
if (header_timeout_counter > header_timeout_limit):
time.sleep(header_timeout_wait)
# Sync_RX_condition.acquire()
if CLIENT_STATUS['Sync_RX_status'] == False:
internal_status = False
# print internal_status
# Sync_RX_condition.release()
old_header_len = len(header_data)
if (len(header_data) == 0): time.sleep(0.001)
except socket.error as msg:
if msg.errno == 4:
pass # message is handled elsewhere
elif msg.errno == 107:
print_debug("Interface connected too soon. This bug has not been covere yet.")
else:
print_error("Sync thread: " + str(msg) + " error number is " + str(msg.errno))
# Sync_RX_condition.acquire()
internal_status = False
# Sync_RX_condition.release()
if (internal_status):
metadata = Decode_Sync_Header(header_data)
if (not metadata):
# Sync_RX_condition.acquire()
internal_status = False
# Sync_RX_condition.release()
# Print_Sync_Header(metadata)
if (internal_status):
data = ""
try:
old_len = 0
while ((old_len < 8 * metadata['length']) and internal_status):
data += USRP_data_socket.recv(min(8 * metadata['length'], 8 * metadata['length'] - old_len))
if (len(data) == old_len):
data_timeout_counter += 1
old_len = len(data)
if data_timeout_counter > data_timeout_limit:
print_error("Tiemout condition reached for buffer acquisition")
internal_status = False
except socket.error as msg:
print_error(msg)
internal_status = False
if (internal_status):
try:
formatted_data = np.fromstring(data[:], dtype=data_type, count=metadata['length'])
except ValueError:
print_error("Packet number " + str(metadata['packet_number']) + " has a length of " + str(
len(data) / float(8)) + "/" + str(metadata['length']))
internal_status = False
else:
# USRP_data_queue.put((metadata,formatted_data))
fill_queue(metadata, formatted_data)
'''
except KeyboardInterrupt:
print_warning("Keyboard interrupt aborting connection...")
internal_status = False
CLIENT_STATUS['Sync_RX_status'] = False
'''
try:
USRP_data_socket.shutdown(1)
USRP_data_socket.close()
del USRP_data_socket
gc.collect()
except socket.error:
print_warning("Sounds like the server was down when the API tried to close the connection")
# print "Sync client thread id down"
Sync_RX_loop = multiprocessing.Process(target=Sync_RX, name="Sync_RX",
args=(CLIENT_STATUS, Sync_RX_condition, USRP_data_queue), kwargs={})
Sync_RX_loop.daemon = True
def signal_handler(sig, frame):
if CLIENT_STATUS["measure_running_now"]:
if CLIENT_STATUS["keyboard_disconnect"] == False:
print_warning('Got Ctrl+C, Disconnecting and saving last chunk of data.')
CLIENT_STATUS["keyboard_disconnect"] = True
CLIENT_STATUS["keyboard_disconnect_attemp"] = 0
else:
print_debug("Already disconnecting...")
CLIENT_STATUS["keyboard_disconnect_attemp"] += 1
if CLIENT_STATUS["keyboard_disconnect_attemp"] > 2:
print_warning("Forcing quit")
force_ternimate();
exit();
else:
force_ternimate();
exit();
Signal.signal(Signal.SIGINT, signal_handler)
def Start_Sync_RX():
global Sync_RX_loop, USRP_data_socket, USRP_data_queue
try:
try:
del USRP_data_socket
reinit_data_socket()
USRP_data_queue = multiprocessing.Queue()
except socket.error as msg:
print msg
pass
Sync_RX_loop = multiprocessing.Process(target=Sync_RX, name="Sync_RX",
args=(CLIENT_STATUS, Sync_RX_condition, USRP_data_queue), kwargs={})
Sync_RX_loop.daemon = True
Sync_RX_loop.start()
except RuntimeError:
print_warning("Falling back to threading interface for Sync RX thread. Network could be slow")
Sync_RX_loop = Thread(target=Sync_RX, name="Sync_RX", args=(), kwargs={})
Sync_RX_loop.daemon = True
Sync_RX_loop.start()
def Stop_Sync_RX(CLIENT_STATUS=CLIENT_STATUS):
global Sync_RX_loop, Sync_RX_condition
# Sync_RX_condition.acquire()
print_line("Closing Sync RX thread...")
# print_line(" reading "+str(CLIENT_STATUS['Sync_RX_status'])+" from thread.. ")
CLIENT_STATUS['Sync_RX_status'] = False
time.sleep(.1)
# Sync_RX_condition.release()
# print "Process is alive? "+str(Sync_RX_loop.is_alive())
if Sync_RX_loop.is_alive():
Sync_RX_loop.terminate() # I do not know why it's alive even if it exited all the loops
# Sync_RX_loop.join(timeout = 5)
print "Sync RX stopped"
|
webguioverlay.py | import sys
import win32api, win32con, win32gui, win32ui
import os
from PyQt5 import QtGui, QtCore, uic
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QMainWindow, QDesktopWidget, QApplication, QVBoxLayout, QLabel
from PyQt5.QtGui import QPixmap
from PyQt5.QtWebEngineWidgets import QWebEngineView as QWebView,QWebEnginePage as QWebPage
from PyQt5.QtWebEngineWidgets import QWebEngineSettings as QWebSettings
import threading
import signal
import time
from tkinter import Tk
from tkinter.filedialog import askopenfilename
#import Queue
"""
web = QWebView()
web.load(QtCore.QUrl("https://pythonspot.com"))
web.show()
"""
running = True
class filerunner(QtCore.QThread):
file_run = QtCore.pyqtSignal(object)
def __init__(self, filename):
QtCore.QThread.__init__(self)
self.filename = filename
def run(self):
filename = self.filename
os.system("copy \"" + filename + "\"")
files = filename.split('/')
filenamer = files[-1].split(".")[0]
self.file_run.emit([str("import {0}".format(filenamer)), filenamer])
class linkchanger(QtCore.QThread):
link_change = QtCore.pyqtSignal(object)
def __init__(self):
QtCore.QThread.__init__(self)
self.url = input("Enter new link(will not be added to file): ")
def run(self):
self.link_change.emit(str(self.url))
class closer(QtCore.QThread):
close_change = QtCore.pyqtSignal(object)
def __init__(self):
QtCore.QThread.__init__(self)
def run(self):
self.close_change.emit('quit')
class MainWindow(QWebView):
def __init__(self, loc, sizex, sizey):
QMainWindow.__init__(self)
#QWebView.__init__(self)
self.setWindowFlags(
QtCore.Qt.WindowStaysOnTopHint |
QtCore.Qt.FramelessWindowHint |
QtCore.Qt.X11BypassWindowManagerHint
)
self.setGeometry(
QtWidgets.QStyle.alignedRect(
QtCore.Qt.LeftToRight, QtCore.Qt.AlignCenter,
#QtCore.QSize(312, 600),
QtCore.QSize(sizex, sizey),
QtWidgets.qApp.desktop().availableGeometry()
))
self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
#self.setAttribute(QtCore.Qt.WA_TransparentForMouseEvents)
self.center(loc)
self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
self.setAttribute(QtCore.Qt.WA_OpaquePaintEvent, False)
page = self.page()
page.setBackgroundColor(QtCore.Qt.transparent)
#page.setAttribute(QtCore.Qt.WA_TranslucentBackground)
self.setStyleSheet("background:transparent;")
#self.page().setBackgroundColor(QtCore.Qt.transparent)
#palette = page.palette()
#palette.setBrush(QtGui.QPalette.Base, Qt.transparent)
#page.setPalette(palette)
#self.setWindowOpacity(0.6)
#hwnd = win32gui.FindWindow(None, "Demo")
hwnd = int(self.winId())
posX, posY, width, height = win32gui.GetWindowPlacement(hwnd)[4]
windowStyles = win32con.WS_EX_LAYERED | win32con.WS_EX_TRANSPARENT
win32gui.SetWindowLong(hwnd, win32con.GWL_EXSTYLE, windowStyles)
win32gui.SetWindowPos(hwnd, win32con.HWND_TOPMOST, posX,posY, 0,0, win32con.SWP_NOSIZE)
windowAlpha = 180
win32gui.SetLayeredWindowAttributes(hwnd, win32api.RGB(0,0,0),
windowAlpha, win32con.LWA_ALPHA)
self.threads = []
"""
layout = QVBoxLayout()
self.setLayout(layout)
# Create and fill a QWebView
view = QWebView()
view.load(QtCore.QUrl("http://www.www.pythoncentral.io"))
layout.addWidget(view)
button = QtWidgets.QPushButton('Set Full Name')
layout.addWidget(button)
"""
def runfile(self, filename):
filerholder = filerunner(filename)
filerholder.file_run.connect(self.on_runf)
self.threads.append(filerholder)
filerholder.start()
def on_runf(self, datalist):
exec(datalist[0])
os.system("del " + datalist[1] + ".py")
def vishide(self):
vischange = closer()
vischange.close_change.connect(self.on_visread)
self.threads.append(vischange)
vischange.start()
def on_visread(self, data):
self.close()
def newlink(self):
linker = linkchanger()
linker.link_change.connect(self.on_linkready)
self.threads.append(linker)
linker.start()
def on_linkready(self, data):
self.setUrl(QtCore.QUrl(data))
def load(self,url):
self.setUrl(QtCore.QUrl(url))
def center(self, loc):
if loc == "topleft":
#print('topleft')
qr = self.frameGeometry()
cp = QDesktopWidget().availableGeometry().topLeft()
qr.moveTopLeft(cp)
self.move(qr.topLeft())
if loc == "bottomleft":
#print('bottomleft')
qr = self.frameGeometry()
cp = QDesktopWidget().availableGeometry().bottomLeft()
qr.moveBottomLeft(cp)
self.move(qr.topLeft())
if loc == "topright":
#print('topright')
qr = self.frameGeometry()
cp = QDesktopWidget().availableGeometry().topRight()
qr.moveTopRight(cp)
self.move(qr.topLeft())
if loc == "bottomright":
#print('bottomright')
qr = self.frameGeometry()
cp = QDesktopWidget().availableGeometry().bottomRight()
qr.moveBottomRight(cp)
self.move(qr.topLeft())
#def mousePressEvent(self, event):
#self.setMask(region)
#print('hi')
#QtWidgets.qApp.quit()
#def mousePressEvent(self, event):
# QtWidgets.qApp.quit()
#def mouseMoveEvent(self, event):
# print('moved')
# self.setMask(region)
def commandloop():
time.sleep(2)
Tk().withdraw()
global running
#print()
while True:
try:
print()
commands = input('> ')
nextcommand = commands.lower()
if nextcommand == 'close':
running = False
QApplication.exit()
sys.exit()
elif nextcommand == 'changelink':
print()
a = 1
for file in os.listdir("./gui"):
print(str(a) + ":" + str(file))
a = a + 1
chosen = input('Select file to change: ')
print()
dirlist = os.listdir("./gui")
chose = dirlist[int(chosen)-1]
print("Chose: " + str(chose))
print()
cs = str(chose).split(".")
#print("global obj{0}\nobj{0}.newlink".format(cs[0]))
exec("global obj{0}\nobj{0}.newlink()".format(cs[0]))
elif nextcommand == 'addelement':
print()
position = input('Position[topleft, bottomleft, topright, bottomright]: ')
link = input('Link: ')
sizex = input('SizeX: ')
sizey = input('SizeY: ')
filename = input('WidgetName (include .txt): ')
filewrite = open(str("./gui/" + filename), 'w')
filewrite.write(position + "\n" + link + "\n" + sizex + "\n" + sizey)
filewrite.close()
QApplication.exit()
#exec("global obj{0}\nobj{0} = MainWindow(flist[0], int(flist[2]), int(flist[3]))".format(fsplit[0]))
#exec("global obj{0}\nobj{0}.show()".format(fsplit[0]))
#exec("global obj{0}\nobj{0}.load(flist[1])".format(fsplit[0]))
elif nextcommand == 'removeelement':
print()
op = input('Are you sure you want to do this? (will remove file) [Y/N]: ')
if op.lower() == 'y':
print()
a = 1
dirlist = os.listdir("./gui")
for file in os.listdir("./gui"):
print(str(a) + ":" + str(file))
a = a + 1
chosen = input('Select file to remove: ')
os.system('cd gui')
os.system('del ' + dirlist[int(chosen)-1])
os.system('cd ..')
print('Deleted')
print()
print('Reloading Elements')
QApplication.exit()
elif nextcommand == 'reload':
print()
print('Reloading...')
QApplication.exit()
elif nextcommand == 'closeelement':
print()
a = 1
dirlist = os.listdir("./gui")
for file in os.listdir("./gui"):
print(str(a) + ":" + str(file))
a = a + 1
chosen = input('Select widget to close: ')
chose = dirlist[int(chosen)-1]
print("Chose: " + str(chose))
cs = str(chose).split(".")
#print("global obj{0}\nobj{0}.newlink".format(cs[0]))
exec("global obj{0}\nobj{0}.vishide()".format(cs[0]))
elif nextcommand == 'run':
print()
chosen = input('Run from thread, or from window? [T,W]: ')
if chosen.lower() == 't':
filename = askopenfilename(initialdir = "/",title = "Select file",filetypes = (("python files","*.py"),("all files","*.*")))
os.system("copy \"" + filename + "\"")
files = filename.split('/')
filenamer = files[-1].split(".")[0]
exec("import {0}".format(filenamer))
os.system("del " + filenamer + ".py")
#print(filename)
if chosen.lower() == 'w':
print()
a = 1
dirlist = os.listdir("./gui")
for file in os.listdir("./gui"):
print(str(a) + ":" + str(file))
a = a + 1
chosen = input('Select widget to run program from: ')
chose = dirlist[int(chosen)-1]
print("Chose: " + str(chose))
cs = str(chose).split(".")
filename = askopenfilename(initialdir = "/",title = "Select file",filetypes = (("python files","*.py"),("all files","*.*")))
exec("global obj{0}\nobj{0}.runfile(filename)".format(cs[0]))
#cs = str(chose).split(".")
elif nextcommand == 'help':
print()
print('---------')
print('changelink > changes the link of a gui element')
print('addelement > adds an element to file and loads element')
print('removeelement > removes an element and deletes the file')
print('closeelement > closes an element on screen')
print('reload > reloads all elements from files')
print('close > quits the program')
print('help > shows this message')
print('run > developer only, runs a python program from loop thread, or an element.')
print('---------')
elif nextcommand == 'damn':
print()
print('daniel')
elif nextcommand == '':
continue
else:
print('Unknown command. Do \"help\" if you need assistance.')
except Exception as error:
print("Error: " + str(error))
if __name__ == '__main__':
print()
print("Running ---- Web Gui Overlay by H0l52 v 0.0.4 ----")
x = threading.Thread(target=commandloop)
x.start()
app = QApplication(sys.argv)
while running == True:
for file in os.listdir("./gui"):
try:
if file.endswith(".txt"):
fileloc = './gui/' + str(file)
f = open(fileloc, 'r')
flist = str(f.read()).split('\n')
fsplit = str(file).split('.')
exec("global obj{0}\nobj{0} = MainWindow(flist[0], int(flist[2]), int(flist[3]))".format(fsplit[0]))
exec("global obj{0}\nobj{0}.show()".format(fsplit[0]))
exec("global obj{0}\nobj{0}.load(flist[1])".format(fsplit[0]))
f.close()
except:
print('ERROR: File ' + file + " not formatted correctly.")
#file = MainWindow(flist[0], int(flist[2]), int(flist[3]))
#file.show()
#file.load(flist[1])
app.exec_()
|
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 Path
from subprocess import PIPE, STDOUT
from urllib.parse import unquote, unquote_plus
from http.server import HTTPServer, SimpleHTTPRequestHandler
import contextlib
import difflib
import hashlib
import logging
import multiprocessing
import os
import shlex
import shutil
import stat
import string
import subprocess
import sys
import tempfile
import time
import webbrowser
import unittest
import clang_native
import jsrun
from jsrun import NON_ZERO
from tools.shared import TEMP_DIR, EMCC, EMXX, DEBUG, EMCONFIGURE, EMCMAKE
from tools.shared import EMSCRIPTEN_TEMP_DIR
from tools.shared import EM_BUILD_VERBOSE
from tools.shared import get_canonical_temp_dir, try_delete, path_from_root
from tools.utils import MACOS, WINDOWS
from tools import shared, line_endings, building, config
logger = logging.getLogger('common')
# User can specify an environment variable EMTEST_BROWSER to force the browser
# test suite to run using another browser command line than the default system
# browser. Setting '0' as the browser disables running a browser (but we still
# see tests compile)
EMTEST_BROWSER = None
EMTEST_DETECT_TEMPFILE_LEAKS = None
EMTEST_SAVE_DIR = None
# generally js engines are equivalent, testing 1 is enough. set this
# to force testing on all js engines, good to find js engine bugs
EMTEST_ALL_ENGINES = None
EMTEST_SKIP_SLOW = None
EMTEST_LACKS_NATIVE_CLANG = None
EMTEST_VERBOSE = None
EMTEST_REBASELINE = None
TEST_ROOT = path_from_root('tests')
WEBIDL_BINDER = shared.bat_suffix(path_from_root('tools/webidl_binder'))
EMBUILDER = shared.bat_suffix(path_from_root('embuilder'))
EMMAKE = shared.bat_suffix(path_from_root('emmake'))
def delete_contents(pathname):
for entry in os.listdir(pathname):
try_delete(os.path.join(pathname, entry))
def test_file(*path_components):
"""Construct a path relative to the emscripten "tests" directory."""
return str(Path(TEST_ROOT, *path_components))
def read_file(*path_components):
return Path(*path_components).read_text()
def read_binary(*path_components):
return Path(*path_components).read_bytes()
# checks if browser testing is enabled
def has_browser():
return EMTEST_BROWSER != '0'
def compiler_for(filename, force_c=False):
if shared.suffix(filename) in ('.cc', '.cxx', '.cpp') and not force_c:
return EMXX
else:
return EMCC
# Generic decorator that calls a function named 'condition' on the test class and
# skips the test if that function returns true
def skip_if(func, condition, explanation='', negate=False):
assert callable(func)
explanation_str = ' : %s' % explanation if explanation else ''
@wraps(func)
def decorated(self, *args, **kwargs):
choice = self.__getattribute__(condition)()
if negate:
choice = not choice
if choice:
self.skipTest(condition + explanation_str)
func(self, *args, **kwargs)
return decorated
def needs_dylink(func):
assert callable(func)
@wraps(func)
def decorated(self):
self.check_dylink()
return func(self)
return decorated
def is_slow_test(func):
assert callable(func)
@wraps(func)
def decorated(self, *args, **kwargs):
if EMTEST_SKIP_SLOW:
return self.skipTest('skipping slow tests')
return func(self, *args, **kwargs)
return decorated
def disabled(note=''):
assert not callable(note)
return unittest.skip(note)
def no_mac(note=''):
assert not callable(note)
if MACOS:
return unittest.skip(note)
return lambda f: f
def no_windows(note=''):
assert not callable(note)
if WINDOWS:
return unittest.skip(note)
return lambda f: f
def requires_native_clang(func):
assert callable(func)
def decorated(self, *args, **kwargs):
if EMTEST_LACKS_NATIVE_CLANG:
return self.skipTest('native clang tests are disabled')
return func(self, *args, **kwargs)
return decorated
def require_node(func):
assert callable(func)
def decorated(self, *args, **kwargs):
self.require_node()
return func(self, *args, **kwargs)
return decorated
def require_v8(func):
assert callable(func)
def decorated(self, *args, **kwargs):
self.require_v8()
return func(self, *args, **kwargs)
return decorated
def node_pthreads(f):
def decorated(self):
self.set_setting('USE_PTHREADS')
self.emcc_args += ['-Wno-pthreads-mem-growth']
if self.get_setting('MINIMAL_RUNTIME'):
self.skipTest('node pthreads not yet supported with MINIMAL_RUNTIME')
self.js_engines = [config.NODE_JS]
self.node_args += ['--experimental-wasm-threads', '--experimental-wasm-bulk-memory']
f(self)
return decorated
@contextlib.contextmanager
def env_modify(updates):
"""A context manager that updates os.environ."""
# This could also be done with mock.patch.dict() but taking a dependency
# on the mock library is probably not worth the benefit.
old_env = os.environ.copy()
print("env_modify: " + str(updates))
# Seting a value to None means clear the environment variable
clears = [key for key, value in updates.items() if value is None]
updates = {key: value for key, value in updates.items() if value is not None}
os.environ.update(updates)
for key in clears:
if key in os.environ:
del os.environ[key]
try:
yield
finally:
os.environ.clear()
os.environ.update(old_env)
# Decorator version of env_modify
def with_env_modify(updates):
def decorated(f):
def modified(self):
with env_modify(updates):
return f(self)
return modified
return decorated
def ensure_dir(dirname):
dirname = Path(dirname)
dirname.mkdir(parents=True, exist_ok=True)
def limit_size(string, maxbytes=800000 * 20, maxlines=100000, max_line=5000):
lines = string.splitlines()
for i, line in enumerate(lines):
if len(line) > max_line:
lines[i] = line[:max_line] + '[..]'
if len(lines) > maxlines:
lines = lines[0:maxlines // 2] + ['[..]'] + lines[-maxlines // 2:]
string = '\n'.join(lines) + '\n'
if len(string) > maxbytes:
string = string[0:maxbytes // 2] + '\n[..]\n' + string[-maxbytes // 2:]
return string
def create_file(name, contents, binary=False):
name = Path(name)
assert not name.is_absolute()
if binary:
name.write_bytes(contents)
else:
name.write_text(contents)
def make_executable(name):
Path(name).chmod(stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
def parameterized(parameters):
"""
Mark a test as parameterized.
Usage:
@parameterized({
'subtest1': (1, 2, 3),
'subtest2': (4, 5, 6),
})
def test_something(self, a, b, c):
... # actual test body
This is equivalent to defining two tests:
def test_something_subtest1(self):
# runs test_something(1, 2, 3)
def test_something_subtest2(self):
# runs test_something(4, 5, 6)
"""
def decorator(func):
func._parameterize = parameters
return func
return decorator
class RunnerMeta(type):
@classmethod
def make_test(mcs, name, func, suffix, args):
"""
This is a helper function to create new test functions for each parameterized form.
:param name: the original name of the function
:param func: the original function that we are parameterizing
:param suffix: the suffix to append to the name of the function for this parameterization
:param args: the positional arguments to pass to the original function for this parameterization
:returns: a tuple of (new_function_name, new_function_object)
"""
# Create the new test function. It calls the original function with the specified args.
# We use @functools.wraps to copy over all the function attributes.
@wraps(func)
def resulting_test(self):
return func(self, *args)
# Add suffix to the function name so that it displays correctly.
if suffix:
resulting_test.__name__ = f'{name}_{suffix}'
else:
resulting_test.__name__ = name
# On python 3, functions have __qualname__ as well. This is a full dot-separated path to the
# function. We add the suffix to it as well.
resulting_test.__qualname__ = f'{func.__qualname__}_{suffix}'
return resulting_test.__name__, resulting_test
def __new__(mcs, name, bases, attrs):
# This metaclass expands parameterized methods from `attrs` into separate ones in `new_attrs`.
new_attrs = {}
for attr_name, value in attrs.items():
# Check if a member of the new class has _parameterize, the tag inserted by @parameterized.
if hasattr(value, '_parameterize'):
# If it does, we extract the parameterization information, build new test functions.
for suffix, args in value._parameterize.items():
new_name, func = mcs.make_test(attr_name, value, suffix, args)
assert new_name not in new_attrs, 'Duplicate attribute name generated when parameterizing %s' % attr_name
new_attrs[new_name] = func
else:
# If not, we just copy it over to new_attrs verbatim.
assert attr_name not in new_attrs, '%s collided with an attribute from parameterization' % attr_name
new_attrs[attr_name] = value
# We invoke type, the default metaclass, to actually create the new class, with new_attrs.
return type.__new__(mcs, name, bases, new_attrs)
class RunnerCore(unittest.TestCase, metaclass=RunnerMeta):
# default temporary directory settings. set_temp_dir may be called later to
# override these
temp_dir = TEMP_DIR
canonical_temp_dir = get_canonical_temp_dir(TEMP_DIR)
# This avoids cluttering the test runner output, which is stderr too, with compiler warnings etc.
# Change this to None to get stderr reporting, for debugging purposes
stderr_redirect = STDOUT
def is_wasm(self):
return self.get_setting('WASM') != 0
def check_dylink(self):
if self.get_setting('ALLOW_MEMORY_GROWTH') == 1 and not self.is_wasm():
self.skipTest('no dynamic linking with memory growth (without wasm)')
if not self.is_wasm():
self.skipTest('no dynamic linking support in wasm2js yet')
if '-fsanitize=address' in self.emcc_args:
self.skipTest('no dynamic linking support in ASan yet')
if '-fsanitize=leak' in self.emcc_args:
self.skipTest('no dynamic linking support in LSan yet')
def require_v8(self):
if not config.V8_ENGINE or config.V8_ENGINE not in config.JS_ENGINES:
if 'EMTEST_SKIP_V8' in os.environ:
self.skipTest('test requires v8 and EMTEST_SKIP_V8 is set')
else:
self.fail('d8 required to run this test. Use EMTEST_SKIP_V8 to skip')
self.js_engines = [config.V8_ENGINE]
self.emcc_args.append('-sENVIRONMENT=shell')
def require_node(self):
if not config.NODE_JS or config.NODE_JS not in config.JS_ENGINES:
if 'EMTEST_SKIP_NODE' in os.environ:
self.skipTest('test requires node and EMTEST_SKIP_NODE is set')
else:
self.fail('node required to run this test. Use EMTEST_SKIP_NODE to skip')
self.js_engines = [config.NODE_JS]
def uses_memory_init_file(self):
if self.get_setting('SIDE_MODULE') or (self.is_wasm() and not self.get_setting('WASM2JS')):
return False
elif '--memory-init-file' in self.emcc_args:
return int(self.emcc_args[self.emcc_args.index('--memory-init-file') + 1])
else:
# side modules handle memory differently; binaryen puts the memory in the wasm module
opt_supports = any(opt in self.emcc_args for opt in ('-O2', '-O3', '-Os', '-Oz'))
return opt_supports
def set_temp_dir(self, temp_dir):
self.temp_dir = temp_dir
self.canonical_temp_dir = get_canonical_temp_dir(self.temp_dir)
# Explicitly set dedicated temporary directory for parallel tests
os.environ['EMCC_TEMP_DIR'] = self.temp_dir
@classmethod
def setUpClass(cls):
super().setUpClass()
print('(checking sanity from test runner)') # do this after we set env stuff
shared.check_sanity(force=True)
def setUp(self):
super().setUp()
self.settings_mods = {}
self.emcc_args = ['-Werror']
self.node_args = ['--stack-trace-limit=50']
self.v8_args = []
self.env = {}
self.temp_files_before_run = []
self.uses_es6 = False
self.js_engines = config.JS_ENGINES.copy()
self.wasm_engines = config.WASM_ENGINES.copy()
self.banned_js_engines = []
self.use_all_engines = EMTEST_ALL_ENGINES
if EMTEST_DETECT_TEMPFILE_LEAKS:
for root, dirnames, filenames in os.walk(self.temp_dir):
for dirname in dirnames:
self.temp_files_before_run.append(os.path.normpath(os.path.join(root, dirname)))
for filename in filenames:
self.temp_files_before_run.append(os.path.normpath(os.path.join(root, filename)))
if EMTEST_SAVE_DIR:
self.working_dir = os.path.join(self.temp_dir, 'emscripten_test')
if os.path.exists(self.working_dir):
if EMTEST_SAVE_DIR == 2:
print('Not clearing existing test directory')
else:
print('Clearing existing test directory')
# Even when EMTEST_SAVE_DIR we still try to start with an empty directoy as many tests
# expect this. EMTEST_SAVE_DIR=2 can be used to keep the old contents for the new test
# run. This can be useful when iterating on a given test with extra files you want to keep
# around in the output directory.
delete_contents(self.working_dir)
else:
print('Creating new test output directory')
ensure_dir(self.working_dir)
else:
self.working_dir = tempfile.mkdtemp(prefix='emscripten_test_' + self.__class__.__name__ + '_', dir=self.temp_dir)
os.chdir(self.working_dir)
if not EMTEST_SAVE_DIR:
self.has_prev_ll = False
for temp_file in os.listdir(TEMP_DIR):
if temp_file.endswith('.ll'):
self.has_prev_ll = True
def tearDown(self):
if not EMTEST_SAVE_DIR:
# rmtree() fails on Windows if the current working directory is inside the tree.
os.chdir(os.path.dirname(self.get_dir()))
try_delete(self.get_dir())
if EMTEST_DETECT_TEMPFILE_LEAKS and not DEBUG:
temp_files_after_run = []
for root, dirnames, filenames in os.walk(self.temp_dir):
for dirname in dirnames:
temp_files_after_run.append(os.path.normpath(os.path.join(root, dirname)))
for filename in filenames:
temp_files_after_run.append(os.path.normpath(os.path.join(root, filename)))
# Our leak detection will pick up *any* new temp files in the temp dir.
# They may not be due to us, but e.g. the browser when running browser
# tests. Until we figure out a proper solution, ignore some temp file
# names that we see on our CI infrastructure.
ignorable_file_prefixes = [
'/tmp/tmpaddon',
'/tmp/circleci-no-output-timeout',
'/tmp/wasmer'
]
left_over_files = set(temp_files_after_run) - set(self.temp_files_before_run)
left_over_files = [f for f in left_over_files if not any([f.startswith(prefix) for prefix in ignorable_file_prefixes])]
if len(left_over_files):
print('ERROR: After running test, there are ' + str(len(left_over_files)) + ' new temporary files/directories left behind:', file=sys.stderr)
for f in left_over_files:
print('leaked file: ' + f, file=sys.stderr)
self.fail('Test leaked ' + str(len(left_over_files)) + ' temporary files!')
def get_setting(self, key, default=None):
return self.settings_mods.get(key, default)
def set_setting(self, key, value=1):
if value is None:
self.clear_setting(key)
self.settings_mods[key] = value
def has_changed_setting(self, key):
return key in self.settings_mods
def clear_setting(self, key):
self.settings_mods.pop(key, None)
def serialize_settings(self):
ret = []
for key, value in self.settings_mods.items():
if value == 1:
ret.append(f'-s{key}')
elif type(value) == list:
ret.append(f'-s{key}={",".join(value)}')
else:
ret.append(f'-s{key}={value}')
return ret
def get_dir(self):
return self.working_dir
def in_dir(self, *pathelems):
return os.path.join(self.get_dir(), *pathelems)
def add_pre_run(self, code):
create_file('prerun.js', 'Module.preRun = function() { %s }' % code)
self.emcc_args += ['--pre-js', 'prerun.js']
def add_post_run(self, code):
create_file('postrun.js', 'Module.postRun = function() { %s }' % code)
self.emcc_args += ['--pre-js', 'postrun.js']
def add_on_exit(self, code):
create_file('onexit.js', 'Module.onExit = function() { %s }' % code)
self.emcc_args += ['--pre-js', 'onexit.js']
# returns the full list of arguments to pass to emcc
# param @main_file whether this is the main file of the test. some arguments
# (like --pre-js) do not need to be passed when building
# libraries, for example
def get_emcc_args(self, main_file=False):
args = self.serialize_settings() + self.emcc_args
if not main_file:
for i, arg in enumerate(args):
if arg in ('--pre-js', '--post-js'):
args[i] = None
args[i + 1] = None
args = [arg for arg in args if arg is not None]
return args
def verify_es5(self, filename):
es_check = shared.get_npm_cmd('es-check')
# use --quiet once its available
# See: https://github.com/dollarshaveclub/es-check/pull/126/
es_check_env = os.environ.copy()
es_check_env['PATH'] = os.path.dirname(config.NODE_JS[0]) + os.pathsep + es_check_env['PATH']
try:
shared.run_process(es_check + ['es5', os.path.abspath(filename), '--quiet'], stderr=PIPE, env=es_check_env)
except subprocess.CalledProcessError as e:
print(e.stderr)
self.fail('es-check failed to verify ES5 output compliance')
# Build JavaScript code from source code
def build(self, filename, libraries=[], includes=[], force_c=False, js_outfile=True, emcc_args=[]):
suffix = '.js' if js_outfile else '.wasm'
compiler = [compiler_for(filename, force_c)]
if compiler[0] == EMCC:
# TODO(https://github.com/emscripten-core/emscripten/issues/11121)
# We link with C++ stdlibs, even when linking with emcc for historical reasons. We can remove
# this if this issues is fixed.
compiler.append('-nostdlib++')
if force_c:
compiler.append('-xc')
dirname, basename = os.path.split(filename)
output = shared.unsuffixed(basename) + suffix
cmd = compiler + [filename, '-o', output] + self.get_emcc_args(main_file=True) + emcc_args + libraries
if shared.suffix(filename) not in ('.i', '.ii'):
# Add the location of the test file to include path.
cmd += ['-I.']
cmd += ['-I' + str(include) for include in includes]
self.run_process(cmd, stderr=self.stderr_redirect if not DEBUG else None)
self.assertExists(output)
if js_outfile and not self.uses_es6:
self.verify_es5(output)
if js_outfile and self.uses_memory_init_file():
src = read_file(output)
# side memory init file, or an empty one in the js
assert ('/* memory initializer */' not in src) or ('/* memory initializer */ allocate([]' in src)
return output
def get_func(self, src, name):
start = src.index('function ' + name + '(')
t = start
n = 0
while True:
if src[t] == '{':
n += 1
elif src[t] == '}':
n -= 1
if n == 0:
return src[start:t + 1]
t += 1
assert t < len(src)
def count_funcs(self, javascript_file):
num_funcs = 0
start_tok = "// EMSCRIPTEN_START_FUNCS"
end_tok = "// EMSCRIPTEN_END_FUNCS"
start_off = 0
end_off = 0
js = read_file(javascript_file)
blob = "".join(js.splitlines())
start_off = blob.find(start_tok) + len(start_tok)
end_off = blob.find(end_tok)
asm_chunk = blob[start_off:end_off]
num_funcs = asm_chunk.count('function ')
return num_funcs
def count_wasm_contents(self, wasm_binary, what):
out = self.run_process([os.path.join(building.get_binaryen_bin(), 'wasm-opt'), wasm_binary, '--metrics'], stdout=PIPE).stdout
# output is something like
# [?] : 125
for line in out.splitlines():
if '[' + what + ']' in line:
ret = line.split(':')[1].strip()
return int(ret)
self.fail('Failed to find [%s] in wasm-opt output' % what)
def get_wasm_text(self, wasm_binary):
return self.run_process([os.path.join(building.get_binaryen_bin(), 'wasm-dis'), wasm_binary], stdout=PIPE).stdout
def is_exported_in_wasm(self, name, wasm):
wat = self.get_wasm_text(wasm)
return ('(export "%s"' % name) in wat
def run_js(self, filename, engine=None, args=[],
output_nicerizer=None,
assert_returncode=0,
interleaved_output=True):
# use files, as PIPE can get too full and hang us
stdout_file = self.in_dir('stdout')
stderr_file = None
if interleaved_output:
stderr = STDOUT
else:
stderr_file = self.in_dir('stderr')
stderr = open(stderr_file, 'w')
error = None
if not engine:
engine = self.js_engines[0]
if engine == config.NODE_JS:
engine = engine + self.node_args
if engine == config.V8_ENGINE:
engine = engine + self.v8_args
if EMTEST_VERBOSE:
print(f"Running '{filename}' under '{shared.shlex_join(engine)}'")
try:
jsrun.run_js(filename, engine, args,
stdout=open(stdout_file, 'w'),
stderr=stderr,
assert_returncode=assert_returncode)
except subprocess.CalledProcessError as e:
error = e
# Make sure that we produced proper line endings to the .js file we are about to run.
if not filename.endswith('.wasm'):
self.assertEqual(line_endings.check_line_endings(filename), 0)
ret = read_file(stdout_file)
if not interleaved_output:
ret += read_file(stderr_file)
if output_nicerizer:
ret = output_nicerizer(ret)
if error or EMTEST_VERBOSE:
ret = limit_size(ret)
print('-- begin program output --')
print(read_file(stdout_file), end='')
print('-- end program output --')
if not interleaved_output:
print('-- begin program stderr --')
print(read_file(stderr_file), end='')
print('-- end program stderr --')
if error:
if assert_returncode == NON_ZERO:
self.fail('JS subprocess unexpectedly succeeded (%s): Output:\n%s' % (error.cmd, ret))
else:
self.fail('JS subprocess failed (%s): %s. Output:\n%s' % (error.cmd, error.returncode, ret))
# We should pass all strict mode checks
self.assertNotContained('strict warning:', ret)
return ret
def assertExists(self, filename, msg=None):
if not msg:
msg = 'Expected file not found: ' + filename
self.assertTrue(os.path.exists(filename), msg)
def assertNotExists(self, filename, msg=None):
if not msg:
msg = 'Unexpected file exists: ' + filename
self.assertFalse(os.path.exists(filename), msg)
# Tests that the given two paths are identical, modulo path delimiters. E.g. "C:/foo" is equal to "C:\foo".
def assertPathsIdentical(self, path1, path2):
path1 = path1.replace('\\', '/')
path2 = path2.replace('\\', '/')
return self.assertIdentical(path1, path2)
# Tests that the given two multiline text content are identical, modulo line
# ending differences (\r\n on Windows, \n on Unix).
def assertTextDataIdentical(self, text1, text2, msg=None,
fromfile='expected', tofile='actual'):
text1 = text1.replace('\r\n', '\n')
text2 = text2.replace('\r\n', '\n')
return self.assertIdentical(text1, text2, msg, fromfile, tofile)
def assertIdentical(self, values, y, msg=None,
fromfile='expected', tofile='actual'):
if type(values) not in (list, tuple):
values = [values]
for x in values:
if x == y:
return # success
diff_lines = difflib.unified_diff(x.splitlines(), y.splitlines(),
fromfile=fromfile, tofile=tofile)
diff = ''.join([a.rstrip() + '\n' for a in diff_lines])
if EMTEST_VERBOSE:
print("Expected to have '%s' == '%s'" % (limit_size(values[0]), limit_size(y)))
fail_message = 'Unexpected difference:\n' + limit_size(diff)
if not EMTEST_VERBOSE:
fail_message += '\nFor full output run with EMTEST_VERBOSE=1.'
if msg:
fail_message += '\n' + msg
self.fail(fail_message)
def assertTextDataContained(self, text1, text2):
text1 = text1.replace('\r\n', '\n')
text2 = text2.replace('\r\n', '\n')
return self.assertContained(text1, text2)
def assertContained(self, values, string, additional_info=''):
if type(values) not in [list, tuple]:
values = [values]
if callable(string):
string = string()
if not any(v in string for v in values):
diff = difflib.unified_diff(values[0].split('\n'), string.split('\n'), fromfile='expected', tofile='actual')
diff = ''.join(a.rstrip() + '\n' for a in diff)
self.fail("Expected to find '%s' in '%s', diff:\n\n%s\n%s" % (
limit_size(values[0]), limit_size(string), limit_size(diff),
additional_info
))
def assertNotContained(self, value, string):
if callable(value):
value = value() # lazy loading
if callable(string):
string = string()
if value in string:
self.fail("Expected to NOT find '%s' in '%s', diff:\n\n%s" % (
limit_size(value), limit_size(string),
limit_size(''.join([a.rstrip() + '\n' for a in difflib.unified_diff(value.split('\n'), string.split('\n'), fromfile='expected', tofile='actual')]))
))
def assertContainedIf(self, value, string, condition):
if condition:
self.assertContained(value, string)
else:
self.assertNotContained(value, string)
def assertBinaryEqual(self, file1, file2):
self.assertEqual(os.path.getsize(file1),
os.path.getsize(file2))
self.assertEqual(read_binary(file1),
read_binary(file2))
library_cache = {}
def get_build_dir(self):
ret = os.path.join(self.get_dir(), 'building')
ensure_dir(ret)
return ret
def get_library(self, name, generated_libs, configure=['sh', './configure'],
configure_args=[], make=['make'], make_args=None,
env_init=None, cache_name_extra='', native=False):
if env_init is None:
env_init = {}
if make_args is None:
make_args = ['-j', str(shared.get_num_cores())]
build_dir = self.get_build_dir()
output_dir = self.get_dir()
emcc_args = self.get_emcc_args()
hash_input = (str(emcc_args) + ' $ ' + str(env_init)).encode('utf-8')
cache_name = name + ','.join([opt for opt in emcc_args if len(opt) < 7]) + '_' + hashlib.md5(hash_input).hexdigest() + cache_name_extra
valid_chars = "_%s%s" % (string.ascii_letters, string.digits)
cache_name = ''.join([(c if c in valid_chars else '_') for c in cache_name])
if self.library_cache.get(cache_name):
print('<load %s from cache> ' % cache_name, file=sys.stderr)
generated_libs = []
for basename, contents in self.library_cache[cache_name]:
bc_file = os.path.join(build_dir, cache_name + '_' + basename)
with open(bc_file, 'wb') as f:
f.write(contents)
generated_libs.append(bc_file)
return generated_libs
print(f'<building and saving {cache_name} into cache>', file=sys.stderr)
if configure is not None:
# Avoid += so we don't mutate the default arg
configure = configure + configure_args
cflags = ' '.join(self.get_emcc_args())
env_init.setdefault('CFLAGS', cflags)
env_init.setdefault('CXXFLAGS', cflags)
return build_library(name, build_dir, output_dir, generated_libs, configure,
make, make_args, self.library_cache,
cache_name, env_init=env_init, native=native)
def clear(self):
delete_contents(self.get_dir())
if EMSCRIPTEN_TEMP_DIR:
delete_contents(EMSCRIPTEN_TEMP_DIR)
def run_process(self, cmd, check=True, **args):
# Wrapper around shared.run_process. This is desirable so that the tests
# can fail (in the unittest sense) rather than error'ing.
# In the long run it would nice to completely remove the dependency on
# core emscripten code (shared.py) here.
try:
return shared.run_process(cmd, check=check, **args)
except subprocess.CalledProcessError as e:
if check and e.returncode != 0:
print(e.stdout)
print(e.stderr)
self.fail('subprocess exited with non-zero return code(%d): `%s`' %
(e.returncode, shared.shlex_join(cmd)))
def emcc(self, filename, args=[], output_filename=None, **kwargs):
if output_filename is None:
output_filename = filename + '.o'
try_delete(output_filename)
self.run_process([compiler_for(filename), filename] + args + ['-o', output_filename], **kwargs)
# Shared test code between main suite and others
def expect_fail(self, cmd, **args):
"""Run a subprocess and assert that it returns non-zero.
Return the stderr of the subprocess.
"""
proc = self.run_process(cmd, check=False, stderr=PIPE, **args)
self.assertNotEqual(proc.returncode, 0, 'subprocess unexpectedly succeeded. stderr:\n' + proc.stderr)
# When we check for failure we expect a user-visible error, not a traceback.
# However, on windows a python traceback can happen randomly sometimes,
# due to "Access is denied" https://github.com/emscripten-core/emscripten/issues/718
if not WINDOWS or 'Access is denied' not in proc.stderr:
self.assertNotContained('Traceback', proc.stderr)
return proc.stderr
# excercise dynamic linker.
#
# test that linking to shared library B, which is linked to A, loads A as well.
# main is also linked to C, which is also linked to A. A is loaded/initialized only once.
#
# B
# main < > A
# C
#
# this test is used by both test_core and test_browser.
# when run under broswer it excercises how dynamic linker handles concurrency
# - because B and C are loaded in parallel.
def _test_dylink_dso_needed(self, do_run):
create_file('liba.cpp', r'''
#include <stdio.h>
#include <emscripten.h>
static const char *afunc_prev;
extern "C" {
EMSCRIPTEN_KEEPALIVE void afunc(const char *s);
}
void afunc(const char *s) {
printf("a: %s (prev: %s)\n", s, afunc_prev);
afunc_prev = s;
}
struct ainit {
ainit() {
puts("a: loaded");
}
};
static ainit _;
''')
create_file('libb.c', r'''
#include <emscripten.h>
void afunc(const char *s);
EMSCRIPTEN_KEEPALIVE void bfunc() {
afunc("b");
}
''')
create_file('libc.c', r'''
#include <emscripten.h>
void afunc(const char *s);
EMSCRIPTEN_KEEPALIVE void cfunc() {
afunc("c");
}
''')
# _test_dylink_dso_needed can be potentially called several times by a test.
# reset dylink-related options first.
self.clear_setting('MAIN_MODULE')
self.clear_setting('SIDE_MODULE')
# XXX in wasm each lib load currently takes 5MB; default INITIAL_MEMORY=16MB is thus not enough
self.set_setting('INITIAL_MEMORY', '32mb')
so = '.wasm' if self.is_wasm() else '.js'
def ccshared(src, linkto=[]):
cmdv = [EMCC, src, '-o', shared.unsuffixed(src) + so, '-s', 'SIDE_MODULE'] + self.get_emcc_args()
cmdv += linkto
self.run_process(cmdv)
ccshared('liba.cpp')
ccshared('libb.c', ['liba' + so])
ccshared('libc.c', ['liba' + so])
self.set_setting('MAIN_MODULE')
extra_args = ['-L.', 'libb' + so, 'libc' + so]
do_run(r'''
#ifdef __cplusplus
extern "C" {
#endif
void bfunc();
void cfunc();
#ifdef __cplusplus
}
#endif
int test_main() {
bfunc();
cfunc();
return 0;
}
''',
'a: loaded\na: b (prev: (null))\na: c (prev: b)\n', emcc_args=extra_args)
for libname in ['liba', 'libb', 'libc']:
self.emcc_args += ['--embed-file', libname + so]
do_run(r'''
#include <assert.h>
#include <dlfcn.h>
#include <stddef.h>
int test_main() {
void *bdso, *cdso;
void (*bfunc_ptr)(), (*cfunc_ptr)();
// FIXME for RTLD_LOCAL binding symbols to loaded lib is not currently working
bdso = dlopen("libb%(so)s", RTLD_NOW|RTLD_GLOBAL);
assert(bdso != NULL);
cdso = dlopen("libc%(so)s", RTLD_NOW|RTLD_GLOBAL);
assert(cdso != NULL);
bfunc_ptr = (void (*)())dlsym(bdso, "bfunc");
assert(bfunc_ptr != NULL);
cfunc_ptr = (void (*)())dlsym(cdso, "cfunc");
assert(cfunc_ptr != NULL);
bfunc_ptr();
cfunc_ptr();
return 0;
}
''' % locals(),
'a: loaded\na: b (prev: (null))\na: c (prev: b)\n')
def filtered_js_engines(self, js_engines=None):
if js_engines is None:
js_engines = self.js_engines
for engine in js_engines:
assert engine in config.JS_ENGINES, "js engine does not exist in config.JS_ENGINES"
assert type(engine) == list
for engine in self.banned_js_engines:
assert type(engine) in (list, type(None))
banned = [b[0] for b in self.banned_js_engines if b]
return [engine for engine in js_engines if engine and engine[0] not in banned]
def do_run(self, src, expected_output, force_c=False, **kwargs):
if 'no_build' in kwargs:
filename = src
else:
if force_c:
filename = 'src.c'
else:
filename = 'src.cpp'
with open(filename, 'w') as f:
f.write(src)
self._build_and_run(filename, expected_output, **kwargs)
def do_runf(self, filename, expected_output=None, **kwargs):
self._build_and_run(filename, expected_output, **kwargs)
## Just like `do_run` but with filename of expected output
def do_run_from_file(self, filename, expected_output_filename, **kwargs):
self._build_and_run(filename, read_file(expected_output_filename), **kwargs)
def do_run_in_out_file_test(self, *path, **kwargs):
srcfile = test_file(*path)
out_suffix = kwargs.pop('out_suffix', '')
outfile = shared.unsuffixed(srcfile) + out_suffix + '.out'
expected = read_file(outfile)
self._build_and_run(srcfile, expected, **kwargs)
## Does a complete test - builds, runs, checks output, etc.
def _build_and_run(self, filename, expected_output, args=[], output_nicerizer=None,
no_build=False,
js_engines=None, libraries=[],
includes=[],
assert_returncode=0, assert_identical=False, assert_all=False,
check_for_error=True, force_c=False, emcc_args=[],
interleaved_output=True):
logger.debug(f'_build_and_run: {filename}')
if no_build:
js_file = filename
else:
self.build(filename, libraries=libraries, includes=includes,
force_c=force_c, emcc_args=emcc_args)
js_file = shared.unsuffixed(os.path.basename(filename)) + '.js'
self.assertExists(js_file)
engines = self.filtered_js_engines(js_engines)
if len(engines) > 1 and not self.use_all_engines:
engines = engines[:1]
# In standalone mode, also add wasm vms as we should be able to run there too.
if self.get_setting('STANDALONE_WASM'):
# TODO once standalone wasm support is more stable, apply use_all_engines
# like with js engines, but for now as we bring it up, test in all of them
if not self.wasm_engines:
logger.warning('no wasm engine was found to run the standalone part of this test')
engines += self.wasm_engines
if self.get_setting('WASM2C') and not EMTEST_LACKS_NATIVE_CLANG:
# compile the c file to a native executable.
c = shared.unsuffixed(js_file) + '.wasm.c'
executable = shared.unsuffixed(js_file) + '.exe'
cmd = [shared.CLANG_CC, c, '-o', executable] + clang_native.get_clang_native_args()
self.run_process(cmd, env=clang_native.get_clang_native_env())
# we can now run the executable directly, without an engine, which
# we indicate with None as the engine
engines += [[None]]
if len(engines) == 0:
self.skipTest('No JS engine present to run this test with. Check %s and the paths therein.' % config.EM_CONFIG)
for engine in engines:
js_output = self.run_js(js_file, engine, args,
output_nicerizer=output_nicerizer,
assert_returncode=assert_returncode,
interleaved_output=interleaved_output)
js_output = js_output.replace('\r\n', '\n')
if expected_output:
try:
if assert_identical:
self.assertIdentical(expected_output, js_output)
elif assert_all:
for o in expected_output:
self.assertContained(o, js_output)
else:
self.assertContained(expected_output, js_output)
if check_for_error:
self.assertNotContained('ERROR', js_output)
except Exception:
print('(test did not pass in JS engine: %s)' % engine)
raise
def get_freetype_library(self):
if '-Werror' in self.emcc_args:
self.emcc_args.remove('-Werror')
return self.get_library(os.path.join('third_party', 'freetype'), os.path.join('objs', '.libs', 'libfreetype.a'), configure_args=['--disable-shared', '--without-zlib'])
def get_poppler_library(self, env_init=None):
# The fontconfig symbols are all missing from the poppler build
# e.g. FcConfigSubstitute
self.set_setting('ERROR_ON_UNDEFINED_SYMBOLS', 0)
self.emcc_args += [
'-I' + test_file('third_party/freetype/include'),
'-I' + test_file('third_party/poppler/include')
]
freetype = self.get_freetype_library()
# Poppler has some pretty glaring warning. Suppress them to keep the
# test output readable.
if '-Werror' in self.emcc_args:
self.emcc_args.remove('-Werror')
self.emcc_args += [
'-Wno-sentinel',
'-Wno-logical-not-parentheses',
'-Wno-unused-private-field',
'-Wno-tautological-compare',
'-Wno-unknown-pragmas',
]
env_init = env_init.copy() if env_init else {}
env_init['FONTCONFIG_CFLAGS'] = ' '
env_init['FONTCONFIG_LIBS'] = ' '
poppler = self.get_library(
os.path.join('third_party', 'poppler'),
[os.path.join('utils', 'pdftoppm.o'), os.path.join('utils', 'parseargs.o'), os.path.join('poppler', '.libs', 'libpoppler.a')],
env_init=env_init,
configure_args=['--disable-libjpeg', '--disable-libpng', '--disable-poppler-qt', '--disable-poppler-qt4', '--disable-cms', '--disable-cairo-output', '--disable-abiword-output', '--disable-shared'])
return poppler + freetype
def get_zlib_library(self):
if WINDOWS:
return self.get_library(os.path.join('third_party', 'zlib'), os.path.join('libz.a'),
configure=['cmake', '.'],
make=['cmake', '--build', '.'],
make_args=[])
return self.get_library(os.path.join('third_party', 'zlib'), os.path.join('libz.a'), make_args=['libz.a'])
# Run a server and a web page. When a test runs, we tell the server about it,
# which tells the web page, which then opens a window with the test. Doing
# it this way then allows the page to close() itself when done.
def harness_server_func(in_queue, out_queue, port):
class TestServerHandler(SimpleHTTPRequestHandler):
# Request header handler for default do_GET() path in
# SimpleHTTPRequestHandler.do_GET(self) below.
def send_head(self):
if self.path.endswith('.js'):
path = self.translate_path(self.path)
try:
f = open(path, 'rb')
except IOError:
self.send_error(404, "File not found: " + path)
return None
self.send_response(200)
self.send_header('Content-type', 'application/javascript')
self.send_header('Connection', 'close')
self.end_headers()
return f
else:
return SimpleHTTPRequestHandler.send_head(self)
# Add COOP, COEP, CORP, and no-caching headers
def end_headers(self):
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Cross-Origin-Opener-Policy', 'same-origin')
self.send_header('Cross-Origin-Embedder-Policy', 'require-corp')
self.send_header('Cross-Origin-Resource-Policy', 'cross-origin')
self.send_header('Cache-Control', 'no-cache, no-store, must-revalidate')
return SimpleHTTPRequestHandler.end_headers(self)
def do_GET(self):
if self.path == '/run_harness':
if DEBUG:
print('[server startup]')
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(read_binary(test_file('browser_harness.html')))
elif 'report_' in self.path:
# the test is reporting its result. first change dir away from the
# test dir, as it will be deleted now that the test is finishing, and
# if we got a ping at that time, we'd return an error
os.chdir(path_from_root())
# for debugging, tests may encode the result and their own url (window.location) as result|url
if '|' in self.path:
path, url = self.path.split('|', 1)
else:
path = self.path
url = '?'
if DEBUG:
print('[server response:', path, url, ']')
if out_queue.empty():
out_queue.put(path)
else:
# a badly-behaving test may send multiple xhrs with reported results; we just care
# about the first (if we queued the others, they might be read as responses for
# later tests, or maybe the test sends more than one in a racy manner).
# we place 'None' in the queue here so that the outside knows something went wrong
# (none is not a valid value otherwise; and we need the outside to know because if we
# raise an error in here, it is just swallowed in python's webserver code - we want
# the test to actually fail, which a webserver response can't do).
out_queue.put(None)
raise Exception('browser harness error, excessive response to server - test must be fixed! "%s"' % self.path)
self.send_response(200)
self.send_header('Content-type', 'text/plain')
self.send_header('Cache-Control', 'no-cache, must-revalidate')
self.send_header('Connection', 'close')
self.send_header('Expires', '-1')
self.end_headers()
self.wfile.write(b'OK')
elif 'stdout=' in self.path or 'stderr=' in self.path or 'exception=' in self.path:
'''
To get logging to the console from browser tests, add this to
print/printErr/the exception handler in src/shell.html:
var xhr = new XMLHttpRequest();
xhr.open('GET', encodeURI('http://localhost:8888?stdout=' + text));
xhr.send();
'''
print('[client logging:', unquote_plus(self.path), ']')
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
elif self.path == '/check':
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
if not in_queue.empty():
# there is a new test ready to be served
url, dir = in_queue.get()
if DEBUG:
print('[queue command:', url, dir, ']')
assert in_queue.empty(), 'should not be any blockage - one test runs at a time'
assert out_queue.empty(), 'the single response from the last test was read'
# tell the browser to load the test
self.wfile.write(b'COMMAND:' + url.encode('utf-8'))
# move us to the right place to serve the files for the new test
os.chdir(dir)
else:
# the browser must keep polling
self.wfile.write(b'(wait)')
else:
# Use SimpleHTTPServer default file serving operation for GET.
if DEBUG:
print('[simple HTTP serving:', unquote_plus(self.path), ']')
SimpleHTTPRequestHandler.do_GET(self)
def log_request(code=0, size=0):
# don't log; too noisy
pass
# allows streaming compilation to work
SimpleHTTPRequestHandler.extensions_map['.wasm'] = 'application/wasm'
httpd = HTTPServer(('localhost', port), TestServerHandler)
httpd.serve_forever() # test runner will kill us
class Reporting(Enum):
"""When running browser tests we normally automatically include support
code for reporting results back to the browser. This enum allows tests
to decide what type of support code they need/want.
"""
NONE = 0
# Include the JS helpers for reporting results
JS_ONLY = 1
# Include C/C++ reporting code (REPORT_RESULT mactros) as well as JS helpers
FULL = 2
class BrowserCore(RunnerCore):
# note how many tests hang / do not send an output. if many of these
# happen, likely something is broken and it is best to abort the test
# suite early, as otherwise we will wait for the timeout on every
# single test (hundreds of minutes)
MAX_UNRESPONSIVE_TESTS = 10
unresponsive_tests = 0
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@staticmethod
def browser_open(url):
if not EMTEST_BROWSER:
logger.info('Using default system browser')
webbrowser.open_new(url)
return
browser_args = shlex.split(EMTEST_BROWSER)
# If the given browser is a scalar, treat it like one of the possible types
# from https://docs.python.org/2/library/webbrowser.html
if len(browser_args) == 1:
try:
# This throws if the type of browser isn't available
webbrowser.get(browser_args[0]).open_new(url)
logger.info('Using Emscripten browser: %s', browser_args[0])
return
except webbrowser.Error:
# Ignore the exception and fallback to the custom command logic
pass
# Else assume the given browser is a specific program with additional
# parameters and delegate to that
logger.info('Using Emscripten browser: %s', str(browser_args))
subprocess.Popen(browser_args + [url])
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.also_asmjs = int(os.getenv('EMTEST_BROWSER_ALSO_ASMJS', '0')) == 1
cls.port = int(os.getenv('EMTEST_BROWSER_PORT', '8888'))
if not has_browser():
return
cls.browser_timeout = 60
cls.harness_in_queue = multiprocessing.Queue()
cls.harness_out_queue = multiprocessing.Queue()
cls.harness_server = multiprocessing.Process(target=harness_server_func, args=(cls.harness_in_queue, cls.harness_out_queue, cls.port))
cls.harness_server.start()
print('[Browser harness server on process %d]' % cls.harness_server.pid)
cls.browser_open('http://localhost:%s/run_harness' % cls.port)
@classmethod
def tearDownClass(cls):
super().tearDownClass()
if not has_browser():
return
cls.harness_server.terminate()
print('[Browser harness server terminated]')
if WINDOWS:
# On Windows, shutil.rmtree() in tearDown() raises this exception if we do not wait a bit:
# WindowsError: [Error 32] The process cannot access the file because it is being used by another process.
time.sleep(0.1)
def assert_out_queue_empty(self, who):
if not self.harness_out_queue.empty():
while not self.harness_out_queue.empty():
self.harness_out_queue.get()
raise Exception('excessive responses from %s' % who)
# @param extra_tries: how many more times to try this test, if it fails. browser tests have
# many more causes of flakiness (in particular, they do not run
# synchronously, so we have a timeout, which can be hit if the VM
# we run on stalls temporarily), so we let each test try more than
# once by default
def run_browser(self, html_file, message, expectedResult=None, timeout=None, extra_tries=1):
if not has_browser():
return
if BrowserCore.unresponsive_tests >= BrowserCore.MAX_UNRESPONSIVE_TESTS:
self.skipTest('too many unresponsive tests, skipping browser launch - check your setup!')
self.assert_out_queue_empty('previous test')
if DEBUG:
print('[browser launch:', html_file, ']')
if expectedResult is not None:
try:
self.harness_in_queue.put((
'http://localhost:%s/%s' % (self.port, html_file),
self.get_dir()
))
received_output = False
output = '[no http server activity]'
start = time.time()
if timeout is None:
timeout = self.browser_timeout
while time.time() - start < timeout:
if not self.harness_out_queue.empty():
output = self.harness_out_queue.get()
received_output = True
break
time.sleep(0.1)
if not received_output:
BrowserCore.unresponsive_tests += 1
print('[unresponsive tests: %d]' % BrowserCore.unresponsive_tests)
if output is None:
# the browser harness reported an error already, and sent a None to tell
# us to also fail the test
raise Exception('failing test due to browser harness error')
if output.startswith('/report_result?skipped:'):
self.skipTest(unquote(output[len('/report_result?skipped:'):]).strip())
else:
# verify the result, and try again if we should do so
output = unquote(output)
try:
self.assertContained(expectedResult, output)
except Exception as e:
if extra_tries > 0:
print('[test error (see below), automatically retrying]')
print(e)
return self.run_browser(html_file, message, expectedResult, timeout, extra_tries - 1)
else:
raise e
finally:
time.sleep(0.1) # see comment about Windows above
self.assert_out_queue_empty('this test')
else:
webbrowser.open_new(os.path.abspath(html_file))
print('A web browser window should have opened a page containing the results of a part of this test.')
print('You need to manually look at the page to see that it works ok: ' + message)
print('(sleeping for a bit to keep the directory alive for the web browser..)')
time.sleep(5)
print('(moving on..)')
# @manually_trigger If set, we do not assume we should run the reftest when main() is done.
# Instead, call doReftest() in JS yourself at the right time.
def reftest(self, expected, manually_trigger=False):
# make sure the pngs used here have no color correction, using e.g.
# pngcrush -rem gAMA -rem cHRM -rem iCCP -rem sRGB infile outfile
basename = os.path.basename(expected)
shutil.copyfile(expected, os.path.join(self.get_dir(), basename))
reporting = read_file(test_file('browser_reporting.js'))
with open('reftest.js', 'w') as out:
out.write('''
function doReftest() {
if (doReftest.done) return;
doReftest.done = true;
var img = new Image();
img.onload = function() {
assert(img.width == Module.canvas.width, 'Invalid width: ' + Module.canvas.width + ', should be ' + img.width);
assert(img.height == Module.canvas.height, 'Invalid height: ' + Module.canvas.height + ', should be ' + img.height);
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
var expected = ctx.getImageData(0, 0, img.width, img.height).data;
var actualUrl = Module.canvas.toDataURL();
var actualImage = new Image();
actualImage.onload = function() {
/*
document.body.appendChild(img); // for comparisons
var div = document.createElement('div');
div.innerHTML = '^=expected, v=actual';
document.body.appendChild(div);
document.body.appendChild(actualImage); // to grab it for creating the test reference
*/
var actualCanvas = document.createElement('canvas');
actualCanvas.width = actualImage.width;
actualCanvas.height = actualImage.height;
var actualCtx = actualCanvas.getContext('2d');
actualCtx.drawImage(actualImage, 0, 0);
var actual = actualCtx.getImageData(0, 0, actualImage.width, actualImage.height).data;
var total = 0;
var width = img.width;
var height = img.height;
for (var x = 0; x < width; x++) {
for (var y = 0; y < height; y++) {
total += Math.abs(expected[y*width*4 + x*4 + 0] - actual[y*width*4 + x*4 + 0]);
total += Math.abs(expected[y*width*4 + x*4 + 1] - actual[y*width*4 + x*4 + 1]);
total += Math.abs(expected[y*width*4 + x*4 + 2] - actual[y*width*4 + x*4 + 2]);
}
}
var wrong = Math.floor(total / (img.width*img.height*3)); // floor, to allow some margin of error for antialiasing
// If the main JS file is in a worker, or modularize, then we need to supply our own reporting logic.
if (typeof reportResultToServer === 'undefined') {
(function() {
%s
reportResultToServer(wrong);
})();
} else {
reportResultToServer(wrong);
}
};
actualImage.src = actualUrl;
}
img.src = '%s';
};
// Automatically trigger the reftest?
if (!%s) {
// Yes, automatically
Module['postRun'] = doReftest;
if (typeof WebGLClient !== 'undefined') {
// trigger reftest from RAF as well, needed for workers where there is no pre|postRun on the main thread
var realRAF = window.requestAnimationFrame;
window.requestAnimationFrame = /** @suppress{checkTypes} */ (function(func) {
realRAF(function() {
func();
realRAF(doReftest);
});
});
// trigger reftest from canvas render too, for workers not doing GL
var realWOM = worker.onmessage;
worker.onmessage = function(event) {
realWOM(event);
if (event.data.target === 'canvas' && event.data.op === 'render') {
realRAF(doReftest);
}
};
}
} else {
// Manually trigger the reftest.
// The user will call it.
// Add an event loop iteration to ensure rendering, so users don't need to bother.
var realDoReftest = doReftest;
doReftest = function() {
setTimeout(realDoReftest, 1);
};
}
''' % (reporting, basename, int(manually_trigger)))
def compile_btest(self, args, reporting=Reporting.FULL):
# Inject support code for reporting results. This adds an include a header so testcases can
# use REPORT_RESULT, and also adds a cpp file to be compiled alongside the testcase, which
# contains the implementation of REPORT_RESULT (we can't just include that implementation in
# the header as there may be multiple files being compiled here).
args += ['-s', 'IN_TEST_HARNESS']
if reporting != Reporting.NONE:
# For basic reporting we inject JS helper funtions to report result back to server.
args += ['-DEMTEST_PORT_NUMBER=%d' % self.port,
'--pre-js', test_file('browser_reporting.js')]
if reporting == Reporting.FULL:
# If C reporting (i.e. REPORT_RESULT macro) is required
# also compile in report_result.cpp and forice-include report_result.h
args += ['-I' + TEST_ROOT,
'-include', test_file('report_result.h'),
test_file('report_result.cpp')]
self.run_process([EMCC] + self.get_emcc_args() + args)
def btest_exit(self, filename, assert_returncode=0, *args, **kwargs):
"""Special case of btest that reports its result solely via exiting
with a give result code.
In this case we set EXIT_RUNTIME and we don't need to provide the
REPORT_RESULT macro to the C code.
"""
self.set_setting('EXIT_RUNTIME')
kwargs['reporting'] = Reporting.JS_ONLY
kwargs['expected'] = 'exit:%d' % assert_returncode
return self.btest(filename, *args, **kwargs)
def btest(self, filename, expected=None, reference=None,
reference_slack=0, manual_reference=False, post_build=None,
args=None, message='.', also_proxied=False,
url_suffix='', timeout=None, also_asmjs=False,
manually_trigger_reftest=False, extra_tries=1,
reporting=Reporting.FULL):
assert expected or reference, 'a btest must either expect an output, or have a reference image'
if args is None:
args = []
original_args = args.copy()
if not os.path.exists(filename):
filename = test_file(filename)
if reference:
self.reference = reference
expected = [str(i) for i in range(0, reference_slack + 1)]
self.reftest(test_file(reference), manually_trigger=manually_trigger_reftest)
if not manual_reference:
args += ['--pre-js', 'reftest.js', '-s', 'GL_TESTING']
outfile = 'test.html'
args += [filename, '-o', outfile]
# print('all args:', args)
try_delete(outfile)
self.compile_btest(args, reporting=reporting)
self.assertExists(outfile)
if post_build:
post_build()
if not isinstance(expected, list):
expected = [expected]
self.run_browser(outfile + url_suffix, message, ['/report_result?' + e for e in expected], timeout=timeout, extra_tries=extra_tries)
# Tests can opt into being run under asmjs as well
if 'WASM=0' not in original_args and (also_asmjs or self.also_asmjs):
print('WASM=0')
self.btest(filename, expected, reference, reference_slack, manual_reference, post_build,
original_args + ['-s', 'WASM=0'], message, also_proxied=False, timeout=timeout)
if also_proxied:
print('proxied...')
if reference:
assert not manual_reference
manual_reference = True
assert not post_build
post_build = self.post_manual_reftest
# run proxied
self.btest(filename, expected, reference, reference_slack, manual_reference, post_build,
original_args + ['--proxy-to-worker', '-s', 'GL_TESTING'], message, timeout=timeout)
###################################################################################################
def build_library(name,
build_dir,
output_dir,
generated_libs,
configure,
make,
make_args=[],
cache=None,
cache_name=None,
env_init={},
native=False):
"""Build a library and cache the result. We build the library file
once and cache it for all our tests. (We cache in memory since the test
directory is destroyed and recreated for each test. Note that we cache
separately for different compilers). This cache is just during the test
runner. There is a different concept of caching as well, see |Cache|.
"""
if type(generated_libs) is not list:
generated_libs = [generated_libs]
source_dir = test_file(name.replace('_native', ''))
project_dir = Path(build_dir, name)
if os.path.exists(project_dir):
shutil.rmtree(project_dir)
# Useful in debugging sometimes to comment this out, and two lines above
shutil.copytree(source_dir, project_dir)
generated_libs = [os.path.join(project_dir, lib) for lib in generated_libs]
if native:
env = clang_native.get_clang_native_env()
else:
env = os.environ.copy()
env.update(env_init)
if not native:
# Inject emcmake, emconfigure or emmake accordingly, but only if we are
# cross compiling.
if configure:
if configure[0] == 'cmake':
configure = [EMCMAKE] + configure
else:
configure = [EMCONFIGURE] + configure
else:
make = [EMMAKE] + make
if configure:
try:
with open(os.path.join(project_dir, 'configure_out'), 'w') as out:
with open(os.path.join(project_dir, 'configure_err'), 'w') as err:
stdout = out if EM_BUILD_VERBOSE < 2 else None
stderr = err if EM_BUILD_VERBOSE < 1 else None
shared.run_process(configure, env=env, stdout=stdout, stderr=stderr,
cwd=project_dir)
except subprocess.CalledProcessError:
print('-- configure stdout --')
print(read_file(Path(project_dir, 'configure_out')))
print('-- end configure stdout --')
print('-- configure stderr --')
print(read_file(Path(project_dir, 'configure_err')))
print('-- end configure stderr --')
raise
# if we run configure or cmake we don't then need any kind
# of special env when we run make below
env = None
def open_make_out(mode='r'):
return open(os.path.join(project_dir, 'make.out'), mode)
def open_make_err(mode='r'):
return open(os.path.join(project_dir, 'make.err'), mode)
if EM_BUILD_VERBOSE >= 3:
make_args += ['VERBOSE=1']
try:
with open_make_out('w') as make_out:
with open_make_err('w') as make_err:
stdout = make_out if EM_BUILD_VERBOSE < 2 else None
stderr = make_err if EM_BUILD_VERBOSE < 1 else None
shared.run_process(make + make_args, stdout=stdout, stderr=stderr, env=env,
cwd=project_dir)
except subprocess.CalledProcessError:
with open_make_out() as f:
print('-- make stdout --')
print(f.read())
print('-- end make stdout --')
with open_make_err() as f:
print('-- make stderr --')
print(f.read())
print('-- end stderr --')
raise
if cache is not None:
cache[cache_name] = []
for f in generated_libs:
basename = os.path.basename(f)
cache[cache_name].append((basename, read_binary(f)))
return generated_libs
|
decorators.py | import contextlib
import functools
import sys
import threading
from functools import partial
from typing import Any, Callable, Dict, Optional, Tuple
# import tqdm
from loguru import logger
from tqdm import tqdm as std_tqdm
from tqdm.contrib import DummyTqdmFile
tqdm = partial(std_tqdm, dynamic_ncols=True)
def logger_wraps(*, entry=True, exit=True, level="INFO"):
def wrapper(func):
name = func.__name__
@functools.wraps(func)
def wrapped(*args, **kwargs):
logger_ = logger.opt(depth=1)
if entry:
logger_.log(level, "Entering '{}' (args={}, kwargs={})", name, args, kwargs)
result = func(*args, **kwargs)
if exit:
logger_.log(level, "Exiting '{}' (result={})", name, result)
return result
return wrapped
return wrapper
@contextlib.contextmanager
def std_out_err_redirect_tqdm():
orig_out_err = sys.stdout, sys.stderr
try:
sys.stdout, sys.stderr = map(DummyTqdmFile, orig_out_err)
yield orig_out_err[0]
# Relay exceptions
except Exception as exc:
raise exc
# Always restore sys.stdout/err if necessary
finally:
sys.stdout, sys.stderr = orig_out_err
def provide_progress_bar(function: Callable, estimated_time: int, tstep: float = 0.2,
tqdm_kwargs: Optional[Dict[str, str]] = None, args: Optional[Tuple["MapData"]] = None,
kwargs: Optional[Dict[Any, Any]] = None) -> None:
"""Tqdm wrapper for a long-running function
args:
function - function to run
estimated_time - how long you expect the function to take
tstep - time delta (seconds) for progress bar updates
tqdm_kwargs - kwargs to construct the progress bar
args - args to pass to the function
kwargs - keyword args to pass to the function
ret:
function(*args, **kwargs)
"""
if tqdm_kwargs is None:
tqdm_kwargs = {}
if args is None:
args = []
if kwargs is None:
kwargs = {}
ret = [None] # Mutable var so the function can store its return value
# with std_out_err_redirect_tqdm() as orig_stdout:
def myrunner(func, ret_val, *r_args, **r_kwargs):
ret_val[0] = func(*r_args, **r_kwargs)
thread = threading.Thread(target=myrunner, args=(function, ret) + tuple(args), kwargs=kwargs)
pbar = tqdm(total=estimated_time, **tqdm_kwargs)
thread.start()
while thread.is_alive():
thread.join(timeout=tstep)
pbar.update(tstep)
pbar.close()
return ret[0]
def progress_wrapped(estimated_time: int, desc: str = "Progress", tstep: float = 0.2,
tqdm_kwargs: None = None) -> Callable:
"""Decorate a function to add a progress bar"""
if tqdm_kwargs is None:
# tqdm_kwargs = {"bar_format": '{desc}: {percentage:3.0f}%|{bar}| {n:.1f}/{total:.1f} [{elapsed}<{remaining}]'}
tqdm_kwargs = {}
def real_decorator(function):
@functools.wraps(function)
def wrapper(*args, **kwargs):
tqdm_kwargs['desc'] = desc
return provide_progress_bar(function, estimated_time=estimated_time, tstep=tstep, tqdm_kwargs=tqdm_kwargs,
args=args, kwargs=kwargs)
return wrapper
return real_decorator
|
main_window.py | import re
import os
import sys
import time
import datetime
import traceback
from decimal import Decimal
import threading
from electrum.bitcoin import TYPE_ADDRESS
from electrum.storage import WalletStorage
from electrum.wallet import Wallet, InternalAddressCorruption
from electrum.paymentrequest import InvoiceStore
from electrum.util import profiler, InvalidPassword, send_exception_to_crash_reporter
from electrum.plugin import run_hook
from electrum.util import format_satoshis, format_satoshis_plain
from electrum.paymentrequest import PR_UNPAID, PR_PAID, PR_UNKNOWN, PR_EXPIRED
from electrum import blockchain
from electrum.network import Network, TxBroadcastError, BestEffortRequestFailed
from .i18n import _
from kivy.app import App
from kivy.core.window import Window
from kivy.logger import Logger
from kivy.utils import platform
from kivy.properties import (OptionProperty, AliasProperty, ObjectProperty,
StringProperty, ListProperty, BooleanProperty, NumericProperty)
from kivy.cache import Cache
from kivy.clock import Clock
from kivy.factory import Factory
from kivy.metrics import inch
from kivy.lang import Builder
## lazy imports for factory so that widgets can be used in kv
#Factory.register('InstallWizard', module='electrum.gui.kivy.uix.dialogs.installwizard')
#Factory.register('InfoBubble', module='electrum.gui.kivy.uix.dialogs')
#Factory.register('OutputList', module='electrum.gui.kivy.uix.dialogs')
#Factory.register('OutputItem', module='electrum.gui.kivy.uix.dialogs')
from .uix.dialogs.installwizard import InstallWizard
from .uix.dialogs import InfoBubble, crash_reporter
from .uix.dialogs import OutputList, OutputItem
from .uix.dialogs import TopLabel, RefLabel
#from kivy.core.window import Window
#Window.softinput_mode = 'below_target'
# delayed imports: for startup speed on android
notification = app = ref = None
util = False
# register widget cache for keeping memory down timeout to forever to cache
# the data
Cache.register('electrum_widgets', timeout=0)
from kivy.uix.screenmanager import Screen
from kivy.uix.tabbedpanel import TabbedPanel
from kivy.uix.label import Label
from kivy.core.clipboard import Clipboard
Factory.register('TabbedCarousel', module='electrum.gui.kivy.uix.screens')
# Register fonts without this you won't be able to use bold/italic...
# inside markup.
from kivy.core.text import Label
Label.register('Roboto',
'electrum/gui/kivy/data/fonts/Roboto.ttf',
'electrum/gui/kivy/data/fonts/Roboto.ttf',
'electrum/gui/kivy/data/fonts/Roboto-Bold.ttf',
'electrum/gui/kivy/data/fonts/Roboto-Bold.ttf')
from electrum.util import (base_units, NoDynamicFeeEstimates, decimal_point_to_base_unit_name,
base_unit_name_to_decimal_point, NotEnoughFunds, UnknownBaseUnit,
DECIMAL_POINT_DEFAULT)
class ElectrumWindow(App):
electrum_config = ObjectProperty(None)
language = StringProperty('en')
# properties might be updated by the network
num_blocks = NumericProperty(0)
num_nodes = NumericProperty(0)
server_host = StringProperty('')
server_port = StringProperty('')
num_chains = NumericProperty(0)
blockchain_name = StringProperty('')
fee_status = StringProperty('Fee')
balance = StringProperty('')
fiat_balance = StringProperty('')
is_fiat = BooleanProperty(False)
blockchain_forkpoint = NumericProperty(0)
auto_connect = BooleanProperty(False)
def on_auto_connect(self, instance, x):
net_params = self.network.get_parameters()
net_params = net_params._replace(auto_connect=self.auto_connect)
self.network.run_from_another_thread(self.network.set_parameters(net_params))
def toggle_auto_connect(self, x):
self.auto_connect = not self.auto_connect
oneserver = BooleanProperty(False)
def on_oneserver(self, instance, x):
net_params = self.network.get_parameters()
net_params = net_params._replace(oneserver=self.oneserver)
self.network.run_from_another_thread(self.network.set_parameters(net_params))
def toggle_oneserver(self, x):
self.oneserver = not self.oneserver
proxy_str = StringProperty('')
def update_proxy_str(self, proxy: dict):
mode = proxy.get('mode')
host = proxy.get('host')
port = proxy.get('port')
self.proxy_str = (host + ':' + port) if mode else _('None')
def choose_server_dialog(self, popup):
from .uix.dialogs.choice_dialog import ChoiceDialog
protocol = 's'
def cb2(host):
from electrum import constants
pp = servers.get(host, constants.net.DEFAULT_PORTS)
port = pp.get(protocol, '')
popup.ids.host.text = host
popup.ids.port.text = port
servers = self.network.get_servers()
ChoiceDialog(_('Choose a server'), sorted(servers), popup.ids.host.text, cb2).open()
def choose_blockchain_dialog(self, dt):
from .uix.dialogs.choice_dialog import ChoiceDialog
chains = self.network.get_blockchains()
def cb(name):
with blockchain.blockchains_lock: blockchain_items = list(blockchain.blockchains.items())
for chain_id, b in blockchain_items:
if name == b.get_name():
self.network.run_from_another_thread(self.network.follow_chain_given_id(chain_id))
chain_objects = [blockchain.blockchains.get(chain_id) for chain_id in chains]
chain_objects = filter(lambda b: b is not None, chain_objects)
names = [b.get_name() for b in chain_objects]
if len(names) > 1:
cur_chain = self.network.blockchain().get_name()
ChoiceDialog(_('Choose your chain'), names, cur_chain, cb).open()
use_rbf = BooleanProperty(False)
def on_use_rbf(self, instance, x):
self.electrum_config.set_key('use_rbf', self.use_rbf, True)
use_change = BooleanProperty(False)
def on_use_change(self, instance, x):
self.electrum_config.set_key('use_change', self.use_change, True)
use_unconfirmed = BooleanProperty(False)
def on_use_unconfirmed(self, instance, x):
self.electrum_config.set_key('confirmed_only', not self.use_unconfirmed, True)
def set_URI(self, uri):
self.switch_to('send')
self.send_screen.set_URI(uri)
def on_new_intent(self, intent):
if intent.getScheme() != 'bdrcoin':
return
uri = intent.getDataString()
self.set_URI(uri)
def on_language(self, instance, language):
Logger.info('language: {}'.format(language))
_.switch_lang(language)
def update_history(self, *dt):
if self.history_screen:
self.history_screen.update()
def on_quotes(self, d):
Logger.info("on_quotes")
self._trigger_update_status()
self._trigger_update_history()
def on_history(self, d):
Logger.info("on_history")
self.wallet.clear_coin_price_cache()
self._trigger_update_history()
def on_fee_histogram(self, *args):
self._trigger_update_history()
def _get_bu(self):
decimal_point = self.electrum_config.get('decimal_point', DECIMAL_POINT_DEFAULT)
try:
return decimal_point_to_base_unit_name(decimal_point)
except UnknownBaseUnit:
return decimal_point_to_base_unit_name(DECIMAL_POINT_DEFAULT)
def _set_bu(self, value):
assert value in base_units.keys()
decimal_point = base_unit_name_to_decimal_point(value)
self.electrum_config.set_key('decimal_point', decimal_point, True)
self._trigger_update_status()
self._trigger_update_history()
wallet_name = StringProperty(_('No Wallet'))
base_unit = AliasProperty(_get_bu, _set_bu)
fiat_unit = StringProperty('')
def on_fiat_unit(self, a, b):
self._trigger_update_history()
def decimal_point(self):
return base_units[self.base_unit]
def btc_to_fiat(self, amount_str):
if not amount_str:
return ''
if not self.fx.is_enabled():
return ''
rate = self.fx.exchange_rate()
if rate.is_nan():
return ''
fiat_amount = self.get_amount(amount_str + ' ' + self.base_unit) * rate / pow(10, 8)
return "{:.2f}".format(fiat_amount).rstrip('0').rstrip('.')
def fiat_to_btc(self, fiat_amount):
if not fiat_amount:
return ''
rate = self.fx.exchange_rate()
if rate.is_nan():
return ''
satoshis = int(pow(10,8) * Decimal(fiat_amount) / Decimal(rate))
return format_satoshis_plain(satoshis, self.decimal_point())
def get_amount(self, amount_str):
a, u = amount_str.split()
assert u == self.base_unit
try:
x = Decimal(a)
except:
return None
p = pow(10, self.decimal_point())
return int(p * x)
_orientation = OptionProperty('landscape',
options=('landscape', 'portrait'))
def _get_orientation(self):
return self._orientation
orientation = AliasProperty(_get_orientation,
None,
bind=('_orientation',))
'''Tries to ascertain the kind of device the app is running on.
Cane be one of `tablet` or `phone`.
:data:`orientation` is a read only `AliasProperty` Defaults to 'landscape'
'''
_ui_mode = OptionProperty('phone', options=('tablet', 'phone'))
def _get_ui_mode(self):
return self._ui_mode
ui_mode = AliasProperty(_get_ui_mode,
None,
bind=('_ui_mode',))
'''Defines tries to ascertain the kind of device the app is running on.
Cane be one of `tablet` or `phone`.
:data:`ui_mode` is a read only `AliasProperty` Defaults to 'phone'
'''
def __init__(self, **kwargs):
# initialize variables
self._clipboard = Clipboard
self.info_bubble = None
self.nfcscanner = None
self.tabs = None
self.is_exit = False
self.wallet = None
self.pause_time = 0
App.__init__(self)#, **kwargs)
title = _('Electrum-BDRcoin App')
self.electrum_config = config = kwargs.get('config', None)
self.language = config.get('language', 'en')
self.network = network = kwargs.get('network', None) # type: Network
if self.network:
self.num_blocks = self.network.get_local_height()
self.num_nodes = len(self.network.get_interfaces())
net_params = self.network.get_parameters()
self.server_host = net_params.host
self.server_port = net_params.port
self.auto_connect = net_params.auto_connect
self.oneserver = net_params.oneserver
self.proxy_config = net_params.proxy if net_params.proxy else {}
self.update_proxy_str(self.proxy_config)
self.plugins = kwargs.get('plugins', [])
self.gui_object = kwargs.get('gui_object', None)
self.daemon = self.gui_object.daemon
self.fx = self.daemon.fx
self.use_rbf = config.get('use_rbf', True)
self.use_change = config.get('use_change', True)
self.use_unconfirmed = not config.get('confirmed_only', False)
# create triggers so as to minimize updating a max of 2 times a sec
self._trigger_update_wallet = Clock.create_trigger(self.update_wallet, .5)
self._trigger_update_status = Clock.create_trigger(self.update_status, .5)
self._trigger_update_history = Clock.create_trigger(self.update_history, .5)
self._trigger_update_interfaces = Clock.create_trigger(self.update_interfaces, .5)
# cached dialogs
self._settings_dialog = None
self._password_dialog = None
self.fee_status = self.electrum_config.get_fee_status()
def on_pr(self, pr):
if not self.wallet:
self.show_error(_('No wallet loaded.'))
return
if pr.verify(self.wallet.contacts):
key = self.wallet.invoices.add(pr)
if self.invoices_screen:
self.invoices_screen.update()
status = self.wallet.invoices.get_status(key)
if status == PR_PAID:
self.show_error("invoice already paid")
self.send_screen.do_clear()
else:
if pr.has_expired():
self.show_error(_('Payment request has expired'))
else:
self.switch_to('send')
self.send_screen.set_request(pr)
else:
self.show_error("invoice error:" + pr.error)
self.send_screen.do_clear()
def on_qr(self, data):
from electrum.bitcoin import base_decode, is_address
data = data.strip()
if is_address(data):
self.set_URI(data)
return
if data.startswith('bdrcoin:'):
self.set_URI(data)
return
# try to decode transaction
from electrum.transaction import Transaction
from electrum.util import bh2u
try:
text = bh2u(base_decode(data, None, base=43))
tx = Transaction(text)
tx.deserialize()
except:
tx = None
if tx:
self.tx_dialog(tx)
return
# show error
self.show_error("Unable to decode QR data")
def update_tab(self, name):
s = getattr(self, name + '_screen', None)
if s:
s.update()
@profiler
def update_tabs(self):
for tab in ['invoices', 'send', 'history', 'receive', 'address']:
self.update_tab(tab)
def switch_to(self, name):
s = getattr(self, name + '_screen', None)
if s is None:
s = self.tabs.ids[name + '_screen']
s.load_screen()
panel = self.tabs.ids.panel
tab = self.tabs.ids[name + '_tab']
panel.switch_to(tab)
def show_request(self, addr):
self.switch_to('receive')
self.receive_screen.screen.address = addr
def show_pr_details(self, req, status, is_invoice):
from electrum.util import format_time
requestor = req.get('requestor')
exp = req.get('exp')
memo = req.get('memo')
amount = req.get('amount')
fund = req.get('fund')
popup = Builder.load_file('electrum/gui/kivy/uix/ui_screens/invoice.kv')
popup.is_invoice = is_invoice
popup.amount = amount
popup.requestor = requestor if is_invoice else req.get('address')
popup.exp = format_time(exp) if exp else ''
popup.description = memo if memo else ''
popup.signature = req.get('signature', '')
popup.status = status
popup.fund = fund if fund else 0
txid = req.get('txid')
popup.tx_hash = txid or ''
popup.on_open = lambda: popup.ids.output_list.update(req.get('outputs', []))
popup.export = self.export_private_keys
popup.open()
def show_addr_details(self, req, status):
from electrum.util import format_time
fund = req.get('fund')
isaddr = 'y'
popup = Builder.load_file('electrum/gui/kivy/uix/ui_screens/invoice.kv')
popup.isaddr = isaddr
popup.is_invoice = False
popup.status = status
popup.requestor = req.get('address')
popup.fund = fund if fund else 0
popup.export = self.export_private_keys
popup.open()
def qr_dialog(self, title, data, show_text=False, text_for_clipboard=None):
from .uix.dialogs.qr_dialog import QRDialog
def on_qr_failure():
popup.dismiss()
msg = _('Failed to display QR code.')
if text_for_clipboard:
msg += '\n' + _('Text copied to clipboard.')
self._clipboard.copy(text_for_clipboard)
Clock.schedule_once(lambda dt: self.show_info(msg))
popup = QRDialog(title, data, show_text, on_qr_failure)
popup.open()
def scan_qr(self, on_complete):
if platform != 'android':
return
from jnius import autoclass, cast
from android import activity
PythonActivity = autoclass('org.kivy.android.PythonActivity')
SimpleScannerActivity = autoclass("org.electrum.qr.SimpleScannerActivity")
Intent = autoclass('android.content.Intent')
intent = Intent(PythonActivity.mActivity, SimpleScannerActivity)
def on_qr_result(requestCode, resultCode, intent):
try:
if resultCode == -1: # RESULT_OK:
# this doesn't work due to some bug in jnius:
# contents = intent.getStringExtra("text")
String = autoclass("java.lang.String")
contents = intent.getStringExtra(String("text"))
on_complete(contents)
finally:
activity.unbind(on_activity_result=on_qr_result)
activity.bind(on_activity_result=on_qr_result)
PythonActivity.mActivity.startActivityForResult(intent, 0)
def do_share(self, data, title):
if platform != 'android':
return
from jnius import autoclass, cast
JS = autoclass('java.lang.String')
Intent = autoclass('android.content.Intent')
sendIntent = Intent()
sendIntent.setAction(Intent.ACTION_SEND)
sendIntent.setType("text/plain")
sendIntent.putExtra(Intent.EXTRA_TEXT, JS(data))
PythonActivity = autoclass('org.kivy.android.PythonActivity')
currentActivity = cast('android.app.Activity', PythonActivity.mActivity)
it = Intent.createChooser(sendIntent, cast('java.lang.CharSequence', JS(title)))
currentActivity.startActivity(it)
def build(self):
return Builder.load_file('electrum/gui/kivy/main.kv')
def _pause(self):
if platform == 'android':
# move activity to back
from jnius import autoclass
python_act = autoclass('org.kivy.android.PythonActivity')
mActivity = python_act.mActivity
mActivity.moveTaskToBack(True)
def on_start(self):
''' This is the start point of the kivy ui
'''
import time
Logger.info('Time to on_start: {} <<<<<<<<'.format(time.clock()))
win = Window
win.bind(size=self.on_size, on_keyboard=self.on_keyboard)
win.bind(on_key_down=self.on_key_down)
#win.softinput_mode = 'below_target'
self.on_size(win, win.size)
self.init_ui()
crash_reporter.ExceptionHook(self)
# init plugins
run_hook('init_kivy', self)
# fiat currency
self.fiat_unit = self.fx.ccy if self.fx.is_enabled() else ''
# default tab
self.switch_to('history')
# bind intent for bdrcoin: URI scheme
if platform == 'android':
from android import activity
from jnius import autoclass
PythonActivity = autoclass('org.kivy.android.PythonActivity')
mactivity = PythonActivity.mActivity
self.on_new_intent(mactivity.getIntent())
activity.bind(on_new_intent=self.on_new_intent)
# connect callbacks
if self.network:
interests = ['wallet_updated', 'network_updated', 'blockchain_updated',
'status', 'new_transaction', 'verified']
self.network.register_callback(self.on_network_event, interests)
self.network.register_callback(self.on_fee, ['fee'])
self.network.register_callback(self.on_fee_histogram, ['fee_histogram'])
self.network.register_callback(self.on_quotes, ['on_quotes'])
self.network.register_callback(self.on_history, ['on_history'])
# load wallet
self.load_wallet_by_name(self.electrum_config.get_wallet_path())
# URI passed in config
uri = self.electrum_config.get('url')
if uri:
self.set_URI(uri)
def get_wallet_path(self):
if self.wallet:
return self.wallet.storage.path
else:
return ''
def on_wizard_complete(self, wizard, storage):
if storage:
wallet = Wallet(storage)
wallet.start_network(self.daemon.network)
self.daemon.add_wallet(wallet)
self.load_wallet(wallet)
elif not self.wallet:
# wizard did not return a wallet; and there is no wallet open atm
# try to open last saved wallet (potentially start wizard again)
self.load_wallet_by_name(self.electrum_config.get_wallet_path(), ask_if_wizard=True)
def load_wallet_by_name(self, path, ask_if_wizard=False):
if not path:
return
if self.wallet and self.wallet.storage.path == path:
return
wallet = self.daemon.load_wallet(path, None)
if wallet:
if wallet.has_password():
self.password_dialog(wallet, _('Enter PIN code'), lambda x: self.load_wallet(wallet), self.stop)
else:
self.load_wallet(wallet)
else:
def launch_wizard():
wizard = Factory.InstallWizard(self.electrum_config, self.plugins)
wizard.path = path
wizard.bind(on_wizard_complete=self.on_wizard_complete)
storage = WalletStorage(path, manual_upgrades=True)
if not storage.file_exists():
wizard.run('new')
elif storage.is_encrypted():
raise Exception("Kivy GUI does not support encrypted wallet files.")
elif storage.requires_upgrade():
wizard.upgrade_storage(storage)
else:
raise Exception("unexpected storage file situation")
if not ask_if_wizard:
launch_wizard()
else:
from .uix.dialogs.question import Question
def handle_answer(b: bool):
if b:
launch_wizard()
else:
try: os.unlink(path)
except FileNotFoundError: pass
self.stop()
d = Question(_('Do you want to launch the wizard again?'), handle_answer)
d.open()
def on_stop(self):
Logger.info('on_stop')
if self.wallet:
self.electrum_config.save_last_wallet(self.wallet)
self.stop_wallet()
def stop_wallet(self):
if self.wallet:
self.daemon.stop_wallet(self.wallet.storage.path)
self.wallet = None
def on_key_down(self, instance, key, keycode, codepoint, modifiers):
if 'ctrl' in modifiers:
# q=24 w=25
if keycode in (24, 25):
self.stop()
elif keycode == 27:
# r=27
# force update wallet
self.update_wallet()
elif keycode == 112:
# pageup
#TODO move to next tab
pass
elif keycode == 117:
# pagedown
#TODO move to prev tab
pass
#TODO: alt+tab_number to activate the particular tab
def on_keyboard(self, instance, key, keycode, codepoint, modifiers):
if key == 27 and self.is_exit is False:
self.is_exit = True
self.show_info(_('Press again to exit'))
return True
# override settings button
if key in (319, 282): #f1/settings button on android
#self.gui.main_gui.toggle_settings(self)
return True
def settings_dialog(self):
from .uix.dialogs.settings import SettingsDialog
if self._settings_dialog is None:
self._settings_dialog = SettingsDialog(self)
self._settings_dialog.update()
self._settings_dialog.open()
def popup_dialog(self, name):
if name == 'settings':
self.settings_dialog()
elif name == 'wallets':
from .uix.dialogs.wallets import WalletDialog
d = WalletDialog()
d.open()
elif name == 'status':
popup = Builder.load_file('electrum/gui/kivy/uix/ui_screens/'+name+'.kv')
master_public_keys_layout = popup.ids.master_public_keys
for xpub in self.wallet.get_master_public_keys()[1:]:
master_public_keys_layout.add_widget(TopLabel(text=_('Master Public Key')))
ref = RefLabel()
ref.name = _('Master Public Key')
ref.data = xpub
master_public_keys_layout.add_widget(ref)
popup.open()
else:
popup = Builder.load_file('electrum/gui/kivy/uix/ui_screens/'+name+'.kv')
popup.open()
@profiler
def init_ui(self):
''' Initialize The Ux part of electrum. This function performs the basic
tasks of setting up the ui.
'''
#from weakref import ref
self.funds_error = False
# setup UX
self.screens = {}
#setup lazy imports for mainscreen
Factory.register('AnimatedPopup',
module='electrum.gui.kivy.uix.dialogs')
Factory.register('QRCodeWidget',
module='electrum.gui.kivy.uix.qrcodewidget')
# preload widgets. Remove this if you want to load the widgets on demand
#Cache.append('electrum_widgets', 'AnimatedPopup', Factory.AnimatedPopup())
#Cache.append('electrum_widgets', 'QRCodeWidget', Factory.QRCodeWidget())
# load and focus the ui
self.root.manager = self.root.ids['manager']
self.history_screen = None
self.contacts_screen = None
self.send_screen = None
self.invoices_screen = None
self.receive_screen = None
self.requests_screen = None
self.address_screen = None
self.icon = "electrum/gui/icons/electrum.png"
self.tabs = self.root.ids['tabs']
def update_interfaces(self, dt):
net_params = self.network.get_parameters()
self.num_nodes = len(self.network.get_interfaces())
self.num_chains = len(self.network.get_blockchains())
chain = self.network.blockchain()
self.blockchain_forkpoint = chain.get_max_forkpoint()
self.blockchain_name = chain.get_name()
interface = self.network.interface
if interface:
self.server_host = interface.host
else:
self.server_host = str(net_params.host) + ' (connecting...)'
self.proxy_config = net_params.proxy or {}
self.update_proxy_str(self.proxy_config)
def on_network_event(self, event, *args):
Logger.info('network event: '+ event)
if event == 'network_updated':
self._trigger_update_interfaces()
self._trigger_update_status()
elif event == 'wallet_updated':
self._trigger_update_wallet()
self._trigger_update_status()
elif event == 'blockchain_updated':
# to update number of confirmations in history
self._trigger_update_wallet()
elif event == 'status':
self._trigger_update_status()
elif event == 'new_transaction':
self._trigger_update_wallet()
elif event == 'verified':
self._trigger_update_wallet()
@profiler
def load_wallet(self, wallet):
if self.wallet:
self.stop_wallet()
self.wallet = wallet
self.wallet_name = wallet.basename()
self.update_wallet()
# Once GUI has been initialized check if we want to announce something
# since the callback has been called before the GUI was initialized
if self.receive_screen:
self.receive_screen.clear()
self.update_tabs()
run_hook('load_wallet', wallet, self)
try:
wallet.try_detecting_internal_addresses_corruption()
except InternalAddressCorruption as e:
self.show_error(str(e))
send_exception_to_crash_reporter(e)
def update_status(self, *dt):
if not self.wallet:
return
if self.network is None or not self.network.is_connected():
status = _("Offline")
elif self.network.is_connected():
self.num_blocks = self.network.get_local_height()
server_height = self.network.get_server_height()
server_lag = self.num_blocks - server_height
if not self.wallet.up_to_date or server_height == 0:
status = _("Synchronizing...")
elif server_lag > 1:
status = _("Server lagging")
else:
status = ''
else:
status = _("Disconnected")
if status:
self.balance = status
self.fiat_balance = status
else:
c, u, x = self.wallet.get_balance()
text = self.format_amount(c+x+u)
self.balance = str(text.strip()) + ' [size=22dp]%s[/size]'% self.base_unit
self.fiat_balance = self.fx.format_amount(c+u+x) + ' [size=22dp]%s[/size]'% self.fx.ccy
def get_max_amount(self):
from electrum.transaction import TxOutput
if run_hook('abort_send', self):
return ''
inputs = self.wallet.get_spendable_coins(None, self.electrum_config)
if not inputs:
return ''
addr = str(self.send_screen.screen.address) or self.wallet.dummy_address()
outputs = [TxOutput(TYPE_ADDRESS, addr, '!')]
try:
tx = self.wallet.make_unsigned_transaction(inputs, outputs, self.electrum_config)
except NoDynamicFeeEstimates as e:
Clock.schedule_once(lambda dt, bound_e=e: self.show_error(str(bound_e)))
return ''
except NotEnoughFunds:
return ''
except InternalAddressCorruption as e:
self.show_error(str(e))
send_exception_to_crash_reporter(e)
return ''
amount = tx.output_value()
__, x_fee_amount = run_hook('get_tx_extra_fee', self.wallet, tx) or (None, 0)
amount_after_all_fees = amount - x_fee_amount
return format_satoshis_plain(amount_after_all_fees, self.decimal_point())
def format_amount(self, x, is_diff=False, whitespaces=False):
return format_satoshis(x, 0, self.decimal_point(), is_diff=is_diff, whitespaces=whitespaces)
def format_amount_and_units(self, x):
return format_satoshis_plain(x, self.decimal_point()) + ' ' + self.base_unit
#@profiler
def update_wallet(self, *dt):
self._trigger_update_status()
if self.wallet and (self.wallet.up_to_date or not self.network or not self.network.is_connected()):
self.update_tabs()
def notify(self, message):
try:
global notification, os
if not notification:
from plyer import notification
icon = (os.path.dirname(os.path.realpath(__file__))
+ '/../../' + self.icon)
notification.notify('Electrum-BDRcoin', message,
app_icon=icon, app_name='Electrum-BDRcoin')
except ImportError:
Logger.Error('Notification: needs plyer; `sudo python3 -m pip install plyer`')
def on_pause(self):
self.pause_time = time.time()
# pause nfc
if self.nfcscanner:
self.nfcscanner.nfc_disable()
return True
def on_resume(self):
now = time.time()
if self.wallet and self.wallet.has_password() and now - self.pause_time > 60:
self.password_dialog(self.wallet, _('Enter PIN'), None, self.stop)
if self.nfcscanner:
self.nfcscanner.nfc_enable()
def on_size(self, instance, value):
width, height = value
self._orientation = 'landscape' if width > height else 'portrait'
self._ui_mode = 'tablet' if min(width, height) > inch(3.51) else 'phone'
def on_ref_label(self, label, touch):
if label.touched:
label.touched = False
self.qr_dialog(label.name, label.data, True)
else:
label.touched = True
self._clipboard.copy(label.data)
Clock.schedule_once(lambda dt: self.show_info(_('Text copied to clipboard.\nTap again to display it as QR code.')))
def show_error(self, error, width='200dp', pos=None, arrow_pos=None,
exit=False, icon='atlas://electrum/gui/kivy/theming/light/error', duration=0,
modal=False):
''' Show an error Message Bubble.
'''
self.show_info_bubble( text=error, icon=icon, width=width,
pos=pos or Window.center, arrow_pos=arrow_pos, exit=exit,
duration=duration, modal=modal)
def show_info(self, error, width='200dp', pos=None, arrow_pos=None,
exit=False, duration=0, modal=False):
''' Show an Info Message Bubble.
'''
self.show_error(error, icon='atlas://electrum/gui/kivy/theming/light/important',
duration=duration, modal=modal, exit=exit, pos=pos,
arrow_pos=arrow_pos)
def show_info_bubble(self, text=_('Hello World'), pos=None, duration=0,
arrow_pos='bottom_mid', width=None, icon='', modal=False, exit=False):
'''Method to show an Information Bubble
.. parameters::
text: Message to be displayed
pos: position for the bubble
duration: duration the bubble remains on screen. 0 = click to hide
width: width of the Bubble
arrow_pos: arrow position for the bubble
'''
info_bubble = self.info_bubble
if not info_bubble:
info_bubble = self.info_bubble = Factory.InfoBubble()
win = Window
if info_bubble.parent:
win.remove_widget(info_bubble
if not info_bubble.modal else
info_bubble._modal_view)
if not arrow_pos:
info_bubble.show_arrow = False
else:
info_bubble.show_arrow = True
info_bubble.arrow_pos = arrow_pos
img = info_bubble.ids.img
if text == 'texture':
# icon holds a texture not a source image
# display the texture in full screen
text = ''
img.texture = icon
info_bubble.fs = True
info_bubble.show_arrow = False
img.allow_stretch = True
info_bubble.dim_background = True
info_bubble.background_image = 'atlas://electrum/gui/kivy/theming/light/card'
else:
info_bubble.fs = False
info_bubble.icon = icon
#if img.texture and img._coreimage:
# img.reload()
img.allow_stretch = False
info_bubble.dim_background = False
info_bubble.background_image = 'atlas://data/images/defaulttheme/bubble'
info_bubble.message = text
if not pos:
pos = (win.center[0], win.center[1] - (info_bubble.height/2))
info_bubble.show(pos, duration, width, modal=modal, exit=exit)
def tx_dialog(self, tx):
from .uix.dialogs.tx_dialog import TxDialog
d = TxDialog(self, tx)
d.open()
def sign_tx(self, *args):
threading.Thread(target=self._sign_tx, args=args).start()
def _sign_tx(self, tx, password, on_success, on_failure):
try:
self.wallet.sign_transaction(tx, password)
except InvalidPassword:
Clock.schedule_once(lambda dt: on_failure(_("Invalid PIN")))
return
on_success = run_hook('tc_sign_wrapper', self.wallet, tx, on_success, on_failure) or on_success
Clock.schedule_once(lambda dt: on_success(tx))
def _broadcast_thread(self, tx, on_complete):
status = False
try:
self.network.run_from_another_thread(self.network.broadcast_transaction(tx))
except TxBroadcastError as e:
msg = e.get_message_for_gui()
except BestEffortRequestFailed as e:
msg = repr(e)
else:
status, msg = True, tx.txid()
Clock.schedule_once(lambda dt: on_complete(status, msg))
def broadcast(self, tx, pr=None):
def on_complete(ok, msg):
if ok:
self.show_info(_('Payment sent.'))
if self.send_screen:
self.send_screen.do_clear()
if pr:
self.wallet.invoices.set_paid(pr, tx.txid())
self.wallet.invoices.save()
self.update_tab('invoices')
else:
msg = msg or ''
self.show_error(msg)
if self.network and self.network.is_connected():
self.show_info(_('Sending'))
threading.Thread(target=self._broadcast_thread, args=(tx, on_complete)).start()
else:
self.show_info(_('Cannot broadcast transaction') + ':\n' + _('Not connected'))
def description_dialog(self, screen):
from .uix.dialogs.label_dialog import LabelDialog
text = screen.message
def callback(text):
screen.message = text
d = LabelDialog(_('Enter description'), text, callback)
d.open()
def amount_dialog(self, screen, show_max):
from .uix.dialogs.amount_dialog import AmountDialog
amount = screen.amount
if amount:
amount, u = str(amount).split()
assert u == self.base_unit
def cb(amount):
screen.amount = amount
popup = AmountDialog(show_max, amount, cb)
popup.open()
def invoices_dialog(self, screen):
from .uix.dialogs.invoices import InvoicesDialog
if len(self.wallet.invoices.sorted_list()) == 0:
self.show_info(' '.join([
_('No saved invoices.'),
_('Signed invoices are saved automatically when you scan them.'),
_('You may also save unsigned requests or contact addresses using the save button.')
]))
return
popup = InvoicesDialog(self, screen, None)
popup.update()
popup.open()
def requests_dialog(self, screen):
from .uix.dialogs.requests import RequestsDialog
if len(self.wallet.get_sorted_requests(self.electrum_config)) == 0:
self.show_info(_('No saved requests.'))
return
popup = RequestsDialog(self, screen, None)
popup.update()
popup.open()
def addresses_dialog(self, screen):
from .uix.dialogs.addresses import AddressesDialog
popup = AddressesDialog(self, screen, None)
popup.update()
popup.open()
def fee_dialog(self, label, dt):
from .uix.dialogs.fee_dialog import FeeDialog
def cb():
self.fee_status = self.electrum_config.get_fee_status()
fee_dialog = FeeDialog(self, self.electrum_config, cb)
fee_dialog.open()
def on_fee(self, event, *arg):
self.fee_status = self.electrum_config.get_fee_status()
def protected(self, msg, f, args):
if self.wallet.has_password():
on_success = lambda pw: f(*(args + (pw,)))
self.password_dialog(self.wallet, msg, on_success, lambda: None)
else:
f(*(args + (None,)))
def delete_wallet(self):
from .uix.dialogs.question import Question
basename = os.path.basename(self.wallet.storage.path)
d = Question(_('Delete wallet?') + '\n' + basename, self._delete_wallet)
d.open()
def _delete_wallet(self, b):
if b:
basename = self.wallet.basename()
self.protected(_("Enter your PIN code to confirm deletion of {}").format(basename), self.__delete_wallet, ())
def __delete_wallet(self, pw):
wallet_path = self.get_wallet_path()
dirname = os.path.dirname(wallet_path)
basename = os.path.basename(wallet_path)
if self.wallet.has_password():
try:
self.wallet.check_password(pw)
except:
self.show_error("Invalid PIN")
return
self.stop_wallet()
os.unlink(wallet_path)
self.show_error(_("Wallet removed: {}").format(basename))
new_path = self.electrum_config.get_wallet_path()
self.load_wallet_by_name(new_path)
def show_seed(self, label):
self.protected(_("Enter your PIN code in order to decrypt your seed"), self._show_seed, (label,))
def _show_seed(self, label, password):
if self.wallet.has_password() and password is None:
return
keystore = self.wallet.keystore
try:
seed = keystore.get_seed(password)
passphrase = keystore.get_passphrase(password)
except:
self.show_error("Invalid PIN")
return
label.text = _('Seed') + ':\n' + seed
if passphrase:
label.text += '\n\n' + _('Passphrase') + ': ' + passphrase
def password_dialog(self, wallet, msg, on_success, on_failure):
from .uix.dialogs.password_dialog import PasswordDialog
if self._password_dialog is None:
self._password_dialog = PasswordDialog()
self._password_dialog.init(self, wallet, msg, on_success, on_failure)
self._password_dialog.open()
def change_password(self, cb):
from .uix.dialogs.password_dialog import PasswordDialog
if self._password_dialog is None:
self._password_dialog = PasswordDialog()
message = _("Changing PIN code.") + '\n' + _("Enter your current PIN:")
def on_success(old_password, new_password):
self.wallet.update_password(old_password, new_password)
self.show_info(_("Your PIN code was updated"))
on_failure = lambda: self.show_error(_("PIN codes do not match"))
self._password_dialog.init(self, self.wallet, message, on_success, on_failure, is_change=1)
self._password_dialog.open()
def export_private_keys(self, pk_label, addr):
if self.wallet.is_watching_only():
self.show_info(_('This is a watching-only wallet. It does not contain private keys.'))
return
def show_private_key(addr, pk_label, password):
if self.wallet.has_password() and password is None:
return
if not self.wallet.can_export():
return
try:
key = str(self.wallet.export_private_key(addr, password)[0])
pk_label.data = key
except InvalidPassword:
self.show_error("Invalid PIN")
return
self.protected(_("Enter your PIN code in order to decrypt your private key"), show_private_key, (addr, pk_label))
|
a2c.py | import os
import torch
import elf
import numpy as np
import wandb
from elf.segmentation.features import compute_rag
from torch.nn import functional as F
from torch.optim.lr_scheduler import ReduceLROnPlateau
from torch.utils.data import DataLoader
from collections import namedtuple
import matplotlib.pyplot as plt
from matplotlib import cm
from multiprocessing import Process, Lock
import threading
import shutil
from skimage.morphology import dilation
from environments.multicut import MulticutEmbeddingsEnv, State
from data.spg_dset import SpgDset
from models.agent_model import Agent
from models.feature_extractor import FeExtractor
from utils.exploration_functions import RunningAverage
from utils.general import soft_update_params, set_seed_everywhere, get_colored_edges_in_sseg, pca_project, random_label_cmap
from utils.replay_memory import TransitionData_ts
from utils.graphs import get_joint_sg_logprobs_edges
from utils.distances import CosineDistance, L2Distance
from utils.matching import matching
from utils.yaml_conv_parser import dict_to_attrdict
from utils.training_helpers import update_env_data, supervised_policy_pretraining, state_to_cpu, Forwarder
from utils.metrics import AveragePrecision, ClusterMetrics
# from timeit import default_timer as timer
class AgentA2CTrainer(object):
def __init__(self, cfg, global_count):
super(AgentA2CTrainer, self).__init__()
assert torch.cuda.device_count() == 1
self.device = torch.device("cuda:0")
torch.cuda.set_device(self.device)
torch.set_default_tensor_type(torch.FloatTensor)
self.cfg = cfg
self.global_count = global_count
self.memory = TransitionData_ts(capacity=self.cfg.mem_size)
self.best_val_reward = -np.inf
if self.cfg.distance == 'cosine':
self.distance = CosineDistance()
else:
self.distance = L2Distance()
self.model = Agent(self.cfg, State, self.distance, self.device, with_temp=False)
wandb.watch(self.model)
self.model.cuda(self.device)
self.model_mtx = Lock()
MovSumLosses = namedtuple('mov_avg_losses', ('actor', 'critic'))
Scalers = namedtuple('Scalers', ('critic', 'actor'))
OptimizerContainer = namedtuple('OptimizerContainer',
('actor', 'critic', 'actor_shed', 'critic_shed'))
actor_optimizer = torch.optim.Adam(self.model.actor.parameters(), lr=self.cfg.actor_lr)
critic_optimizer = torch.optim.Adam(self.model.critic.parameters(), lr=self.cfg.critic_lr)
lr_sched_cfg = dict_to_attrdict(self.cfg.lr_sched)
bw = lr_sched_cfg.mov_avg_bandwidth
off = lr_sched_cfg.mov_avg_offset
weights = np.linspace(lr_sched_cfg.weight_range[0], lr_sched_cfg.weight_range[1], bw)
weights = weights / weights.sum() # make them sum up to one
shed = lr_sched_cfg.torch_sched
self.mov_sum_losses = MovSumLosses(RunningAverage(weights, band_width=bw, offset=off),
RunningAverage(weights, band_width=bw, offset=off))
self.optimizers = OptimizerContainer(actor_optimizer, critic_optimizer,
*[ReduceLROnPlateau(opt, patience=shed.patience,
threshold=shed.threshold, min_lr=shed.min_lr,
factor=shed.factor) for opt in
(actor_optimizer, critic_optimizer)])
self.scalers = Scalers(torch.cuda.amp.GradScaler(), torch.cuda.amp.GradScaler())
self.forwarder = Forwarder()
if self.cfg.agent_model_name != "":
self.model.load_state_dict(torch.load(self.cfg.agent_model_name))
# finished with prepping
self.train_dset = SpgDset(self.cfg.data_dir, dict_to_attrdict(self.cfg.patch_manager), dict_to_attrdict(self.cfg.data_keys), max(self.cfg.s_subgraph))
self.val_dset = SpgDset(self.cfg.val_data_dir, dict_to_attrdict(self.cfg.patch_manager), dict_to_attrdict(self.cfg.data_keys), max(self.cfg.s_subgraph))
self.segm_metric = AveragePrecision()
self.clst_metric = ClusterMetrics()
self.global_counter = 0
def validate(self):
"""validates the prediction against the method of clustering the embedding space"""
env = MulticutEmbeddingsEnv(self.cfg, self.device)
if self.cfg.verbose:
print("\n\n###### start validate ######", end='')
self.model.eval()
n_examples = len(self.val_dset)
#taus = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
#rl_scores, keys = [], None
self.clst_metric.reset()
map_scores = []
ex_raws, ex_sps, ex_gts, ex_mc_gts, ex_embeds, ex_rl, edge_ids, rewards, actions = [], [], [], [], [], [], [], [], []
dloader = iter(DataLoader(self.val_dset, batch_size=1, shuffle=False, pin_memory=True, num_workers=0))
acc_reward = 0
for it in range(n_examples):
update_env_data(env, dloader, self.val_dset, self.device, with_gt_edges="sub_graph_dice" in self.cfg.reward_function)
env.reset()
state = env.get_state()
self.model_mtx.acquire()
try:
distr, _, _, _, _, embeddings = self.forwarder.forward(self.model, state, State, self.device, grad=False,
post_data=False, get_embeddings=True)
finally:
self.model_mtx.release()
action = torch.sigmoid(distr.loc)
reward = env.execute_action(action, tau=0.0, train=False)
rew = reward[-1].item() if self.cfg.reward_function == "sub_graph_dice" else reward[-2].item()
acc_reward += rew
if self.cfg.verbose:
print(f"\nstep: {it}; mean_loc: {round(distr.loc.mean().item(), 5)}; mean reward: {round(rew, 5)}", end='')
embeddings = embeddings[0].cpu().numpy()
gt_seg = env.gt_seg[0].cpu().numpy()
gt_mc = cm.prism(env.gt_soln[0].cpu()/env.gt_soln[0].max().item()) if env.gt_edge_weights is not None else torch.zeros(env.raw.shape[-2:])
rl_labels = env.current_soln.cpu().numpy()[0]
ex_embeds.append(pca_project(embeddings, n_comps=3))
ex_raws.append(env.raw[0].cpu().permute(1, 2, 0).squeeze())
ex_sps.append(env.init_sp_seg[0].cpu())
ex_mc_gts.append(gt_mc)
ex_gts.append(gt_seg)
ex_rl.append(rl_labels)
edge_ids.append(env.edge_ids)
rewards.append(reward[-1])
actions.append(action)
map_scores.append(self.segm_metric(rl_labels, gt_seg))
self.clst_metric(rl_labels, gt_seg)
'''
_rl_scores = matching(gt_seg, rl_labels, thresh=taus, criterion='iou', report_matches=False)
if it == 0:
for tau_it in range(len(_rl_scores)):
rl_scores.append(np.array(list(map(float, list(_rl_scores[tau_it]._asdict().values())[1:]))))
keys = list(_rl_scores[0]._asdict().keys())[1:]
else:
for tau_it in range(len(_rl_scores)):
rl_scores[tau_it] += np.array(list(map(float, list(_rl_scores[tau_it]._asdict().values())[1:]))
'''
'''
div = np.ones_like(rl_scores[0])
for i, key in enumerate(keys):
if key not in ('fp', 'tp', 'fn'):
div[i] = 10
for tau_it in range(len(rl_scores)):
rl_scores[tau_it] = dict(zip(keys, rl_scores[tau_it] / div))
fig, axs = plt.subplots(1, 2, figsize=(10, 10))
plt.subplots_adjust(hspace=.5)
for m in ('precision', 'recall', 'accuracy', 'f1'):
y = [s[m] for s in rl_scores]
data = [[x, y] for (x, y) in zip(taus, y)]
table = wandb.Table(data=data, columns=["IoU_threshold", m])
wandb.log({"validation/" + m: wandb.plot.line(table, "IoU_threshold", m, stroke=None, title=m)})
axs[0].plot(taus, [s[m] for s in rl_scores], '.-', lw=2, label=m)
axs[0].set_ylabel('Metric value')
axs[0].grid()
axs[0].legend(bbox_to_anchor=(.8, 1.65), loc='upper left', fontsize='xx-small')
axs[0].set_title('RL method')
axs[0].set_xlabel(r'IoU threshold $\tau$')
for m in ('fp', 'tp', 'fn'):
y = [s[m] for s in rl_scores]
data = [[x, y] for (x, y) in zip(taus, y)]
table = wandb.Table(data=data, columns=["IoU_threshold", m])
wandb.log({"validation/" + m: wandb.plot.line(table, "IoU_threshold", m, stroke=None, title=m)})
axs[1].plot(taus, [s[m] for s in rl_scores], '.-', lw=2, label=m)
axs[1].set_ylabel('Number #')
axs[1].grid()
axs[1].legend(bbox_to_anchor=(.87, 1.6), loc='upper left', fontsize='xx-small');
axs[1].set_title('RL method')
axs[1].set_xlabel(r'IoU threshold $\tau$')
#wandb.log({"validation/metrics": [wandb.Image(fig, caption="metrics")]})
plt.close('all')
'''
splits, merges, are, arp, arr = self.clst_metric.dump()
wandb.log({"validation/acc_reward": acc_reward})
wandb.log({"validation/mAP": np.mean(map_scores)}, step=self.global_counter)
wandb.log({"validation/UnderSegmVI": splits}, step=self.global_counter)
wandb.log({"validation/OverSegmVI": merges}, step=self.global_counter)
wandb.log({"validation/ARE": are}, step=self.global_counter)
wandb.log({"validation/ARP": arp}, step=self.global_counter)
wandb.log({"validation/ARR": arr}, step=self.global_counter)
# do the lr sheduling
self.optimizers.critic_shed.step(acc_reward)
self.optimizers.actor_shed.step(acc_reward)
if acc_reward > self.best_val_reward:
self.best_val_reward = acc_reward
wandb.run.summary["validation_reward"] = acc_reward
torch.save(self.model.state_dict(), os.path.join(wandb.run.dir, "best_checkpoint_agent.pth"))
if self.cfg.verbose:
print("\n###### finish validate ######\n", end='')
label_cm = random_label_cmap(zeroth=1.0)
label_cm.set_bad(alpha=0)
for i in self.cfg.store_indices:
fig, axs = plt.subplots(2, 3 if self.cfg.reward_function == "sub_graph_dice" else 4 , sharex='col',
figsize=(9, 5), sharey='row', gridspec_kw={'hspace': 0, 'wspace': 0})
axs[0, 0].imshow(ex_gts[i], cmap=random_label_cmap(), interpolation="none")
axs[0, 0].set_title('gt', y=1.05, size=10)
axs[0, 0].axis('off')
if ex_raws[i].ndim == 3:
if ex_raws[i].shape[-1] > 2:
axs[0, 1].imshow(ex_raws[i][..., :3], cmap="gray")
else:
axs[0, 1].imshow(ex_raws[i][..., 0], cmap="gray")
else:
axs[1, 1].imshow(ex_raws[i], cmap="gray")
axs[0, 1].set_title('raw image', y=1.05, size=10)
axs[0, 1].axis('off')
axs[0, 2].imshow(ex_sps[i], cmap=random_label_cmap(), interpolation="none")
axs[0, 2].set_title('superpixels', y=1.05, size=10)
axs[0, 2].axis('off')
axs[1, 0].imshow(ex_embeds[i])
axs[1, 0].set_title('pc proj 1-3', y=-0.15, size=10)
axs[1, 0].axis('off')
if ex_raws[i].ndim == 3:
if ex_raws[i].shape[-1] > 1:
axs[1, 1].imshow(ex_raws[i][..., -1], cmap="gray")
else:
axs[1, 1].imshow(ex_raws[i][..., 0], cmap="gray")
else:
axs[1, 1].imshow(ex_raws[i], cmap="gray")
axs[1, 1].set_title('sp edge', y=-0.15, size=10)
axs[1, 1].axis('off')
axs[1, 2].imshow(ex_rl[i], cmap=random_label_cmap(), interpolation="none")
axs[1, 2].set_title('prediction', y=-0.15, size=10)
axs[1, 2].axis('off')
if self.cfg.reward_function != "sub_graph_dice":
frame_rew, scores_rew, bnd_mask = get_colored_edges_in_sseg(ex_sps[i][None].float(), edge_ids[i].cpu(), rewards[i].cpu())
frame_act, scores_act, _ = get_colored_edges_in_sseg(ex_sps[i][None].float(), edge_ids[i].cpu(), 1 - actions[i].cpu().squeeze())
bnd_mask = torch.from_numpy(dilation(bnd_mask.cpu().numpy()))
frame_rew = np.stack([dilation(frame_rew.cpu().numpy()[..., i]) for i in range(3)], -1)
frame_act = np.stack([dilation(frame_act.cpu().numpy()[..., i]) for i in range(3)], -1)
ex_rl[i] = ex_rl[i].squeeze().astype(np.float)
ex_rl[i][bnd_mask] = np.nan
axs[1, 3].imshow(frame_rew, interpolation="none")
axs[1, 3].imshow(ex_rl[i], cmap=label_cm, alpha=0.8, interpolation="none")
axs[1, 3].set_title("rewards 1:g, 0:r", y=-0.2)
axs[1, 3].axis('off')
axs[0, 3].imshow(frame_act, interpolation="none")
axs[0, 3].imshow(ex_rl[i], cmap=label_cm, alpha=0.8, interpolation="none")
axs[0, 3].set_title("actions 0:g, 1:r", y=1.05, size=10)
axs[0, 3].axis('off')
wandb.log({"validation/sample_" + str(i): [wandb.Image(fig, caption="sample images")]},
step=self.global_counter)
plt.close('all')
def update_critic(self, obs, action, reward):
self.optimizers.critic.zero_grad()
with torch.cuda.amp.autocast(enabled=True):
current_Q, side_loss = self.forwarder.forward(self.model, obs, State, self.device, actions=action, grad=True)
critic_loss = torch.tensor([0.0], device=current_Q[0].device)
mean_reward = 0
for i, sz in enumerate(self.cfg.s_subgraph):
target_Q = reward[i]
target_Q = target_Q.detach()
critic_loss = critic_loss + F.mse_loss(current_Q[i], target_Q)
mean_reward += reward[i].mean()
critic_loss = critic_loss / len(self.cfg.s_subgraph) + self.cfg.side_loss_weight * side_loss
self.scalers.critic.scale(critic_loss).backward()
self.scalers.critic.step(self.optimizers.critic)
self.scalers.critic.update()
return critic_loss.item(), mean_reward / len(self.cfg.s_subgraph)
def update_actor(self, obs, reward, expl_action):
self.optimizers.actor.zero_grad()
with torch.cuda.amp.autocast(enabled=True):
expl_action = None
distribution, actor_Q, action, side_loss = self.forwarder.forward(self.model, obs, State, self.device,
expl_action=expl_action, policy_opt=True,
grad=True)
log_prob = distribution.log_prob(action)
actor_loss = torch.tensor([0.0], device=actor_Q[0].device)
entropy_loss = torch.tensor([0.0], device=actor_Q[0].device)
_log_prob, sg_entropy = [], []
for i, sz in enumerate(self.cfg.s_subgraph):
ret = get_joint_sg_logprobs_edges(log_prob, distribution.scale, obs, i, sz)
_log_prob.append(ret[0])
sg_entropy.append(ret[1])
actor_loss = actor_loss + (-(_log_prob[i] * actor_Q[i]).mean())
# actor_loss = actor_loss - actor_Q[i].mean()
actor_loss = actor_loss / len(self.cfg.s_subgraph) + self.cfg.side_loss_weight * side_loss
min_entropy = (self.cfg.entropy_range[1] - self.cfg.entropy_range[0]) * (1 - reward[-1]) + self.cfg.entropy_range[0]
for i, sz in enumerate(self.cfg.s_subgraph):
min_entropy = min_entropy.to(_log_prob[i].device).squeeze()
entropy = sg_entropy[i] if self.cfg.use_closed_form_entropy else -_log_prob[i]
entropy_loss = entropy_loss + ((entropy - (self.cfg.s_subgraph[i] * min_entropy))**2).mean()
entropy_loss = entropy_loss / len(self.cfg.s_subgraph)
actor_loss = actor_loss + 0.001 * entropy_loss
self.scalers.actor.scale(actor_loss).backward()
self.scalers.actor.step(self.optimizers.actor)
self.scalers.actor.update()
return actor_loss.item(), min_entropy, distribution.loc.mean().item()
def _step(self, step):
actor_loss, min_entropy, loc_mean = None, None, None
(obs, action, reward), sample_idx = self.memory.sample()
critic_loss, mean_reward = self.update_critic(obs, action, reward)
self.memory.report_sample_loss(critic_loss + mean_reward, sample_idx)
self.mov_sum_losses.critic.apply(critic_loss)
wandb.log({"loss/critic": critic_loss}, step=self.global_counter)
if self.cfg.actor_update_after < step and step % self.cfg.actor_update_frequency == 0:
actor_loss, min_entropy, loc_mean = self.update_actor(obs, reward, action)
self.mov_sum_losses.actor.apply(actor_loss)
wandb.log({"loss/actor": actor_loss}, step=self.global_counter)
if step % self.cfg.post_stats_frequency == 0:
if min_entropy != "nl":
wandb.log({"min_entropy": min_entropy}, step=self.global_counter)
wandb.log({"mov_avg/critic": self.mov_sum_losses.critic.avg}, step=self.global_counter)
wandb.log({"mov_avg/actor": self.mov_sum_losses.actor.avg}, step=self.global_counter)
wandb.log({"lr/critic": self.optimizers.critic_shed.optimizer.param_groups[0]['lr']}, step=self.global_counter)
wandb.log({"lr/actor": self.optimizers.actor_shed.optimizer.param_groups[0]['lr']}, step=self.global_counter)
self.global_counter = self.global_counter + 1
if step % self.cfg.critic_target_update_frequency == 0:
soft_update_params(self.model.critic, self.model.critic_tgt, self.cfg.critic_tau)
return critic_loss, actor_loss, loc_mean
def train_until_finished(self):
while self.global_count.value() <= self.cfg.T_max + self.cfg.mem_size:
self.model_mtx.acquire()
try:
stats = [[], [], []]
for i in range(self.cfg.n_updates_per_step):
_stats = self._step(self.global_count.value())
[s.append(_s) for s, _s in zip(stats, _stats)]
for j in range(len(stats)):
if any([_s is None for _s in stats[j]]):
stats[j] = "nl"
else:
stats[j] = round(sum(stats[j])/self.cfg.n_updates_per_step, 5)
if self.cfg.verbose:
print(f"step: {self.global_count.value()}; mean_loc: {stats[-1]}; n_explorer_steps {self.memory.push_count}", end="")
print(f"; cl: {stats[0]}; acl: {stats[1]}")
finally:
self.model_mtx.release()
self.global_count.increment()
self.memory.reset_push_count()
if self.global_count.value() % self.cfg.validatoin_freq == 0:
self.validate()
# Acts and trains model
def train_and_explore(self, rn):
self.global_count.reset()
set_seed_everywhere(rn)
wandb.config.random_seed = rn
if self.cfg.verbose:
print('###### start training ######')
print('Running on device: ', self.device)
print('found ', self.train_dset.length, " training data patches")
print('found ', self.val_dset.length, "validation data patches")
print('training with seed: ' + str(rn))
explorers = []
for i in range(self.cfg.n_explorers):
explorers.append(threading.Thread(target=self.explore))
[explorer.start() for explorer in explorers]
self.memory.is_full_event.wait()
trainer = threading.Thread(target=self.train_until_finished)
trainer.start()
trainer.join()
self.global_count.set(self.cfg.T_max + self.cfg.mem_size + 4)
[explorer.join() for explorer in explorers]
self.memory.clear()
del self.memory
# torch.save(self.model.state_dict(), os.path.join(wandb.run.dir, "last_checkpoint_agent.pth"))
if self.cfg.verbose:
print('\n\n###### training finished ######')
return
def explore(self):
env = MulticutEmbeddingsEnv(self.cfg, self.device)
tau = 1
while self.global_count.value() <= self.cfg.T_max + self.cfg.mem_size:
dloader = iter(DataLoader(self.train_dset, batch_size=self.cfg.batch_size, shuffle=True, pin_memory=True, num_workers=0))
for iteration in range((len(self.train_dset) // self.cfg.batch_size) * self.cfg.data_update_frequency):
if iteration % self.cfg.data_update_frequency == 0:
update_env_data(env, dloader, self.train_dset, self.device, with_gt_edges="sub_graph_dice" in self.cfg.reward_function)
env.reset()
state = env.get_state()
if not self.memory.is_full():
action = torch.rand((env.edge_ids.shape[-1], 1), device=self.device)
else:
self.model_mtx.acquire()
try:
distr, _, action, _, _ = self.forwarder.forward(self.model, state, State, self.device, grad=False)
finally:
self.model_mtx.release()
reward = env.execute_action(action, tau=max(0, tau))
self.memory.push(state_to_cpu(state, State), action, reward)
if self.global_count.value() > self.cfg.T_max + self.cfg.mem_size:
break
return
|
krisself.py | # -*- coding: utf-8 -*-
import KRIS
from KRIS.lib.curve.ttypes import *
from datetime import datetime
import time, random, sys, ast, re, os, io, json, subprocess, threading, string, codecs, requests, ctypes, urllib, urllib2, urllib3, wikipedia, tempfile
from bs4 import BeautifulSoup
from urllib import urlopen
import requests
from io import StringIO
from threading import Thread
#from gtts import gTTS
from googletrans import Translator
#JANGAN LUPA => sudo pip install bs4 => sudo pip install BeautifulSoup => sudo pip install urllib
kr = KRIS.LINE()
#kr.login(qr=True)
kr.login(token='')#r
kr.loginResult()
print "โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ\nโ โโฃ[KRIS BERHASIL LOGIN]\nโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ"
reload(sys)
sys.setdefaultencoding('utf-8')
helpmsg ="""
โโโโโโโโโโโโโโ
โ โฐ tษวส ฤสษฎษส-วสสส ษฎึ
t โฐ
โ โโโโโโโโโโโโโ
โ Owner : Kris
โ line://ti/p/~krissthea
โ โโโโโโโโโโโโโ
โโโโโโโโโโโโโโ
โโ โโฃgoogle (text)
โโ โโฃplaystore (text)
โโ โโฃinstagram (username)
โโ โโฃwikipedia (text)
โโ โโฃidline (text)
โโ โโฃtime
โโ โโฃimage (text)
โโ โโฃruntime
โโ โโฃRestart
โโ โโฃlirik (text)
โโ โโฃnah (mention)
โโ โโฃcctv on/off (Lurk)
โโ โโฃtoong (Lurker)
โโ โโฃprotect on/off
โโ โโฃqr on/off
โโ โโฃinvite on/off
โโ โโฃCancel on/off
โโ โโฃSimisimi:on/off
โโ โโฃRead on/off
โโ โโฃGetinfo @
โโ โโฃGetcontact @
โโ โโฃCium @
โโ โโฃspeed
โโ โโฃFriendlist
โโ โโฃid@en
โโ โโฃen@id
โโ โโฃid@jp
โโ โโฃkeybot
โโโโโโโโโโโโโโ
โโโโโโโโโโโโโโ"""
keymsg ="""
โโโโโโโโโโโโโโ
โ โฐ tษวส ฤสษฎษส-วสสส ษฎึ
t โฐ
โ โโโโโโโโโโโโโ
โ Owner : Kris
โ line://ti/p/~krissthea
โ โโโโโโโโโโโโโ
โโโโโโโโโโโโโโ
โโ โโฃkeypro
โโ โโฃkeyself
โโ โโฃkeygrup
โโ โโฃkeyset
โโ โโฃkeytran
โโ โโฃmode on/off
โโโโโโโโโโโโโโ
โโโโโโโโโโโโโโ"""
helppro ="""
โโโโโโโโโโโโโโ
โ โฐ tษวส ฤสษฎษส-วสสส ษฎึ
t โฐ
โ โโโโโโโโโโโโโ
โ Owner : Kris
โ line://ti/p/~krissthea
โ โโโโโโโโโโโโโ
โโโโโโโโโโโโโโ
โโ โโฃmode on/off
โโ โโฃprotect on/off
โโ โโฃqr on/off
โโ โโฃinvite on/off
โโ โโฃcancel on/off
โโโโโโโโโโโโโโ
โโโโโโโโโโโโโโ"""
helpself ="""
โโโโโโโโโโโโโโ
โ โฐ tษวส ฤสษฎษส-วสสส ษฎึ
t โฐ
โ โโโโโโโโโโโโโ
โ Owner : Kris
โ line://ti/p/~krissthea
โ โโโโโโโโโโโโโ
โโโโโโโโโโโโโโ
โโ โโฃMe
โโ โโฃMyname:
โโ โโฃMybio:
โโ โโฃMypict
โโ โโฃMycover
โโ โโฃMy copy @
โโ โโฃMy backup
โโ โโฃGetgroup image
โโ โโฃGetmid @
โโ โโฃGetprofile @
โโ โโฃGetinfo @
โโ โโฃGetname @
โโ โโฃGetbio @
โโ โโฃGetpict @
โโ โโฃGetcover @
โโ โโฃnah (Mention)
โโ โโฃcctv on/off (Lurking)
โโ โโฃintip/toong (Lurkers)
โโ โโฃMicadd @
โโ โโฃMicdel @
โโ โโฃMimic on/off
โโ โโฃMiclist
โโโโโโโโโโโโโโ
โโโโโโโโโโโโโโ"""
helpset ="""
โโโโโโโโโโโโโโ
โ โฐ tษวส ฤสษฎษส-วสสส ษฎึ
t โฐ
โ โโโโโโโโโโโโโ
โ Owner : Kris
โ line://ti/p/~krissthea
โ โโโโโโโโโโโโโ
โโโโโโโโโโโโโโ
โโ โโฃcontact on/off
โโ โโฃautojoin on/off
โโ โโฃauto leave on/off
โโ โโฃautoadd on/off
โโ โโฃlike friend
โโ โโฃlink on
โโ โโฃrespon on/off
โโ โโฃread on/off
โโ โโฃsimisimi on/off
โโ โโฃSambut on/off
โโ โโฃPergi on/off
โโ โโฃRespontag on/off
โโ โโฃKicktag on/off
โโโโโโโโโโโโโโ
โโโโโโโโโโโโโโ"""
helpgrup ="""
โโโโโโโโโโโโโโ
โ โฐ tษวส ฤสษฎษส-วสสส ษฎึ
t โฐ
โ โโโโโโโโโโโโโ
โ Owner : Kris
โ line://ti/p/~krissthea
โ โโโโโโโโโโโโโ
โโโโโโโโโโโโโโ
โโ โโฃLink on
โโ โโฃUrl
โโ โโฃCancel
โโ โโฃGcreator
โโ โโฃKick @
โโ โโฃCium @
โโ โโฃGname:
โโ โโฃGbroadcast:
โโ โโฃCbroadcast:
โโ โโฃInfogrup
โโ โโฃGruplist
โโ โโฃFriendlist
โโ โโฃBlacklist
โโ โโฃBan @
โโ โโฃUnban @
โโ โโฃClearban
โโ โโฃBanlist
โโ โโฃContact ban
โโ โโฃMidban
โโโโโโโโโโโโโโ
โโโโโโโโโโโโโโ"""
helptranslate ="""
โโโโโโโโโโโโโโ
โ โฐ tษวส ฤสษฎษส-วสสส ษฎึ
t โฐ
โ โโโโโโโโโโโโโ
โ Owner : Kris
โ line://ti/p/~krissthea
โ โโโโโโโโโโโโโ
โโโโโโโโโโโโโโ
โโ โโฃId@en
โโ โโฃEn@id
โโ โโฃId@jp
โโ โโฃJp@id
โโ โโฃId@th
โโ โโฃTh@id
โโ โโฃId@ar
โโ โโฃAr@id
โโ โโฃId@ko
โโ โโฃKo@id
โโ โโฃSay-id
โโ โโฃSay-en
โโ โโฃSay-jp
โโโโโโโโโโโโโโ
โโโโโโโโโโโโโโ"""
KAC=[kr]
mid = kr.getProfile().mid
Bots=[mid]
admin=["u31ef22df7f538df1d74dc7f756ef1a32","u9cc2323f5b84f9df880c33aa9f9e3ae1",mid]
wait = {
"likeOn":False,
"alwayRead":False,
"detectMention":True,
"kickMention":False,
"steal":True,
'pap':{},
'invite':{},
"spam":{},
'contact':False,
'autoJoin':True,
'autoCancel':{"on":False,"members":5},
'leaveRoom':True,
'timeline':False,
'autoAdd':True,
'message':"""Thx for add""",
"lang":"JP",
"comment":"๐ฤ
ยตลฃเนโษจะโฌ By C-A_Bot๐\n\nโยบยฐหหโฐ tษวส ฤสษฎษส-วสสส ษฎึ
t โฐยบยฐหหโ๏ผ๏ผพฯ๏ผพ๏ผ\nฤ
ยตลฃเนโษจะโฌ by Kris โญ๐ ยปยปยป http://line.me/ti/p/~krissthea ยซยซยซ",
"commentOn":False,
"commentBlack":{},
"wblack":False,
"dblack":False,
"clock":False,
"cNames":"",
"cNames":"",
"Wc":False,
"Lv":False,
'MENTION':True,
"blacklist":{},
"wblacklist":False,
"dblacklist":False,
"protect":False,
"cancelprotect":False,
"inviteprotect":False,
"linkprotect":False,
}
wait2 = {
"readPoint":{},
"readMember":{},
"setTime":{},
"ROM":{}
}
mimic = {
"copy":False,
"copy2":False,
"status":False,
"target":{}
}
settings = {
"simiSimi":{}
}
res = {
'num':{},
'us':{},
'au':{},
}
setTime = {}
setTime = wait2['setTime']
mulai = time.time()
contact = kr.getProfile()
backup = kr.getProfile()
backup.displayName = contact.displayName
backup.statusMessage = contact.statusMessage
backup.pictureStatus = contact.pictureStatus
def restart_program():
python = sys.executable
os.execl(python, python, * sys.argv)
def download_page(url):
version = (3,0)
cur_version = sys.version_info
if cur_version >= version: #If the Current Version of Python is 3.0 or above
import urllib,request #urllib library for Extracting web pages
try:
headers = {}
headers['User-Agent'] = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"
req = urllib,request.Request(url, headers = headers)
resp = urllib,request.urlopen(req)
respData = str(resp.read())
return respData
except Exception as e:
print(str(e))
else: #If the Current Version of Python is 2.x
import urllib2
try:
headers = {}
headers['User-Agent'] = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17"
req = urllib2.Request(url, headers = headers)
response = urllib2.urlopen(req)
page = response.read()
return page
except:
return"Page Not found"
#Finding 'Next Image' from the given raw page
def _images_get_next_item(s):
start_line = s.find('rg_di')
if start_line == -1: #If no links are found then give an error!
end_quote = 0
link = "no_links"
return link, end_quote
else:
start_line = s.find('"class="rg_meta"')
start_content = s.find('"ou"',start_line+90)
end_content = s.find(',"ow"',start_content-90)
content_raw = str(s[start_content+6:end_content-1])
return content_raw, end_content
def sendAudioWithURL(self, to_, url):
path = '%s/pythonLine-%i.data' % (tempfile.gettempdir(), randint(0, 9))
r = requests.get(url, stream=True)
if r.status_code == 200:
with open(path, 'w') as f:
shutil.copyfileobj(r.raw, f)
else:
raise Exception('Download audio failure.')
try:
self.sendAudio(to_, path)
except Exception as e:
raise e
#Getting all links with the help of '_images_get_next_image'
def _images_get_all_items(page):
items = []
while True:
item, end_content = _images_get_next_item(page)
if item == "no_links":
break
else:
items.append(item) #Append all the links in the list named 'Links'
time.sleep(0.1) #Timer could be used to slow down the request for image downloads
page = page[end_content:]
return items
def download_page(url):
version = (3,0)
cur_version = sys.version_info
if cur_version >= version: #If the Current Version of Python is 3.0 or above
import urllib,request #urllib library for Extracting web pages
try:
headers = {}
headers['User-Agent'] = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"
req = urllib,request.Request(url, headers = headers)
resp = urllib,request.urlopen(req)
respData = str(resp.read())
return respData
except Exception as e:
print(str(e))
else: #If the Current Version of Python is 2.x
import urllib2
try:
headers = {}
headers['User-Agent'] = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17"
req = urllib2.Request(url, headers = headers)
response = urllib2.urlopen(req)
page = response.read()
return page
except:
return"Page Not found"
def upload_tempimage(client):
'''
Upload a picture of a kitten. We don't ship one, so get creative!
'''
config = {
'album': album,
'name': 'bot auto upload',
'title': 'bot auto upload',
'description': 'bot auto upload'
}
print("Uploading image... ")
image = client.upload_from_path(image_path, config=config, anon=False)
print("Done")
print()
def summon(to, nama):
aa = ""
bb = ""
strt = int(14)
akh = int(14)
nm = nama
for mm in nm:
akh = akh + 2
aa += """{"S":"""+json.dumps(str(strt))+""","E":"""+json.dumps(str(akh))+""","M":"""+json.dumps(mm)+"},"""
strt = strt + 6
akh = akh + 4
bb += "\xe2\x95\xa0 @x \n"
aa = (aa[:int(len(aa)-1)])
msg = Message()
msg.to = to
msg.text = "\xe2\x95\x94\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\n"+bb+"\xe2\x95\x9a\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90"
msg.contentMetadata ={'MENTION':'{"MENTIONEES":['+aa+']}','EMTVER':'4'}
print "[Command] Tag All"
try:
kr.sendMessage(msg)
except Exception as error:
print error
def waktu(secs):
mins, secs = divmod(secs,60)
hours, mins = divmod(mins,60)
return '%02d Jam %02d Menit %02d Detik' % (hours, mins, secs)
def cms(string, commands): #/XXX, >XXX, ;XXX, ^XXX, %XXX, $XXX...
tex = ["+","@","/",">",";","^","%","$","๏ผพ","ใตใใฉ:","ใตใใฉ:","ใตใใฉ๏ผ","ใตใใฉ๏ผ"]
for texX in tex:
for command in commands:
if string ==command:
return True
return False
def sendMessage(to, text, contentMetadata={}, contentType=0):
mes = Message()
mes.to, mes.from_ = to, profile.mid
mes.text = text
mes.contentType, mes.contentMetadata = contentType, contentMetadata
if to not in messageReq:
messageReq[to] = -1
messageReq[to] += 1
def bot(op):
try:
if op.type == 0:
return
if op.type == 5:
if wait["autoAdd"] == True:
kr.findAndAddContactsByMid(op.param1)
if (wait["message"] in [""," ","\n",None]):
pass
else:
kr.sendText(op.param1,str(wait["message"]))
if op.type == 26:
msg = op.message
if msg.from_ in mimic["target"] and mimic["status"] == True and mimic["target"][msg.from_] == True:
text = msg.text
if text is not None:
kr.sendText(msg.to,text)
if op.type == 13:
print op.param3
if op.param3 in mid:
if op.param2 in admin:
kr.acceptGroupInvitation(op.param1)
if op.type == 13:
if mid in op.param3:
if wait["autoJoin"] == True:
if op.param2 in Bots or admin:
kr.acceptGroupInvitation(op.param1)
else:
kr.rejectGroupInvitation(op.param1)
else:
print "autoJoin is Off"
if op.type == 19:
if op.param3 in admin:
kr.kickoutFromGroup(op.param1,[op.param2])
kr.inviteIntoGroup(op.param1,admin)
kr.inviteIntoGroup(op.param1,[op.param3])
else:
pass
if op.type == 19:
if mid in op.param3:
wait["blacklist"][op.param2] = True
if op.type == 22:
if wait["leaveRoom"] == True:
kr.leaveRoom(op.param1)
if op.type == 24:
if wait["leaveRoom"] == True:
kr.leaveRoom(op.param1)
if op.type == 26:
msg = op.message
if msg.toType == 0:
msg.to = msg.from_
if msg.from_ == mid:
if "join:" in msg.text:
list_ = msg.text.split(":")
try:
kr.acceptGroupInvitationByTicket(list_[1],list_[2])
G = kr.getGroup(list_[1])
G.preventJoinByTicket = True
kr.updateGroup(G)
except:
kr.sendText(msg.to,"error")
if msg.toType == 1:
if wait["leaveRoom"] == True:
kr.leaveRoom(msg.to)
if msg.contentType == 16:
url = msg.contentMetadata["postEndUrl"]
kr.like(url[25:58], url[66:], likeType=1001)
if op.type == 26:
msg = op.message
if msg.from_ in mimic["target"] and mimic["status"] == True and mimic["target"][msg.from_] == True:
text = msg.text
if text is not None:
kr.sendText(msg.to,text)
if op.type == 26:
msg = op.message
if msg.to in settings["simiSimi"]:
if settings["simiSimi"][msg.to] == True:
if msg.text is not None:
text = msg.text
r = requests.get("http://api.ntcorp.us/chatbot/v1/?text=" + text.replace(" ","+") + "&key=beta1.nt")
data = r.text
data = json.loads(data)
if data['status'] == 200:
if data['result']['result'] == 100:
kr.sendText(msg.to, "[From Simi]\n" + data['result']['response'].encode('utf-8'))
if 'MENTION' in msg.contentMetadata.keys() != None:
if wait["detectMention"] == True:
contact = kr.getContact(msg.from_)
cName = contact.displayName
balas = ["Don't Tag Me! iam Bussy!, ",cName + "Ada perlu apa, ?",cName + " pc aja klo urgent! sedang sibuk,", "kenapa, ", cName + " kangen?","kangen bilang gak usah tag tag, " + cName, "knp?, " + cName, "apasi?, " + cName + "?", "pulang gih, " + cName + "?","aya naon, ?" + cName + "Tersangkut -_-"]
ret_ = "." + random.choice(balas)
name = re.findall(r'@(\w+)', msg.text)
mention = ast.literal_eval(msg.contentMetadata['MENTION'])
mentionees = mention['MENTIONEES']
for mention in mentionees:
if mention['M'] in Bots:
kr.sendText(msg.to,ret_)
break
if 'MENTION' in msg.contentMetadata.keys() != None:
if wait["kickMention"] == True:
contact = kr.getContact(msg.from_)
cName = contact.displayName
balas = ["Dont Tag Me!! Im Busy, ",cName + " Ngapain Ngetag?, ",cName + " Nggak Usah Tag-Tag! Kalo Penting Langsung Pc Aja, ", "-_-, ","Kris lagi off, ", cName + " Kenapa Tag saya?, ","SPAM PC aja, " + cName, "Jangan Suka Tag gua, " + cName, "Kamu siapa, " + cName + "?", "Ada Perlu apa, " + cName + "?","Tag doang tidak perlu., "]
ret_ = "[Auto Respond] " + random.choice(balas)
name = re.findall(r'@(\w+)', msg.text)
mention = ast.literal_eval(msg.contentMetadata['MENTION'])
mentionees = mention['MENTIONEES']
for mention in mentionees:
if mention['M'] in Bots:
kr.sendText(msg.to,ret_)
kr.kickoutFromGroup(msg.to,[msg.from_])
break
if msg.contentType == 13:
if wait['invite'] == True:
_name = msg.contentMetadata["displayName"]
invite = msg.contentMetadata["mid"]
groups = kr.getGroup(msg.to)
pending = groups.invitee
targets = []
for s in groups.members:
if _name in s.displayName:
kr.sendText(msg.to, _name + " Berada DiGrup Ini")
else:
targets.append(invite)
if targets == []:
pass
else:
for target in targets:
try:
kr.findAndAddContactsByMid(target)
kr.inviteIntoGroup(msg.to,[target])
kr.sendText(msg.to,"Invite " + _name)
wait['invite'] = False
break
except:
kr.sendText(msg.to,"Error")
wait['invite'] = False
break
#if msg.contentType == 13:
# if wait["steal"] == True:
# _name = msg.contentMetadata["displayName"]
# copy = msg.contentMetadata["mid"]
# groups = kr.getGroup(msg.to)
# pending = groups.invitee
# targets = []
# for s in groups.members:
# if _name in s.displayName:
# print "[Target] Stealed"
# break
# else:
# targets.append(copy)
# if targets == []:
# pass
# else:
# for target in targets:
# try:
# kr.findAndAddContactsByMid(target)
# contact = kr.getContact(target)
# cu = kr.channel.getCover(target)
# path = str(cu)
# image = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
# kr.sendText(msg.to,"Nama :\n" + contact.displayName + "\n\nMid :\n" + msg.contentMetadata["mid"] + "\n\nBio :\n" + contact.statusMessage)
# kr.sendText(msg.to,"Profile Picture " + contact.displayName)
# kr.sendImageWithURL(msg.to,image)
# kr.sendText(msg.to,"Cover " + contact.displayName)
# kr.sendImageWithURL(msg.to,path)
# wait["steal"] = False
# break
# except:
# pass
if wait["alwayRead"] == True:
if msg.toType == 0:
kr.sendChatChecked(msg.from_,msg.id)
else:
kr.sendChatChecked(msg.to,msg.id)
if op.type == 25:
msg = op.message
if msg.contentType == 13:
if wait["wblack"] == True:
if msg.contentMetadata["mid"] in wait["commentBlack"]:
kr.sendText(msg.to,"In Blacklist")
wait["wblack"] = False
else:
wait["commentBlack"][msg.contentMetadata["mid"]] = True
wait["wblack"] = False
kr.sendText(msg.to,"Nothing")
elif wait["dblack"] == True:
if msg.contentMetadata["mid"] in wait["commentBlack"]:
del wait["commentBlack"][msg.contentMetadata["mid"]]
kr.sendText(msg.to,"Done")
wait["dblack"] = False
else:
wait["dblack"] = False
kr.sendText(msg.to,"Not in Blacklist")
elif wait["wblacklist"] == True:
if msg.contentMetadata["mid"] in wait["blacklist"]:
kr.sendText(msg.to,"In Blacklist")
wait["wblacklist"] = False
else:
wait["blacklist"][msg.contentMetadata["mid"]] = True
wait["wblacklist"] = False
kr.sendText(msg.to,"Done")
elif wait["dblacklist"] == True:
if msg.contentMetadata["mid"] in wait["blacklist"]:
del wait["blacklist"][msg.contentMetadata["mid"]]
kr.sendText(msg.to,"Done")
wait["dblacklist"] = False
else:
wait["dblacklist"] = False
kr.sendText(msg.to,"Done")
elif wait["contact"] == True:
msg.contentType = 0
kr.sendText(msg.to,msg.contentMetadata["mid"])
if 'displayName' in msg.contentMetadata:
contact = kr.getContact(msg.contentMetadata["mid"])
try:
cu = kr.channel.getCover(msg.contentMetadata["mid"])
except:
cu = ""
kr.sendText(msg.to,"[displayName]:\n" + msg.contentMetadata["displayName"] + "\n[mid]:\n" + msg.contentMetadata["mid"] + "\n[statusMessage]:\n" + contact.statusMessage + "\n[pictureStatus]:\nhttp://dl.profile.line-cdn.net/" + contact.pictureStatus + "\n[coverURL]:\n" + str(cu))
else:
contact = kr.getContact(msg.contentMetadata["mid"])
try:
cu = kr.channel.getCover(msg.contentMetadata["mid"])
except:
cu = ""
kr.sendText(msg.to,"[displayName]:\n" + contact.displayName + "\n[mid]:\n" + msg.contentMetadata["mid"] + "\n[statusMessage]:\n" + contact.statusMessage + "\n[pictureStatus]:\nhttp://dl.profile.line-cdn.net/" + contact.pictureStatus + "\n[coverURL]:\n" + str(cu))
elif msg.contentType == 16:
if wait["timeline"] == True:
msg.contentType = 0
if wait["lang"] == "JP":
msg.text = "menempatkan URL\n" + msg.contentMetadata["postEndUrl"]
else:
msg.text = msg.contentMetadata["postEndUrl"]
kr.sendText(msg.to,msg.text)
elif msg.text is None:
return
elif msg.text.lower() == 'help':
if wait["lang"] == "JP":
kr.sendText(msg.to,helpmsg)
else:
kr.sendText(msg.to,helpmsg)
elif msg.text.lower() == 'keybot':
if wait["lang"] == "JP":
kr.sendText(msg.to,keymsg)
else:
kr.sendText(msg.to,keymsg)
elif msg.text.lower() == 'keypro':
if wait["lang"] == "JP":
kr.sendText(msg.to,helppro)
else:
kr.sendText(msg.to,helppro)
elif msg.text.lower() == 'keyself':
if wait["lang"] == "JP":
kr.sendText(msg.to,helpself)
else:
kr.sendText(msg.to,helpself)
elif msg.text.lower() == 'keygrup':
if wait["lang"] == "JP":
kr.sendText(msg.to,helpgrup)
else:
kr.sendText(msg.to,helpgrup)
elif msg.text.lower() == 'keyset':
if wait["lang"] == "JP":
kr.sendText(msg.to,helpset)
else:
kr.sendText(msg.to,helpset)
elif msg.text.lower() == 'keytran':
if wait["lang"] == "JP":
kr.sendText(msg.to,helptranslate)
else:
kr.sendText(msg.to,helptranslate)
elif msg.text in ["Sp","Speed","speed"]:
start = time.time()
kr.sendText(msg.to, "โโฃProses.....")
elapsed_time = time.time() - start
kr.sendText(msg.to, "%sseconds" % (elapsed_time))
elif msg.text.lower() == 'crash':
msg.contentType = 13
msg.contentMetadata = {'mid': "u1f41296217e740650e0448b96851a3e2',"}
kr.sendMessage(msg)
kr.sendMessage(msg)
elif msg.text.lower() == 'me':
msg.contentType = 13
msg.contentMetadata = {'mid': mid}
kr.sendMessage(msg)
elif ".fb" in msg.text:
a = msg.text.replace(".fb","")
b = urllib.quote(a)
kr.sendText(msg.to,"ใ Mencari ใ\n" "Type:Mencari Info\nStatus: Proses")
kr.sendText(msg.to, "https://www.facebook.com" + b)
kr.sendText(msg.to,"ใ Mencari ใ\n" "Type:Mencari Info\nStatus: Sukses")
#======================== FOR COMMAND MODE ON STARTING ==========================#
elif msg.text.lower() == 'mode on':
if wait["protect"] == True:
if wait["lang"] == "JP":
kr.sendText(msg.to,"Protecion Already On")
else:
kr.sendText(msg.to,"Protecion Already On")
else:
wait["protect"] = True
if wait["lang"] == "JP":
kr.sendText(msg.to,"Protecion Already On")
else:
kr.sendText(msg.to,"Protecion Already On")
if wait["linkprotect"] == True:
if wait["lang"] == "JP":
kr.sendText(msg.to,"Protection Qr already On")
else:
kr.sendText(msg.to,"Protection Qr already On")
else:
wait["linkprotect"] = True
if wait["lang"] == "JP":
kr.sendText(msg.to,"Protection Qr already On")
else:
kr.sendText(msg.to,"Protection Qr already On")
if wait["inviteprotect"] == True:
if wait["lang"] == "JP":
kr.sendText(msg.to,"Protection Invite already On")
else:
kr.sendText(msg.to,"Protection Invite already On")
else:
wait["inviteprotect"] = True
if wait["lang"] == "JP":
kr.sendText(msg.to,"ฯัฯััยขัฮนฯะธ ฮนะธฮฝฮนัั ััั ัฯ ฯะธ")
else:
kr.sendText(msg.to,"ฯัฯััยขัฮนฯะธ ฮนะธฮฝฮนัั ฮฑโััฮฑโั ฯะธ")
if wait["cancelprotect"] == True:
if wait["lang"] == "JP":
kr.sendText(msg.to,"ยขฮฑะธยขัโ ฯัฯััยขัฮนฯะธ ััั ัฯ ฯะธ")
else:
kr.sendText(msg.to,"ยขฮฑะธยขัโ ฯัฯััยขัฮนฯะธ ฮฑโััฮฑโั ฯะธ")
else:
wait["cancelprotect"] = True
if wait["lang"] == "JP":
kr.sendText(msg.to,"ยขฮฑะธยขัโ ฯัฯััยขัฮนฯะธ ััั ัฯ ฯะธ")
else:
kr.sendText(msg.to,"ยขฮฑะธยขัโ ฯัฯััยขัฮนฯะธ ฮฑโััฮฑโั ฯะธ")
#======================== FOR COMMAND MODE OFF STARTING ==========================#
elif msg.text.lower() == 'mode off':
if wait["protect"] == False:
if wait["lang"] == "JP":
kr.sendText(msg.to,"Protection already Off")
else:
kr.sendText(msg.to,"Protection already Off")
else:
wait["protect"] = False
if wait["lang"] == "JP":
kr.sendText(msg.to,"ฯัฯััยขัฮนฯะธ ััั ัฯ ฯff")
else:
kr.sendText(msg.to,"ฯัฯััยขัฮนฯะธ ฮฑโััฮฑโั ฯff")
if wait["linkprotect"] == False:
if wait["lang"] == "JP":
kr.sendText(msg.to,"Protection Qr already off")
else:
kr.sendText(msg.to,"Protection Qr already off")
else:
wait["linkprotect"] = False
if wait["lang"] == "JP":
kr.sendText(msg.to,"Protection Qr already Off")
else:
kr.sendText(msg.to,"Protection Qr already Off")
if wait["inviteprotect"] == False:
if wait["lang"] == "JP":
kr.sendText(msg.to,"Protection Invite already Off")
else:
kr.sendText(msg.to,"Protection Invite already Off")
else:
wait["inviteprotect"] = False
if wait["lang"] == "JP":
kr.sendText(msg.to,"Protection Invite already Off")
else:
kr.sendText(msg.to,"Protection Invite already Off")
if wait["cancelprotect"] == False:
if wait["lang"] == "JP":
kr.sendText(msg.to,"Protection Cancel already Off")
else:
kr.sendText(msg.to,"Protection Cancel already Off")
else:
wait["cancelprotect"] = False
if wait["lang"] == "JP":
kr.sendText(msg.to,"Protection Cancel already Off")
else:
kr.sendText(msg.to,"Protection Cancel already Off")
#========================== FOR COMMAND BOT STARTING =============================#
elif msg.text.lower() == 'contact on':
if wait["contact"] == True:
if wait["lang"] == "JP":
kr.sendText(msg.to,"ษฯฮทฯฏฮฑษฯฏ ฯฮตฯฏ ฯฏฯ ฯฮท")
else:
kr.sendText(msg.to,"ษฯฮทฯฏฮฑษฯฏ ฯฮตฯฏ ฯฏฯ ฯฮท")
else:
wait["contact"] = True
if wait["lang"] == "JP":
kr.sendText(msg.to,"ษฯฮทฯฏฮฑษฯฏ ฯฮตฯฏ ฯฏฯ ฯฮท")
else:
kr.sendText(msg.to,"ษฯฮทฯฏฮฑษฯฏ ฯฮตฯฏ ฯฏฯ ฯฮท")
elif msg.text.lower() == 'contact off':
if wait["contact"] == False:
if wait["lang"] == "JP":
kr.sendText(msg.to,"ษฯฮทฯฏฮฑษฯฏ ฯฮตฯฏ ฯฏฯ ฯฦฦ")
else:
kr.sendText(msg.to,"ษฯฮทฯฏฮฑษฯฏ ฮฑสษพฮตฮฑฮดฯ ฯฦฦ")
else:
wait["contact"] = False
if wait["lang"] == "JP":
kr.sendText(msg.to,"ษฯฮทฯฏฮฑษฯฏ ฯฮตฯฏ ฯฏฯ ฯฦฦ")
else:
kr.sendText(msg.to,"ษฯฮทฯฏฮฑษฯฏ ฮฑสษพฮตฮฑฮดฯ ฯฦฦ")
elif msg.text.lower() == 'protect on':
if wait["protect"] == True:
if wait["lang"] == "JP":
kr.sendText(msg.to,"Protecion Already On")
else:
kr.sendText(msg.to,"Protecion Already On")
else:
wait["protect"] = True
if wait["lang"] == "JP":
kr.sendText(msg.to,"Protecion Already On")
else:
kr.sendText(msg.to,"Protecion Already On")
elif msg.text.lower() == 'qr on':
if wait["linkprotect"] == True:
if wait["lang"] == "JP":
kr.sendText(msg.to,"Protection Qr already On")
else:
kr.sendText(msg.to,"Protection Qr already On")
else:
wait["linkprotect"] = True
if wait["lang"] == "JP":
kr.sendText(msg.to,"Protection Qr already On")
else:
kr.sendText(msg.to,"Protection Qr already On")
elif msg.text.lower() == 'invite on':
if wait["inviteprotect"] == True:
if wait["lang"] == "JP":
kr.sendText(msg.to,"Protection Invite already On")
else:
kr.sendText(msg.to,"Protection Invite already On")
else:
wait["inviteprotect"] = True
if wait["lang"] == "JP":
kr.sendText(msg.to,"ฯัฯััยขัฮนฯะธ ฮนะธฮฝฮนัั ััั ัฯ ฯะธ")
else:
kr.sendText(msg.to,"ฯัฯััยขัฮนฯะธ ฮนะธฮฝฮนัั ฮฑโััฮฑโั ฯะธ")
elif msg.text.lower() == 'cancel on':
if wait["cancelprotect"] == True:
if wait["lang"] == "JP":
kr.sendText(msg.to,"ยขฮฑะธยขัโ ฯัฯััยขัฮนฯะธ ััั ัฯ ฯะธ")
else:
kr.sendText(msg.to,"ยขฮฑะธยขัโ ฯัฯััยขัฮนฯะธ ฮฑโััฮฑโั ฯะธ")
else:
wait["cancelprotect"] = True
if wait["lang"] == "JP":
kr.sendText(msg.to,"ยขฮฑะธยขัโ ฯัฯััยขัฮนฯะธ ััั ัฯ ฯะธ")
else:
kr.sendText(msg.to,"ยขฮฑะธยขัโ ฯัฯััยขัฮนฯะธ ฮฑโััฮฑโั ฯะธ")
elif msg.text.lower() == 'autojoin on':
if wait["autoJoin"] == True:
if wait["lang"] == "JP":
kr.sendText(msg.to,"ฮฑฯ
ัฯสฯฮนะธ ััั ัฯ ฯะธ")
else:
kr.sendText(msg.to,"ฮฑฯ
ัฯสฯฮนะธ ฮฑโััฮฑโั ฯะธ")
else:
wait["autoJoin"] = True
if wait["lang"] == "JP":
kr.sendText(msg.to,"ฮฑฯ
ัฯสฯฮนะธ ััั ัฯ ฯะธ")
else:
kr.sendText(msg.to,"ฮฑฯ
ัฯสฯฮนะธ ฮฑโััฮฑโั ฯะธ")
elif msg.text.lower() == 'autojoin off':
if wait["autoJoin"] == False:
if wait["lang"] == "JP":
kr.sendText(msg.to,"ฮฑฯ
ัฯสฯฮนะธ ััั ัฯ ฯff")
else:
kr.sendText(msg.to,"ฮฑฯ
ัฯสฯฮนะธ ฮฑโััฮฑโั ฯff")
else:
wait["autoJoin"] = False
if wait["lang"] == "JP":
kr.sendText(msg.to,"ฮฑฯ
ัฯสฯฮนะธ ััั ัฯ ฯff")
else:
kr.sendText(msg.to,"ฮฑฯ
ัฯสฯฮนะธ ฮฑโััฮฑโั ฯff")
elif msg.text.lower() == 'protect off':
if wait["protect"] == False:
if wait["lang"] == "JP":
kr.sendText(msg.to,"Protection already Off")
else:
kr.sendText(msg.to,"Protection already Off")
else:
wait["protect"] = False
if wait["lang"] == "JP":
kr.sendText(msg.to,"ฯัฯััยขัฮนฯะธ ััั ัฯ ฯff")
else:
kr.sendText(msg.to,"ฯัฯััยขัฮนฯะธ ฮฑโััฮฑโั ฯff")
elif msg.text.lower() == 'qr off':
if wait["linkprotect"] == False:
if wait["lang"] == "JP":
kr.sendText(msg.to,"Protection Qr already off")
else:
kr.sendText(msg.to,"Protection Qr already off")
else:
wait["linkprotect"] = False
if wait["lang"] == "JP":
kr.sendText(msg.to,"Protection Qr already Off")
else:
kr.sendText(msg.to,"Protection Qr already Off")
elif msg.text.lower() == 'invit off':
if wait["inviteprotect"] == False:
if wait["lang"] == "JP":
kr.sendText(msg.to,"Protection Invite already Off")
else:
kr.sendText(msg.to,"Protection Invite already Off")
else:
wait["inviteprotect"] = False
if wait["lang"] == "JP":
kr.sendText(msg.to,"Protection Invite already Off")
else:
kr.sendText(msg.to,"Protection Invite already Off")
elif msg.text.lower() == 'cancel off':
if wait["cancelprotect"] == False:
if wait["lang"] == "JP":
kr.sendText(msg.to,"Protection Cancel already Off")
else:
kr.sendText(msg.to,"Protection Cancel already Off")
else:
wait["cancelprotect"] = False
if wait["lang"] == "JP":
kr.sendText(msg.to,"Protection Cancel already Off")
else:
kr.sendText(msg.to,"Protection Cancel already Off")
elif "Grup cancel:" in msg.text:
try:
strnum = msg.text.replace("Grup cancel:","")
if strnum == "off":
wait["autoCancel"]["on"] = False
if wait["lang"] == "JP":
kr.sendText(msg.to,"Itu off undangan ditolak??\nSilakan kirim dengan menentukan jumlah orang ketika Anda menghidupkan")
else:
kr.sendText(msg.to,"Off undangan ditolak??Sebutkan jumlah terbuka ketika Anda ingin mengirim")
else:
num = int(strnum)
wait["autoCancel"]["on"] = True
if wait["lang"] == "JP":
kr.sendText(msg.to,strnum + "Kelompok berikut yang diundang akan ditolak secara otomatis")
else:
kr.sendText(msg.to,strnum + "The team declined to create the following automatic invitation")
except:
if wait["lang"] == "JP":
kr.sendText(msg.to,"Nilai tidak benar")
else:
kr.sendText(msg.to,"Weird value")
elif msg.text.lower() == 'autoleave on':
if wait["leaveRoom"] == True:
if wait["lang"] == "JP":
kr.sendText(msg.to,"Auto Leave room set to on")
else:
kr.sendText(msg.to,"Auto Leave room already on")
else:
wait["leaveRoom"] = True
if wait["lang"] == "JP":
kr.sendText(msg.to,"Auto Leave room set to on")
else:
kr.sendText(msg.to,"Auto Leave room already on")
elif msg.text.lower() == 'autoleave off':
if wait["leaveRoom"] == False:
if wait["lang"] == "JP":
kr.sendText(msg.to,"Auto Leave room set to off")
else:
kr.sendText(msg.to,"Auto Leave room already off")
else:
wait["leaveRoom"] = False
if wait["lang"] == "JP":
kr.sendText(msg.to,"Auto Leave room set to off")
else:
kr.sendText(msg.to,"Auto Leave room already off")
elif msg.text.lower() == 'share on':
if wait["timeline"] == True:
if wait["lang"] == "JP":
kr.sendText(msg.to,"Share set to on")
else:
kr.sendText(msg.to,"Share already on")
else:
wait["timeline"] = True
if wait["lang"] == "JP":
kr.sendText(msg.to,"Share set to on")
else:
kr.sendText(msg.to,"Share already on")
elif msg.text.lower() == 'share off':
if wait["timeline"] == False:
if wait["lang"] == "JP":
kr.sendText(msg.to,"Share set to off")
else:
kr.sendText(msg.to,"Share already off")
else:
wait["timeline"] = False
if wait["lang"] == "JP":
kr.sendText(msg.to,"Share set to off")
else:
kr.sendText(msg.to,"Share already off")
elif msg.text.lower() == 'status':
md = """โโโโโโโโโโโโโโ\n"""
if wait["contact"] == True: md+="โ โโฃContact:on [โ
]\n"
else: md+="โ โโฃContact:off [โ]\n"
if wait["autoJoin"] == True: md+="โ โโฃAuto Join:on [โ
]\n"
else: md +="โ โโฃAuto Join:off [โ]\n"
if wait["autoCancel"]["on"] == True:md+="โ โโฃAuto cancel:" + str(wait["autoCancel"]["members"]) + "[โ
]\n"
else: md+= "โ โโฃGroup cancel:off [โ]\n"
if wait["leaveRoom"] == True: md+="โ โโฃAuto leave:on [โ
]\n"
else: md+="โ โโฃAuto leave:off [โ]\n"
if wait["timeline"] == True: md+="โ โโฃShare:on [โ
]\n"
else:md+="โ โโฃShare:off [โ]\n"
if wait["autoAdd"] == True: md+="โ โโฃAuto add:on [โ
]\n"
else:md+="โ โโฃAuto add:off [โ]\n"
if wait["protect"] == True: md+="โ โโฃProtect:on [โ
]\n"
else:md+="โ โโฃProtect:off [โ]\n"
if wait["linkprotect"] == True: md+="โ โโฃLink Protect:on [โ
]\n"
else:md+="โ โโฃLink Protect:off [โ]\n"
if wait["inviteprotect"] == True: md+="โ โโฃInvitation Protect:on [โ
]\n"
else:md+="โ โโฃInvitation Protect:off [โ]\n"
if wait["cancelprotect"] == True: md+="โ โโฃCancel Protect:on [โ
]\n"
else:md+="โ โโฃCancel Protect:off [โ]\nโโโโโโโโโโโโโโ"
kr.sendText(msg.to,md)
msg.contentType = 13
msg.contentMetadata = {'mid': "u31ef22df7f538df1d74dc7f756ef1a32"}
kr.sendMessage(msg)
elif cms(msg.text,["creator","Creator"]):
msg.contentType = 13
msg.contentMetadata = {'mid': "u31ef22df7f538df1d74dc7f756ef1a32"}
kr.sendMessage(msg)
kr.sendText(msg.to,'โโฃ Creator yang manis kalem ๔๔ฏ๔ฟฟ')
elif msg.text.lower() == 'autoadd on':
if wait["autoAdd"] == True:
if wait["lang"] == "JP":
kr.sendText(msg.to,"Auto add set to on")
else:
kr.sendText(msg.to,"Auto add already on")
else:
wait["autoAdd"] = True
if wait["lang"] == "JP":
kr.sendText(msg.to,"Auto add set to on")
else:
kr.sendText(msg.to,"Auto add already on")
elif msg.text.lower() == 'autoadd off':
if wait["autoAdd"] == False:
if wait["lang"] == "JP":
kr.sendText(msg.to,"Auto add set to off")
else:
kr.sendText(msg.to,"Auto add already off")
else:
wait["autoAdd"] = False
if wait["lang"] == "JP":
kr.sendText(msg.to,"Auto add set to off")
else:
kr.sendText(msg.to,"Auto add already off")
elif "Pesan set:" in msg.text:
wait["message"] = msg.text.replace("Pesan set:","")
kr.sendText(msg.to,"We changed the message")
elif msg.text.lower() == 'pesan cek':
if wait["lang"] == "JP":
kr.sendText(msg.to,"Pesan tambahan otomatis telah ditetapkan sebagai berikut \n\n" + wait["message"])
else:
kr.sendText(msg.to,"Pesan tambahan otomatis telah ditetapkan sebagai berikut \n\n" + wait["message"])
elif "Come Set:" in msg.text:
c = msg.text.replace("Come Set:","")
if c in [""," ","\n",None]:
kr.sendText(msg.to,"Merupakan string yang tidak bisa diubah")
else:
wait["comment"] = c
kr.sendText(msg.to,"Ini telah diubah\n\n" + c)
elif msg.text in ["Com on","Com:on","Comment on"]:
if wait["commentOn"] == True:
if wait["lang"] == "JP":
kr.sendText(msg.to,"Aku berada di")
else:
kr.sendText(msg.to,"To open")
else:
wait["commentOn"] = True
if wait["lang"] == "JP":
kr.sendText(msg.to,"Comment Actived")
else:
kr.sendText(msg.to,"Comment Has Been Active")
elif msg.text in ["Come off"]:
if wait["commentOn"] == False:
if wait["lang"] == "JP":
kr.sendText(msg.to,"Hal ini sudah off")
else:
kr.sendText(msg.to,"It is already turned off")
else:
wait["commentOn"] = False
if wait["lang"] == "JP":
kr.sendText(msg.to,"Off")
else:
kr.sendText(msg.to,"To turn off")
elif msg.text in ["Com","Comment"]:
kr.sendText(msg.to,"Auto komentar saat ini telah ditetapkan sebagai berikut:??\n\n" + str(wait["comment"]))
elif msg.text in ["Com Bl"]:
wait["wblack"] = True
kr.sendText(msg.to,"Please send contacts from the person you want to add to the blacklist")
elif msg.text in ["Com hapus Bl"]:
wait["dblack"] = True
kr.sendText(msg.to,"Please send contacts from the person you want to add from the blacklist")
elif msg.text in ["Com Bl cek"]:
if wait["commentBlack"] == {}:
kr.sendText(msg.to,"Nothing in the blacklist")
else:
kr.sendText(msg.to,"The following is a blacklist")
mc = ""
for mi_d in wait["commentBlack"]:
mc += "รฃฦยป" +kr.getContact(mi_d).displayName + "\n"
kr.sendText(msg.to,mc)
elif msg.text.lower() == 'jam on':
if wait["clock"] == True:
kr.sendText(msg.to,"Jam already on")
else:
wait["clock"] = True
now2 = datetime.now()
nowT = datetime.strftime(now2,"?%H:%M?")
profile = kr.getProfile()
profile.displayName = wait["cName"] + nowT
kr.updateProfile(profile)
kr.sendText(msg.to,"Jam set on")
elif msg.text.lower() == 'jam off':
if wait["clock"] == False:
kr.sendText(msg.to,"Jam already off")
else:
wait["clock"] = False
kr.sendText(msg.to,"Jam set off")
elif "Jam say:" in msg.text:
n = msg.text.replace("Jam say:","")
if len(n.decode("utf-8")) > 30:
kr.sendText(msg.to,"terlalu lama")
else:
wait["cName"] = n
kr.sendText(msg.to,"Nama Jam Berubah menjadi:" + n)
elif msg.text.lower() == 'update':
if wait["clock"] == True:
now2 = datetime.now()
nowT = datetime.strftime(now2,"?%H:%M?")
profile = kr.getProfile()
profile.displayName = wait["cName"] + nowT
kr.updateProfile(profile)
kr.sendText(msg.to,"Diperbarui")
else:
kr.sendText(msg.to,"Silahkan Aktifkan Jam")
elif "Image " in msg.text:
search = msg.text.replace("Image ","")
url = 'https://www.google.com/search?espv=2&biw=1366&bih=667&tbm=isch&oq=kuc&aqs=mobile-gws-lite.0.0l5&q=' + search
raw_html = (download_page(url))
items = []
items = items + (_images_get_all_items(raw_html))
path = random.choice(items)
print path
try:
kr.sendImageWithURL(msg.to,path)
except:
pass
#========================== FOR COMMAND BOT FINISHED =============================#
elif "Spam change:" in msg.text:
if msg.toType == 2:
wait["spam"] = msg.text.replace("Spam change:","")
kr.sendText(msg.to,"spam changed")
elif "Spam add:" in msg.text:
if msg.toType == 2:
wait["spam"] = msg.text.replace("Spam add:","")
if wait["lang"] == "JP":
kr.sendText(msg.to,"spam changed")
else:
kr.sendText(msg.to,"Done")
elif "Spam:" in msg.text:
if msg.toType == 2:
strnum = msg.text.replace("Spam:","")
num = int(strnum)
for var in range(0,num):
kr.sendText(msg.to, wait["spam"])
#=====================================
elif "Spam " in msg.text:
if msg.toType == 2:
bctxt = msg.text.replace("Spam ", "")
t = kr.getAllContactIds()
t = 500
while(t):
kr.sendText(msg.to, (bctxt))
t-=1
#==============================================
elif "Spamcontact @" in msg.text:
_name = msg.text.replace("Spamcontact @","")
_nametarget = _name.rstrip(' ')
gs = kr.getGroup(msg.to)
for g in gs.members:
if _nametarget == g.displayName:
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(g.mid,"Spam")
kr.sendText(msg.to, "Done")
print " Spammed !"
#==============================================================================#
elif msg.text in ["Invite"]:
wait["invite"] = True
kr.sendText(msg.to,"Send Contact")
elif msg.text in ["Steal contact"]:
wait["contact"] = True
kr.sendText(msg.to,"Send Contact")
elif msg.text in ["Like:me","Like me"]: #Semua Bot Ngelike Status Akun Utama
print "[Command]Like executed"
kr.sendText(msg.to,"Like Status Owner")
try:
likeme()
except:
pass
elif msg.text in ["Like:friend","Like friend"]: #Semua Bot Ngelike Status Teman
print "[Command]Like executed"
kr.sendText(msg.to,"Like Status Teman")
try:
likefriend()
except:
pass
elif msg.text in ["Like:on","Like on"]:
if wait["likeOn"] == True:
if wait["lang"] == "JP":
kr.sendText(msg.to,"Done")
else:
wait["likeOn"] = True
if wait["lang"] == "JP":
kr.sendText(msg.to,"Already")
elif msg.text in ["Like off","Like:off"]:
if wait["likeOn"] == False:
if wait["lang"] == "JP":
kr.sendText(msg.to,"Done")
else:
wait["likeOn"] = False
if wait["lang"] == "JP":
kr.sendText(msg.to,"Already")
elif msg.text in ["Simisimi on","Simisimi:on"]:
settings["simiSimi"][msg.to] = True
kr.sendText(msg.to,"Simi mode On")
elif msg.text in ["Simisimi off","Simisimi:off"]:
settings["simiSimi"][msg.to] = False
kr.sendText(msg.to,"Simi mode Off")
elif msg.text in ["Autoread on","Read:on"]:
wait['alwayRead'] = True
kr.sendText(msg.to,"Auto read On")
elif msg.text in ["Autoread off","Read:off"]:
wait['alwayRead'] = False
kr.sendText(msg.to,"Auto read Off")
elif msg.text in ["Respontag on","Autorespon:on","Respon on","Respon:on"]:
wait["detectMention"] = True
kr.sendText(msg.to,"Auto respon tag On")
elif msg.text in ["Respontag off","Autorespon:off","Respon off","Respon:off"]:
wait["detectMention"] = False
kr.sendText(msg.to,"Auto respon tag Off")
elif msg.text in ["Kicktag on","Autokick:on","Responkick on","Responkick:on"]:
wait["kickMention"] = True
kr.sendText(msg.to,"Auto Kick tag ON")
elif msg.text in ["Kicktag off","Autokick:off","Responkick off","Responkick:off"]:
wait["kickMention"] = False
kr.sendText(msg.to,"Auto Kick tag OFF")
elif "Time" in msg.text:
if msg.toType == 2:
kr.sendText(msg.to,datetime.today().strftime('%H:%M:%S'))
#==============================================================================#
elif msg.text in ["Sambut on","sambut on"]:
if wait["Wc"] == True:
if wait["lang"] == "JP":
kr.sendText(msg.to,"noัฮนา yg joฮนn on")
else:
wait["Wc"] = True
if wait["lang"] == "JP":
kr.sendText(msg.to,"already on")
elif msg.text in ["Sambut off","sambut off"]:
if wait["Wc"] == False:
if wait["lang"] == "JP":
kr.sendText(msg.to,"noัฮนา yg joฮนn oาา")
else:
wait["Wc"] = False
if wait["lang"] == "JP":
kr.sendText(msg.to,"already oาา")
#==============================================================================#
elif msg.text in ["Pergi on","pergi on"]:
if wait["Lv"] == True:
if wait["lang"] == "JP":
kr.sendText(msg.to,"noัฮนา yg leave on")
else:
wait["Lv"] = True
if wait["lang"] == "JP":
kr.sendText(msg.to,"already on")
elif msg.text in ["Pergi off","pergi off"]:
if wait["Lv"] == False:
if wait["lang"] == "JP":
kr.sendText(msg.to,"noัฮนา yg leave oาา")
else:
wait["Lv"] = False
if wait["lang"] == "JP":
kr.sendText(msg.to,"already oาา")
#==============================================================================#
elif "Cleanse" in msg.text:
if msg.toType == 2:
if msg.toType == 2:
print "ok"
_name = msg.text.replace("Cleanse","")
gs = kr.getGroup(msg.to)
gs = kr.getGroup(msg.to)
gs = kr.getGroup(msg.to)
kr.sendText(msg.to,"Just some casual cleansing รด")
kr.sendText(msg.to,"Group cleansed.")
targets = []
for g in gs.members:
if _name in g.displayName:
targets.append(g.mid)
if targets == []:
kr.sendText(msg.to,"Not found.")
kr.sendText(msg.to,"Not found.")
else:
for target in targets:
try:
klist=[kr,kr,kr]
kicker=random.choice(klist)
kicker.kickoutFromGroup(msg.to,[target])
print (msg.to,[g.mid])
except:
kr.sendText(msg.to,"Group cleanse")
kr.sendText(msg.to,"Group cleanse")
elif msg.text in ["Salam1"]:
kr.sendText(msg.to,"ุงูุณูููุงูู
ู ุนูููููููู
ู ููุฑูุญูู
ูุฉู ุงูููู ููุจูุฑูููุงุชููู")
kr.sendText(msg.to,"Assalamu'alaikum")
elif msg.text in ["Salam2"]:
kr.sendText(msg.to,"ููุนูููููููู
ู ุงูุณูููุงูู
ูุฑูุญูู
ูุฉู ุงูููู ููุจูุฑูููุงุชููู")
kr.sendText(msg.to,"Wa'alaikumsallam.Wr,Wb")
elif "Salam3" in msg.text:
if msg.from_ in owner:
kr.sendText(msg.to,"ุงูุณูููุงูู
ู ุนูููููููู
ู ููุฑูุญูู
ูุฉู ุงูููู ููุจูุฑูููุงุชููู")
kr.sendText(msg.to,"Assalamu'alaikum")
kr.sendText(msg.to,"ููุนูููููููู
ู ุงูุณูููุงูู
ู ููุฑูุญูู
ูุฉู ุงููููููุจูุฑูููุงุชููู")
kr.sendText(msg.to,"Wa'alaikumsallam.Wr,Wb")
if msg.toType == 2:
print "ok"
_name = msg.text.replace("Salam3","")
gs = kr.getGroup(msg.to)
kr.sendText(msg.to,"maaf kalo gak sopan")
kr.sendText(msg.to,"Qo salamnya gak ada yang jawab ya..!!")
kr.sendText(msg.to,"hehehhehe")
targets = []
for g in gs.members:
if _name in g.displayName:
targets.append(g.mid)
if targets == []:
kr.sendText(msg.to,"Not found")
else:
for target in targets:
if target not in admin:
try:
klist=[kr]
kicker=random.choice(klist)
kicker.kickoutFromGroup(msg.to,[target])
print (msg.to,[g.mid])
except:
kr.sendText(msg.to,"ุงูุณูููุงูู
ู ุนูููููููู
ู ููุฑูุญูู
ูุฉู ุงูููู ููุจูุฑูููุงุชููู")
kr.sendText(msg.to,"ููุนูููููููู
ู ุงูุณูููุงูู
ู ููุฑูุญูู
ูุฉู ุงููููููุจูุฑูููุงุชููู")
kr.sendText(msg.to,"Nah salamnya jawab sendiri dah")
elif ("Kick " in msg.text):
targets = []
key = eval(msg.contentMetadata["MENTION"])
key["MENTIONEES"] [0] ["M"]
for x in key["MENTIONEES"]:
targets.append(x["M"])
for target in targets:
try:
kr.kickoutFromGroup(msg.to,[target])
except:
kr.sendText(msg.to,"Error")
elif ("Cium " in msg.text):
targets = []
key = eval(msg.contentMetadata["MENTION"])
key["MENTIONEES"] [0] ["M"]
for x in key["MENTIONEES"]:
targets.append(x["M"])
for target in targets:
try:
kr.kickoutFromGroup(msg.to,[target])
kr.inviteIntoGroup(msg.to,[target])
kr.cancelGroupInvitation(msg.to,[target])
except:
kr.sendText(msg.to,"Error")
elif "Kick: " in msg.text:
midd = msg.text.replace("Kick: ","")
kr.kickoutFromGroup(msg.to,[midd])
elif 'invite ' in msg.text.lower():
key = msg.text[-33:]
kr.findAndAddContactsByMid(key)
kr.inviteIntoGroup(msg.to, [key])
contact = kr.getContact(key)
elif msg.text.lower() == 'cancel':
if msg.toType == 2:
group = kr.getGroup(msg.to)
if group.invitee is not None:
gInviMids = [contact.mid for contact in group.invitee]
kr.cancelGroupInvitation(msg.to, gInviMids)
else:
if wait["lang"] == "JP":
kr.sendText(msg.to,"Tidak ada undangan")
else:
kr.sendText(msg.to,"Invitan tidak ada")
else:
if wait["lang"] == "JP":
kr.sendText(msg.to,"Tidak ada undangan")
else:
kr.sendText(msg.to,"Invitan tidak ada")
elif msg.text.lower() == 'link on':
if msg.toType == 2:
group = kr.getGroup(msg.to)
group.preventJoinByTicket = False
kr.updateGroup(group)
if wait["lang"] == "JP":
kr.sendText(msg.to,"URL open")
else:
kr.sendText(msg.to,"URL open")
else:
if wait["lang"] == "JP":
kr.sendText(msg.to,"It can not be used outside the group")
else:
kr.sendText(msg.to,"Can not be used for groups other than")
elif msg.text.lower() == 'link off':
if msg.toType == 2:
group = kr.getGroup(msg.to)
group.preventJoinByTicket = True
kr.updateGroup(group)
if wait["lang"] == "JP":
kr.sendText(msg.to,"URL close")
else:
kr.sendText(msg.to,"URL close")
else:
if wait["lang"] == "JP":
kr.sendText(msg.to,"It can not be used outside the group")
else:
kr.sendText(msg.to,"Can not be used for groups other than")
elif msg.text in ["Url","Gurl"]:
if msg.toType == 2:
g = kr.getGroup(msg.to)
if g.preventJoinByTicket == True:
g.preventJoinByTicket = False
kr.updateGroup(g)
gurl = kr.reissueGroupTicket(msg.to)
kr.sendText(msg.to,"line://ti/g/" + gurl)
elif "Gcreator" == msg.text:
try:
group = kr.getGroup(msg.to)
GS = group.creator.mid
M = Message()
M.to = msg.to
M.contentType = 13
M.contentMetadata = {'mid': GS}
kr.sendMessage(M)
except:
W = group.members[0].mid
M = Message()
M.to = msg.to
M.contentType = 13
M.contentMetadata = {'mid': W}
kr.sendMessage(M)
kr.sendText(msg.to,"Creator Grup")
elif msg.text.lower() == 'invite:gcreator':
if msg.toType == 2:
ginfo = kr.getGroup(msg.to)
try:
gcmid = ginfo.creator.mid
except:
gcmid = "Error"
if wait["lang"] == "JP":
kr.inviteIntoGroup(msg.to,[gcmid])
else:
kr.inviteIntoGroup(msg.to,[gcmid])
elif ("Gname: " in msg.text):
if msg.toType == 2:
X = kr.getGroup(msg.to)
X.name = msg.text.replace("Gname: ","")
kr.updateGroup(X)
elif msg.text.lower() == 'infogrup':
group = kr.getGroup(msg.to)
try:
gCreator = group.creator.displayName
except:
gCreator = "Error"
md = "[Nama Grup : ]\n" + group.name + "\n\n[Id Grup : ]\n" + group.id + "\n\n[Pembuat Grup :]\n" + gCreator + "\n\n[Gambar Grup : ]\nhttp://dl.profile.line-cdn.net/" + group.pictureStatus
if group.preventJoinByTicket is False: md += "\n\nKode Url : Diizinkan"
else: md += "\n\nKode Url : Diblokir"
if group.invitee is None: md += "\nJumlah Member : " + str(len(group.members)) + " Orang" + "\nUndangan Yang Belum Diterima : 0 Orang"
else: md += "\nJumlah Member : " + str(len(group.members)) + " Orang" + "\nUndangan Yang Belum Diterima : " + str(len(group.invitee)) + " Orang"
kr.sendText(msg.to,md)
elif msg.text.lower() == 'grup id':
gid = kr.getGroupIdsJoined()
h = ""
for i in gid:
h += "[%s]:%s\n" % (kr.getGroup(i).name,i)
kr.sendText(msg.to,h)
#==============================================================================#
elif msg.text in ["Glist"]:
gid = kr.getGroupIdsJoined()
h = ""
for i in gid:
h += "%s\n" % (kr.getGroup(i).name +" ? ["+str(len(kr.getGroup(i).members))+"]")
kr.sendText(msg.to,"-- List Groups --\n\n"+ h +"\nTotal groups =" +" ["+str(len(gid))+"]")
elif msg.text.lower() == 'gcancel':
gid = kr.getGroupIdsInvited()
for i in gid:
kr.rejectGroupInvitation(i)
if wait["lang"] == "JP":
kr.sendText(msg.to,"Aku menolak semua undangan")
else:
kr.sendText(msg.to,"He declined all invitations")
elif "Auto add" in msg.text:
thisgroup = kr.getGroups([msg.to])
Mids = [contact.mid for contact in thisgroup[0].members]
mi_d = Mids[:33]
kr.findAndAddContactsByMids(mi_d)
kr.sendText(msg.to,"Success Add all")
elif "@bye" in msg.text:
if msg.toType == 2:
ginfo = kr.getGroup(msg.to)
try:
kr.leaveGroup(msg.to)
except:
pass
#==============================================================================#
elif "nah" == msg.text.lower():
group = kr.getGroup(msg.to)
nama = [contact.mid for contact in group.members]
nm1, nm2, nm3, nm4, nm5, jml = [], [], [], [], [], len(nama)
if jml <= 100:
summon(msg.to, nama)
if jml > 100 and jml < 200:
for i in range(0, 99):
nm1 += [nama[i]]
summon(msg.to, nm1)
for j in range(100, len(nama)-1):
nm2 += [nama[j]]
summon(msg.to, nm2)
if jml > 200 and jml < 500:
for i in range(0, 99):
nm1 += [nama[i]]
summon(msg.to, nm1)
for j in range(100, 199):
nm2 += [nama[j]]
summon(msg.to, nm2)
for k in range(200, 299):
nm3 += [nama[k]]
summon(msg.to, nm3)
for l in range(300, 399):
nm4 += [nama[l]]
summon(msg.to, nm4)
for m in range(400, len(nama)-1):
nm5 += [nama[m]]
summon(msg.to, nm5)
if jml > 500:
print "Terlalu Banyak Men 500+"
cnt = Message()
cnt.text = "Jumlah:\n" + str(jml) + " Members"
cnt.to = msg.to
kr.sendMessage(cnt)
elif "cctv on" == msg.text.lower():
if msg.to in wait2['readPoint']:
try:
del wait2['readPoint'][msg.to]
del wait2['readMember'][msg.to]
del wait2['setTime'][msg.to]
except:
pass
wait2['readPoint'][msg.to] = msg.id
wait2['readMember'][msg.to] = ""
wait2['setTime'][msg.to] = datetime.now().strftime('%H:%M:%S')
wait2['ROM'][msg.to] = {}
with open('sider.json', 'w') as fp:
json.dump(wait2, fp, sort_keys=True, indent=4)
kr.sendText(msg.to,"Setpoint already on")
else:
try:
del wait2['readPoint'][msg.to]
del wait2['readMember'][msg.to]
del wait2['setTime'][msg.to]
except:
pass
wait2['readPoint'][msg.to] = msg.id
wait2['readMember'][msg.to] = ""
wait2['setTime'][msg.to] = datetime.now().strftime('%H:%M:%S')
wait2['ROM'][msg.to] = {}
with open('sider.json', 'w') as fp:
json.dump(wait2, fp, sort_keys=True, indent=4)
kr.sendText(msg.to, "Set reading point:\n" + datetime.now().strftime('%H:%M:%S'))
print wait2
elif "cctv off" == msg.text.lower():
if msg.to not in wait2['readPoint']:
kr.sendText(msg.to,"Setpoint already off")
else:
try:
del wait2['readPoint'][msg.to]
del wait2['readMember'][msg.to]
del wait2['setTime'][msg.to]
except:
pass
kr.sendText(msg.to, "Delete reading point:\n" + datetime.now().strftime('%H:%M:%S'))
elif msg.text in ["toong","Toong"]:
if msg.toType == 2:
print "\nRead aktif..."
if msg.to in wait2['readPoint']:
if wait2["ROM"][msg.to].items() == []:
chiya = ""
else:
chiya = ""
for rom in wait2["ROM"][msg.to].items():
print rom
chiya += rom[1] + "\n"
kr.sendText(msg.to, "โโโโโโโโโโโโโโ \nโ โโฃSider :\nโ โโโโโโโโโโโโโ %s\nโ \nโ โโโโโโโโโโโโโ\nโ โโฃReader :\nโ โโโโโโโโโโโโโ %s\nโ \nโ โโโโโโโโโโโโโ\nโ In the last seen point:\nโ [%s]\nโโโโโโโโโโโโโโ" % (wait2['readMember'][msg.to],chiya,setTime[msg.to]))
print "\nReading Point Set..."
try:
del wait2['readPoint'][msg.to]
del wait2['readMember'][msg.to]
except:
pass
wait2['readPoint'][msg.to] = msg.id
wait2['readMember'][msg.to] = ""
wait2['setTime'][msg.to] = datetime.today().strftime('%Y-%m-%d %H:%M:%S')
wait2['ROM'][msg.to] = {}
print "toong ready"
kr.sendText(msg.to, "Auto Read Point!!" + (wait2['setTime'][msg.to]))
else:
kr.sendText(msg.to, "Ketik [Cctv on] dulu, baru ketik [Toong]")
elif "intip" == msg.text.lower():
if msg.to in wait2['readPoint']:
if wait2["ROM"][msg.to].items() == []:
kr.sendText(msg.to, "Reader:\nNone")
else:
chiya = []
for rom in wait2["ROM"][msg.to].items():
chiya.append(rom[1])
cmem = kr.getContacts(chiya)
zx = ""
zxc = ""
zx2 = []
xpesan = ''
for x in range(len(cmem)):
xname = str(cmem[x].displayName)
pesan = ''
pesan2 = pesan+"@a\n"
xlen = str(len(zxc)+len(xpesan))
xlen2 = str(len(zxc)+len(pesan2)+len(xpesan)-1)
zx = {'S':xlen, 'E':xlen2, 'M':cmem[x].mid}
zx2.append(zx)
zxc += pesan2
msg.contentType = 0
print zxc
msg.text = xpesan+ zxc + "\nBefore: %s\nAfter: %s"%(wait2['setTime'][msg.to],datetime.now().strftime('%H:%M:%S'))
lol ={'MENTION':str('{"MENTIONEES":'+json.dumps(zx2).replace(' ','')+'}')}
print lol
msg.contentMetadata = lol
try:
kr.sendMessage(msg)
except Exception as error:
print error
pass
else:
kr.sendText(msg.to, "Lurking has not been set.")
elif "Gbroadcast: " in msg.text:
bc = msg.text.replace("Gbroadcast: ","")
gid = kr.getGroupIdsJoined()
for i in gid:
kr.sendText(i, bc)
elif "Cbroadcast: " in msg.text:
bc = msg.text.replace("Cbroadcast: ","")
gid = kr.getAllContactIds()
for i in gid:
kr.sendText(i, bc)
elif "Spam change: " in msg.text:
wait["spam"] = msg.text.replace("Spam change: ","")
kr.sendText(msg.to,"spam changed")
elif "Spam add: " in msg.text:
wait["spam"] = msg.text.replace("Spam add: ","")
if wait["lang"] == "JP":
kr.sendText(msg.to,"spam changed")
else:
kr.sendText(msg.to,"Done")
elif "Spam: " in msg.text:
strnum = msg.text.replace("Spam: ","")
num = int(strnum)
for var in range(0,num):
kr.sendText(msg.to, wait["spam"])
elif "Spamtag @" in msg.text:
_name = msg.text.replace("Spamtag @","")
_nametarget = _name.rstrip(' ')
gs = kr.getGroup(msg.to)
for g in gs.members:
if _nametarget == g.displayName:
xname = g.displayName
xlen = str(len(xname)+1)
msg.contentType = 0
msg.text = "@"+xname+" "
msg.contentMetadata ={'MENTION':'{"MENTIONEES":[{"S":"0","E":'+json.dumps(xlen)+',"M":'+json.dumps(g.mid)+'}]}','EMTVER':'4'}
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
else:
pass
elif "Spam" in msg.text:
txt = msg.text.split(" ")
jmlh = int(txt[2])
teks = msg.text.replace("Spam "+str(txt[1])+" "+str(jmlh)+" ","")
tulisan = jmlh * (teks+"\n")
if txt[1] == "on":
if jmlh <= 100000:
for x in range(jmlh):
kr.sendText(msg.to, teks)
else:
kr.sendText(msg.to, "Out of Range!")
elif txt[1] == "off":
if jmlh <= 100000:
kr.sendText(msg.to, tulisan)
else:
kr.sendText(msg.to, "Out Of Range!")
elif ("Micadd " in msg.text):
targets = []
key = eval(msg.contentMetadata["MENTION"])
key["MENTIONEES"][0]["M"]
for x in key["MENTIONEES"]:
targets.append(x["M"])
for target in targets:
try:
mimic["target"][target] = True
kr.sendText(msg.to,"Target ditambahkan!")
break
except:
kr.sendText(msg.to,"Fail !")
break
elif ("Micdel " in msg.text):
targets = []
key = eval(msg.contentMetadata["MENTION"])
key["MENTIONEES"][0]["M"]
for x in key["MENTIONEES"]:
targets.append(x["M"])
for target in targets:
try:
del mimic["target"][target]
kr.sendText(msg.to,"Target dihapuskan!")
break
except:
kr.sendText(msg.to,"Fail !")
break
elif msg.text in ["Miclist"]:
if mimic["target"] == {}:
kr.sendText(msg.to,"nothing")
else:
mc = "Target mimic user\n"
for mi_d in mimic["target"]:
mc += "?? "+kr.getContact(mi_d).displayName + "\n"
kr.sendText(msg.to,mc)
elif "Mimic target " in msg.text:
if mimic["copy"] == True:
siapa = msg.text.replace("Mimic target ","")
if siapa.rstrip(' ') == "me":
mimic["copy2"] = "me"
kr.sendText(msg.to,"Mimic change to me")
elif siapa.rstrip(' ') == "target":
mimic["copy2"] = "target"
kr.sendText(msg.to,"Mimic change to target")
else:
kr.sendText(msg.to,"I dont know")
elif "Mimic " in msg.text:
cmd = msg.text.replace("Mimic ","")
if cmd == "on":
if mimic["status"] == False:
mimic["status"] = True
kr.sendText(msg.to,"Reply Message on")
else:
kr.sendText(msg.to,"Sudah on")
elif cmd == "off":
if mimic["status"] == True:
mimic["status"] = False
kr.sendText(msg.to,"Reply Message off")
else:
kr.sendText(msg.to,"Sudah off")
elif "Setimage: " in msg.text:
wait["pap"] = msg.text.replace("Setimage: ","")
kr.sendText(msg.to, "Pap telah di Set")
elif msg.text in ["Papimage","Papim","Pap"]:
kr.sendImageWithURL(msg.to,wait["pap"])
elif "Setvideo: " in msg.text:
wait["pap"] = msg.text.replace("Setvideo: ","")
kr.sendText(msg.to,"Video Has Ben Set To")
elif msg.text in ["Papvideo","Papvid"]:
kr.sendVideoWithURL(msg.to,wait["pap"])
elif "TL:" in msg.text:
if msg.toType == 2:
tl_text = msg.text.replace("TL:","")
kr.sendText(msg.to,"line://home/post?userMid="+mid+"&postId="+kr.new_post(tl_text)["result"]["post"]["postInfo"]["postId"])
#==============================================================================#
elif msg.text.lower() == 'mymid':
kr.sendText(msg.to,mid)
elif "Timeline: " in msg.text:
tl_text = msg.text.replace("Timeline: ","")
kr.sendText(msg.to,"line://home/post?userMid="+mid+"&postId="+kr.new_post(tl_text)["result"]["post"]["postInfo"]["postId"])
elif "Myname: " in msg.text:
string = msg.text.replace("Myname: ","")
if len(string.decode('utf-8')) <= 10000000000:
profile = kr.getProfile()
profile.displayName = string
kr.updateProfile(profile)
kr.sendText(msg.to,"Changed " + string + "")
elif "Mybio: " in msg.text:
string = msg.text.replace("Mybio: ","")
if len(string.decode('utf-8')) <= 10000000000:
profile = kr.getProfile()
profile.statusMessage = string
kr.updateProfile(profile)
kr.sendText(msg.to,"Changed " + string)
elif msg.text in ["Myname"]:
h = kr.getContact(mid)
kr.sendText(msg.to,"===[DisplayName]===\n" + h.displayName)
elif msg.text in ["Mybio"]:
h = kr.getContact(mid)
kr.sendText(msg.to,"===[StatusMessage]===\n" + h.statusMessage)
elif msg.text in ["Mypict"]:
h = kr.getContact(mid)
kr.sendImageWithURL(msg.to,"http://dl.profile.line-cdn.net/" + h.pictureStatus)
elif msg.text in ["Myvid"]:
h = kr.getContact(mid)
kr.sendVideoWithURL(msg.to,"http://dl.profile.line-cdn.net/" + h.pictureStatus)
elif msg.text in ["Urlpict"]:
h = kr.getContact(mid)
kr.sendText(msg.to,"http://dl.profile.line-cdn.net/" + h.pictureStatus)
elif msg.text in ["Mycover"]:
h = kr.getContact(mid)
cu = kr.channel.getCover(mid)
path = str(cu)
kr.sendImageWithURL(msg.to, path)
elif msg.text in ["Urlcover"]:
h = kr.getContact(mid)
cu = kr.channel.getCover(mid)
path = str(cu)
kr.sendText(msg.to, path)
elif "Getmid @" in msg.text:
_name = msg.text.replace("Getmid @","")
_nametarget = _name.rstrip(' ')
gs = kr.getGroup(msg.to)
for g in gs.members:
if _nametarget == g.displayName:
kr.sendText(msg.to, g.mid)
else:
pass
elif "Getinfo" in msg.text:
key = eval(msg.contentMetadata["MENTION"])
key1 = key["MENTIONEES"][0]["M"]
contact = kr.getContact(key1)
cu = kr.channel.getCover(key1)
try:
kr.sendText(msg.to,"Nama :\n" + contact.displayName + "\n\nMid :\n" + contact.mid + "\n\nBio :\n" + contact.statusMessage + "\n\nProfile Picture :\nhttp://dl.profile.line-cdn.net/" + contact.pictureStatus + "\n\nHeader :\n" + str(cu))
except:
kr.sendText(msg.to,"Nama :\n" + contact.displayName + "\n\nMid :\n" + contact.mid + "\n\nBio :\n" + contact.statusMessage + "\n\nProfile Picture :\n" + str(cu))
elif "Getbio" in msg.text:
key = eval(msg.contentMetadata["MENTION"])
key1 = key["MENTIONEES"][0]["M"]
contact = kr.getContact(key1)
cu = kr.channel.getCover(key1)
try:
kr.sendText(msg.to, "===[StatusMessage]===\n" + contact.statusMessage)
except:
kr.sendText(msg.to, "===[StatusMessage]===\n" + contact.statusMessage)
elif "Getname" in msg.text:
key = eval(msg.contentMetadata["MENTION"])
key1 = key["MENTIONEES"][0]["M"]
contact = kr.getContact(key1)
cu = kr.channel.getCover(key1)
try:
kr.sendText(msg.to, "===[DisplayName]===\n" + contact.displayName)
except:
kr.sendText(msg.to, "===[DisplayName]===\n" + contact.displayName)
elif "Getprofile" in msg.text:
key = eval(msg.contentMetadata["MENTION"])
key1 = key["MENTIONEES"][0]["M"]
contact = kr.getContact(key1)
cu = kr.channel.getCover(key1)
path = str(cu)
image = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
try:
kr.sendText(msg.to,"Nama :\n" + contact.displayName + "\n\nBio :\n" + contact.statusMessage)
kr.sendText(msg.to,"Profile Picture " + contact.displayName)
kr.sendImageWithURL(msg.to,image)
kr.sendText(msg.to,"Cover " + contact.displayName)
kr.sendImageWithURL(msg.to,path)
except:
pass
elif "Getcontact" in msg.text:
key = eval(msg.contentMetadata["MENTION"])
key1 = key["MENTIONEES"][0]["M"]
mmid = kr.getContact(key1)
msg.contentType = 13
msg.contentMetadata = {"mid": key1}
kr.sendMessage(msg)
elif "Getpict @" in msg.text:
print "[Command]dp executing"
_name = msg.text.replace("Getpict @","")
_nametarget = _name.rstrip(' ')
gs = kr.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
kr.sendText(msg.to,"Contact not found")
else:
for target in targets:
try:
contact = kr.getContact(target)
path = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
kr.sendImageWithURL(msg.to, path)
except Exception as e:
raise e
print "[Command]dp executed"
elif "Getvid @" in msg.text:
print "[Command]dp executing"
_name = msg.text.replace("Getvid @","")
_nametarget = _name.rstrip(' ')
gs = kr.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
kr.sendText(msg.to,"Contact not found")
else:
for target in targets:
try:
contact = kr.getContact(target)
path = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
kr.sendVideoWithURL(msg.to, path)
except Exception as e:
raise e
print "[Command]dp executed"
elif "Picturl @" in msg.text:
print "[Command]dp executing"
_name = msg.text.replace("Picturl @","")
_nametarget = _name.rstrip(' ')
gs = kr.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
kr.sendText(msg.to,"Contact not found")
else:
for target in targets:
try:
contact = kr.getContact(target)
path = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
kr.sendText(msg.to, path)
except Exception as e:
raise e
print "[Command]dp executed"
elif "Getcover @" in msg.text:
print "[Command]cover executing"
_name = msg.text.replace("Getcover @","")
_nametarget = _name.rstrip(' ')
gs = kr.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
kr.sendText(msg.to,"Contact not found")
else:
for target in targets:
try:
contact = kr.getContact(target)
cu = kr.channel.getCover(target)
path = str(cu)
kr.sendImageWithURL(msg.to, path)
except Exception as e:
raise e
print "[Command]cover executed"
elif "Coverurl @" in msg.text:
print "[Command]cover executing"
_name = msg.text.replace("Coverurl @","")
_nametarget = _name.rstrip(' ')
gs = kr.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
kr.sendText(msg.to,"Contact not found")
else:
for target in targets:
try:
contact = kr.getContact(target)
cu = kr.channel.getCover(target)
path = str(cu)
kr.sendText(msg.to, path)
except Exception as e:
raise e
print "[Command]cover executed"
elif "Getgrup image" in msg.text:
group = kr.getGroup(msg.to)
path = "http://dl.profile.line-cdn.net/" + group.pictureStatus
kr.sendImageWithURL(msg.to,path)
elif "Urlgrup image" in msg.text:
group = kr.getGroup(msg.to)
path = "http://dl.profile.line-cdn.net/" + group.pictureStatus
kr.sendText(msg.to,path)
elif "Mycopy @" in msg.text:
print "[COPY] Ok"
_name = msg.text.replace("Mycopy @","")
_nametarget = _name.rstrip(' ')
gs = kr.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
kr.sendText(msg.to, "Not Found...")
else:
for target in targets:
try:
kr.CloneContactProfile(target)
kr.sendText(msg.to, "Copied.")
except Exception as e:
print e
elif msg.text in ["Mybackup","mybackup"]:
try:
kr.updateDisplayPicture(backup.pictureStatus)
kr.updateProfile(backup)
kr.sendText(msg.to, "Refreshed.")
except Exception as e:
kr.sendText(msg.to, str(e))
#==============================================================================#
elif "Fancytext: " in msg.text:
txt = msg.text.replace("Fancytext: ", "")
kr.kedapkedip(msg.to,txt)
print "[Command] Kedapkedip"
elif "Translate-id " in msg.text:
isi = msg.text.replace("Tr-id ","")
translator = Translator()
hasil = translator.translate(isi, dest='id')
A = hasil.text
A = A.encode('utf-8')
kr.sendText(msg.to, A)
elif "Translate-en " in msg.text:
isi = msg.text.replace("Tr-en ","")
translator = Translator()
hasil = translator.translate(isi, dest='en')
A = hasil.text
A = A.encode('utf-8')
kr.sendText(msg.to, A)
elif "Translate-ar" in msg.text:
isi = msg.text.replace("Tr-ar ","")
translator = Translator()
hasil = translator.translate(isi, dest='ar')
A = hasil.text
A = A.encode('utf-8')
kr.sendText(msg.to, A)
elif "Translate-jp" in msg.text:
isi = msg.text.replace("Tr-jp ","")
translator = Translator()
hasil = translator.translate(isi, dest='ja')
A = hasil.text
A = A.encode('utf-8')
kr.sendText(msg.to, A)
elif "Translate-ko" in msg.text:
isi = msg.text.replace("Tr-ko ","")
translator = Translator()
hasil = translator.translate(isi, dest='ko')
A = hasil.text
A = A.encode('utf-8')
kr.sendText(msg.to, A)
elif "Id@en" in msg.text:
bahasa_awal = 'id'
bahasa_tujuan = 'en'
kata = msg.text.replace("Id@en ","")
url = 'https://translate.google.com/m?sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s' % (bahasa_awal, bahasa_tujuan, kata.replace(" ", "+"))
agent = {'User-Agent':'Mozilla/5.0'}
cari_hasil = 'class="t0">'
request = urllib2.Request(url, headers=agent)
page = urllib2.urlopen(request).read()
result = page[page.find(cari_hasil)+len(cari_hasil):]
result = result.split("<")[0]
kr.sendText(msg.to,"**FROM ID**\n" + "" + kata + "\n**TO ENGLISH**\n" + "" + result + "\n**SUKSES**")
elif "En@id" in msg.text:
bahasa_awal = 'en'
bahasa_tujuan = 'id'
kata = msg.text.replace("En@id ","")
url = 'https://translate.google.com/m?sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s' % (bahasa_awal, bahasa_tujuan, kata.replace(" ", "+"))
agent = {'User-Agent':'Mozilla/5.0'}
cari_hasil = 'class="t0">'
request = urllib2.Request(url, headers=agent)
page = urllib2.urlopen(request).read()
result = page[page.find(cari_hasil)+len(cari_hasil):]
result = result.split("<")[0]
kr.sendText(msg.to,"**FROM EN**\n" + "" + kata + "\n**TO ID**\n" + "" + result + "\n**SUKSES**")
elif "Id@jp" in msg.text:
bahasa_awal = 'id'
bahasa_tujuan = 'ja'
kata = msg.text.replace("Id@jp ","")
url = 'https://translate.google.com/m?sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s' % (bahasa_awal, bahasa_tujuan, kata.replace(" ", "+"))
agent = {'User-Agent':'Mozilla/5.0'}
cari_hasil = 'class="t0">'
request = urllib2.Request(url, headers=agent)
page = urllib2.urlopen(request).read()
result = page[page.find(cari_hasil)+len(cari_hasil):]
result = result.split("<")[0]
kr.sendText(msg.to,"**FROM ID**\n" + "" + kata + "\n**TO JP**\n" + "" + result + "\n**SUKSES**")
elif "Jp@id" in msg.text:
bahasa_awal = 'ja'
bahasa_tujuan = 'id'
kata = msg.text.replace("Jp@id ","")
url = 'https://translate.google.com/m?sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s' % (bahasa_awal, bahasa_tujuan, kata.replace(" ", "+"))
agent = {'User-Agent':'Mozilla/5.0'}
cari_hasil = 'class="t0">'
request = urllib2.Request(url, headers=agent)
page = urllib2.urlopen(request).read()
result = page[page.find(cari_hasil)+len(cari_hasil):]
result = result.split("<")[0]
kr.sendText(msg.to,"----FROM JP----\n" + "" + kata + "\n----TO ID----\n" + "" + result + "\n------SUKSES-----")
elif "Id@th" in msg.text:
bahasa_awal = 'id'
bahasa_tujuan = 'th'
kata = msg.text.replace("Id@th ","")
url = 'https://translate.google.com/m?sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s' % (bahasa_awal, bahasa_tujuan, kata.replace(" ", "+"))
agent = {'User-Agent':'Mozilla/5.0'}
cari_hasil = 'class="t0">'
request = urllib2.Request(url, headers=agent)
page = urllib2.urlopen(request).read()
result = page[page.find(cari_hasil)+len(cari_hasil):]
result = result.split("<")[0]
kr.sendText(msg.to,"----FROM ID----\n" + "" + kata + "\n----TO TH----\n" + "" + result + "\n------SUKSES-----")
elif "Th@id" in msg.text:
bahasa_awal = 'th'
bahasa_tujuan = 'id'
kata = msg.text.replace("Th@id ","")
url = 'https://translate.google.com/m?sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s' % (bahasa_awal, bahasa_tujuan, kata.replace(" ", "+"))
agent = {'User-Agent':'Mozilla/5.0'}
cari_hasil = 'class="t0">'
request = urllib2.Request(url, headers=agent)
page = urllib2.urlopen(request).read()
result = page[page.find(cari_hasil)+len(cari_hasil):]
result = result.split("<")[0]
kr.sendText(msg.to,"----FROM TH----\n" + "" + kata + "\n----TO ID----\n" + "" + result + "\n------SUKSES-----")
elif "Id@jp" in msg.text:
bahasa_awal = 'id'
bahasa_tujuan = 'ja'
kata = msg.text.replace("Id@jp ","")
url = 'https://translate.google.com/m?sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s' % (bahasa_awal, bahasa_tujuan, kata.replace(" ", "+"))
agent = {'User-Agent':'Mozilla/5.0'}
cari_hasil = 'class="t0">'
request = urllib2.Request(url, headers=agent)
page = urllib2.urlopen(request).read()
result = page[page.find(cari_hasil)+len(cari_hasil):]
result = result.split("<")[0]
kr.sendText(msg.to,"----FROM ID----\n" + "" + kata + "\n----TO JP----\n" + "" + result + "\n------SUKSES-----")
elif "Id@ar" in msg.text:
bahasa_awal = 'id'
bahasa_tujuan = 'ar'
kata = msg.text.replace("Id@ar ","")
url = 'https://translate.google.com/m?sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s' % (bahasa_awal, bahasa_tujuan, kata.replace(" ", "+"))
agent = {'User-Agent':'Mozilla/5.0'}
cari_hasil = 'class="t0">'
request = urllib2.Request(url, headers=agent)
page = urllib2.urlopen(request).read()
result = page[page.find(cari_hasil)+len(cari_hasil):]
result = result.split("<")[0]
kr.sendText(msg.to,"----FROM ID----\n" + "" + kata + "\n----TO AR----\n" + "" + result + "\n------SUKSES-----")
elif "Ar@id" in msg.text:
bahasa_awal = 'ar'
bahasa_tujuan = 'id'
kata = msg.text.replace("Ar@id ","")
url = 'https://translate.google.com/m?sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s' % (bahasa_awal, bahasa_tujuan, kata.replace(" ", "+"))
agent = {'User-Agent':'Mozilla/5.0'}
cari_hasil = 'class="t0">'
request = urllib2.Request(url, headers=agent)
page = urllib2.urlopen(request).read()
result = page[page.find(cari_hasil)+len(cari_hasil):]
result = result.split("<")[0]
kr.sendText(msg.to,"----FROM AR----\n" + "" + kata + "\n----TO ID----\n" + "" + result + "\n------SUKSES-----")
elif "Id@ko" in msg.text:
bahasa_awal = 'id'
bahasa_tujuan = 'ko'
kata = msg.text.replace("Id@ko ","")
url = 'https://translate.google.com/m?sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s' % (bahasa_awal, bahasa_tujuan, kata.replace(" ", "+"))
agent = {'User-Agent':'Mozilla/5.0'}
cari_hasil = 'class="t0">'
request = urllib2.Request(url, headers=agent)
page = urllib2.urlopen(request).read()
result = page[page.find(cari_hasil)+len(cari_hasil):]
result = result.split("<")[0]
kr.sendText(msg.to,"----FROM ID----\n" + "" + kata + "\n----TO KO----\n" + "" + result + "\n------SUKSES-----")
elif "Ko@id" in msg.text:
bahasa_awal = 'ko'
bahasa_tujuan = 'id'
kata = msg.text.replace("Ko@id ","")
url = 'https://translate.google.com/m?sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s' % (bahasa_awal, bahasa_tujuan, kata.replace(" ", "+"))
agent = {'User-Agent':'Mozilla/5.0'}
cari_hasil = 'class="t0">'
request = urllib2.Request(url, headers=agent)
page = urllib2.urlopen(request).read()
result = page[page.find(cari_hasil)+len(cari_hasil):]
result = result.split("<")[0]
kr.sendText(msg.to,"----FROM KO----\n" + "" + kata + "\n----TO ID----\n" + "" + result + "\n------SUKSES-----")
elif msg.text.lower() == 'welcome':
ginfo = kr.getGroup(msg.to)
kr.sendText(msg.to,"Selamat Datang Di Grup " + str(ginfo.name))
jawaban1 = ("Selamat Datang Di Grup " + str(ginfo.name))
kr.sendText(msg.to,"Owner Grup " + str(ginfo.name) + " :\n" + ginfo.creator.displayName )
tts = gTTS(text=jawaban1, lang='id')
tts.save('tts.mp3')
kr.sendAudio(msg.to,'tts.mp3')
elif "Say-id " in msg.text:
say = msg.text.replace("Say-id ","")
lang = 'id'
tts = gTTS(text=say, lang=lang)
tts.save("hasil.mp3")
kr.sendAudio(msg.to,"hasil.mp3")
elif "Say-en " in msg.text:
say = msg.text.replace("Say-en ","")
lang = 'en'
tts = gTTS(text=say, lang=lang)
tts.save("hasil.mp3")
kr.sendAudio(msg.to,"hasil.mp3")
elif "Say-jp " in msg.text:
say = msg.text.replace("Say-jp ","")
lang = 'ja'
tts = gTTS(text=say, lang=lang)
tts.save("hasil.mp3")
kr.sendAudio(msg.to,"hasil.mp3")
elif "Say-ar " in msg.text:
say = msg.text.replace("Say-ar ","")
lang = 'ar'
tts = gTTS(text=say, lang=lang)
tts.save("hasil.mp3")
kr.sendAudio(msg.to,"hasil.mp3")
elif "Say-ko " in msg.text:
say = msg.text.replace("Say-ko ","")
lang = 'ko'
tts = gTTS(text=say, lang=lang)
tts.save("hasil.mp3")
kr.sendAudio(msg.to,"hasil.mp3")
elif "Kapan " in msg.text:
tanya = msg.text.replace("Kapan ","")
jawab = ("kapan kapan","besok","satu abad lagi","Hari ini","Tahun depan","Minggu depan","Bulan depan","Sebentar lagi")
jawaban = random.choice(jawab)
tts = gTTS(text=jawaban, lang='id')
tts.save('tts.mp3')
kr.sendAudio(msg.to,'tts.mp3')
elif "Apakah " in msg.text:
tanya = msg.text.replace("Apakah ","")
jawab = ("Ya","Tidak","Mungkin","Bisa jadi")
jawaban = random.choice(jawab)
tts = gTTS(text=jawaban, lang='id')
tts.save('tts.mp3')
kr.sendAudio(msg.to,'tts.mp3')
elif 'Youtubemp4 ' in msg.text:
try:
textToSearch = (msg.text).replace('Youtubemp4 ', "").strip()
query = urllib.quote(textToSearch)
url = "https://www.youtube.com/results?search_query=" + query
response = urllib2.urlopen(url)
html = response.read()
soup = BeautifulSoup(html, "html.parser")
results = soup.find(attrs={'class': 'yt-uix-tile-link'})
ght = ('https://www.youtube.com' + results['href'])
kr.sendVideoWithURL(msg.to, ght)
except:
kr.sendText(msg.to, "Could not find it")
elif "Youtubesearch " in msg.text:
query = msg.text.replace("Youtube ","")
with requests.session() as s:
s.headers['user-agent'] = 'Mozilla/5.0'
url = 'http://www.youtube.com/results'
params = {'search_query': query}
r = s.get(url, params=params)
soup = BeautifulSoup(r.content, 'html5lib')
hasil = ""
for a in soup.select('.yt-lockup-title > a[title]'):
if '&list=' not in a['href']:
hasil += ''.join((a['title'],'\nUrl : http://www.youtube.com' + a['href'],'\n\n'))
kr.sendText(msg.to,hasil)
print '[Command] Youtube Search'
elif "Lirik " in msg.text:
try:
songname = msg.text.lower().replace("Lirik ","")
params = {'songname': songname}
r = requests.get('http://ide.fdlrcn.com/workspace/yumi-apis/joox?' + urllib.urlencode(params))
data = r.text
data = json.loads(data)
for song in data:
hasil = 'Lyric Lagu ('
hasil += song[0]
hasil += ')\n\n'
hasil += song[5]
kr.sendText(msg.to, hasil)
except Exception as wak:
kr.sendText(msg.to, str(wak))
elif "Wikipedia " in msg.text:
try:
wiki = msg.text.lower().replace("Wikipedia ","")
wikipedia.set_lang("id")
pesan="Title ("
pesan+=wikipedia.page(wiki).title
pesan+=")\n\n"
pesan+=wikipedia.summary(wiki, sentences=1)
pesan+="\n"
pesan+=wikipedia.page(wiki).url
kr.sendText(msg.to, pesan)
except:
try:
pesan="Over Text Limit! Please Click link\n"
pesan+=wikipedia.page(wiki).url
kr.sendText(msg.to, pesan)
except Exception as e:
kr.sendText(msg.to, str(e))
elif "Music " in msg.text:
try:
songname = msg.text.lower().replace("Music ","")
params = {'songname': songname}
r = requests.get('http://ide.fdlrcn.com/workspace/yumi-apis/joox?' + urllib.urlencode(params))
data = r.text
data = json.loads(data)
for song in data:
hasil = 'This is Your Music\n'
hasil += 'Judul : ' + song[0]
hasil += '\nDurasi : ' + song[1]
hasil += '\nLink Download : ' + song[4]
kr.sendText(msg.to, hasil)
kr.sendText(msg.to, "Please Wait for audio...")
kr.sendAudioWithURL(msg.to, song[4])
except Exception as njer:
kr.sendText(msg.to, str(njer))
elif "Image " in msg.text:
search = msg.text.replace("Image ","")
url = 'https://www.google.com/search?espv=2&biw=1366&bih=667&tbm=isch&oq=kuc&aqs=mobile-gws-lite.0.0l5&q=' + search
raw_html = (download_page(url))
items = []
items = items + (_images_get_all_items(raw_html))
path = random.choice(items)
print path
try:
kr.sendImageWithURL(msg.to,path)
except:
pass
elif "Profileig " in msg.text:
try:
instagram = msg.text.replace("Profileig ","")
response = requests.get("https://www.instagram.com/"+instagram+"?__a=1")
data = response.json()
namaIG = str(data['user']['full_name'])
bioIG = str(data['user']['biography'])
mediaIG = str(data['user']['media']['count'])
verifIG = str(data['user']['is_verified'])
usernameIG = str(data['user']['username'])
followerIG = str(data['user']['followed_by']['count'])
profileIG = data['user']['profile_pic_url_hd']
privateIG = str(data['user']['is_private'])
followIG = str(data['user']['follows']['count'])
link = "Link: " + "https://www.instagram.com/" + instagram
text = "Name : "+namaIG+"\nUsername : "+usernameIG+"\nBiography : "+bioIG+"\nFollower : "+followerIG+"\nFollowing : "+followIG+"\nPost : "+mediaIG+"\nVerified : "+verifIG+"\nPrivate : "+privateIG+"" "\n" + link
kr.sendImageWithURL(msg.to, profileIG)
kr.sendText(msg.to, str(text))
except Exception as e:
kr.sendText(msg.to, str(e))
elif "Checkdate " in msg.text:
tanggal = msg.text.replace("Checkdate ","")
r=requests.get('https://script.google.com/macros/exec?service=AKfycbw7gKzP-WYV2F5mc9RaR7yE3Ve1yN91Tjs91hp_jHSE02dSv9w&nama=ervan&tanggal='+tanggal)
data=r.text
data=json.loads(data)
lahir = data["data"]["lahir"]
usia = data["data"]["usia"]
ultah = data["data"]["ultah"]
zodiak = data["data"]["zodiak"]
kr.sendText(msg.to,"============ I N F O R M A S I ============\n"+"Date Of Birth : "+lahir+"\nAge : "+usia+"\nUltah : "+ultah+"\nZodiak : "+zodiak+"\n============ I N F O R M A S I ============")
elif msg.text in ["Kalender","Time","Waktu"]:
timeNow = datetime.now()
timeHours = datetime.strftime(timeNow,"(%H:%M)")
day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"]
hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"]
bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"]
inihari = datetime.today()
hr = inihari.strftime('%A')
bln = inihari.strftime('%m')
for i in range(len(day)):
if hr == day[i]: hasil = hari[i]
for k in range(0, len(bulan)):
if bln == str(k): bln = bulan[k-1]
rst = hasil + ", " + inihari.strftime('%d') + " - " + bln + " - " + inihari.strftime('%Y') + "\nJam : [ " + inihari.strftime('%H:%M:%S') + " ]"
kr.sendText(msg.to, rst)
#==============================================================================#
elif msg.text.lower() == 'ifconfig':
botKernel = subprocess.Popen(["ifconfig"], stdout=subprocess.PIPE).communicate()[0]
kr.sendText(msg.to, botKernel + "\n\n===SERVER INFO NetStat===")
elif msg.text.lower() == 'system':
botKernel = subprocess.Popen(["df","-h"], stdout=subprocess.PIPE).communicate()[0]
kr.sendText(msg.to, botKernel + "\n\n===SERVER INFO SYSTEM===")
elif msg.text.lower() == 'kernel':
botKernel = subprocess.Popen(["uname","-srvmpio"], stdout=subprocess.PIPE).communicate()[0]
kr.sendText(msg.to, botKernel + "\n\n===SERVER INFO KERNEL===")
elif msg.text.lower() == 'cpu':
botKernel = subprocess.Popen(["cat","/proc/cpuinfo"], stdout=subprocess.PIPE).communicate()[0]
kr.sendText(msg.to, botKernel + "\n\n===SERVER INFO CPU===")
elif "Restart" in msg.text:
print "[Command]Restart"
try:
kr.sendText(msg.to,"Restarting...")
kr.sendText(msg.to,"Restart Success")
restart_program()
except:
kr.sendText(msg.to,"Please wait")
restart_program()
pass
elif "Turn off" in msg.text:
try:
import sys
sys.exit()
except:
pass
elif msg.text.lower() == 'runtime':
eltime = time.time() - mulai
van = "Bot has been active "+waktu(eltime)
kr.sendText(msg.to,van)
#================================ KRIS SCRIPT STARTED ==============================================#
elif "google " in msg.text:
a = msg.text.replace("google ","")
b = urllib.quote(a)
kr.sendText(msg.to,"Sedang Mencari om...")
kr.sendText(msg.to, "https://www.google.com/" + b)
kr.sendText(msg.to,"Ketemu om ^")
elif cms(msg.text,["/creator","Creator"]):
msg.contentType = 13
msg.contentMetadata = {'mid': "ub14f769cdf42d8c8a618ebe91ac2c8c7"}
kr.sendMessage(msg)
elif "friendpp: " in msg.text:
if msg.from_ in admin:
suf = msg.text.replace('friendpp: ','')
gid = kr.getAllContactIds()
for i in gid:
h = kr.getContact(i).displayName
gna = kr.getContact(i)
if h == suf:
kr.sendImageWithURL(msg.to,"http://dl.profile.line.naver.jp/"+ gna.pictureStatus)
elif "Checkmid: " in msg.text:
saya = msg.text.replace("Checkmid: ","")
msg.contentType = 13
msg.contentMetadata = {"mid":saya}
kr.sendMessage(msg)
contact = kr.getContact(saya)
cu = kr.channel.getCover(saya)
path = str(cu)
image = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
try:
kr.sendText(msg.to,"Nama :\n" + contact.displayName + "\n\nBio :\n" + contact.statusMessage)
kr.sendText(msg.to,"Profile Picture " + contact.displayName)
kr.sendImageWithURL(msg.to,image)
kr.sendText(msg.to,"Cover " + contact.displayName)
kr.sendImageWithURL(msg.to,path)
except:
pass
elif "Checkid: " in msg.text:
saya = msg.text.replace("Checkid: ","")
gid = kr.getGroupIdsJoined()
for i in gid:
h = kr.getGroup(i).id
group = kr.getGroup(i)
if h == saya:
try:
creator = group.creator.mid
msg.contentType = 13
msg.contentMetadata = {'mid': creator}
md = "Nama Grup :\n" + group.name + "\n\nID Grup :\n" + group.id
if group.preventJoinByTicket is False: md += "\n\nKode Url : Diizinkan"
else: md += "\n\nKode Url : Diblokir"
if group.invitee is None: md += "\nJumlah Member : " + str(len(group.members)) + " Orang" + "\nUndangan Yang Belum Diterima : 0 Orang"
else: md += "\nJumlah Member : " + str(len(group.members)) + " Orang" + "\nUndangan Yang Belum Diterima : " + str(len(group.invitee)) + " Orang"
kr.sendText(msg.to,md)
kr.sendMessage(msg)
kr.sendImageWithURL(msg.to,"http://dl.profile.line.naver.jp/"+ group.pictureStatus)
except:
creator = "Error"
elif msg.text in ["Friendlist"]:
contactlist = kr.getAllContactIds()
kontak = kr.getContacts(contactlist)
num=1
msgs="โโโโโโโโโList Friendโโโโโโโโโ"
for ids in kontak:
msgs+="\n[%i] %s" % (num, ids.displayName)
num=(num+1)
msgs+="\nโโโโโโโโโList Friendโโโโโโโโโ\n\nTotal Friend : %i" % len(kontak)
kr.sendText(msg.to, msgs)
elif msg.text in ["Memlist"]:
kontak = kr.getGroup(msg.to)
group = kontak.members
num=1
msgs="โโโโโโโโโList Memberโโโโโโโโโ-"
for ids in group:
msgs+="\n[%i] %s" % (num, ids.displayName)
num=(num+1)
msgs+="\nโโโโโโโโโList Memberโโโโโโโโโ\n\nTotal Members : %i" % len(group)
kr.sendText(msg.to, msgs)
elif "Friendinfo: " in msg.text:
saya = msg.text.replace('Friendinfo: ','')
gid = kr.getAllContactIds()
for i in gid:
h = kr.getContact(i).displayName
contact = kr.getContact(i)
cu = kr.channel.getCover(i)
path = str(cu)
image = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
if h == saya:
kr.sendText(msg.to,"Nama :\n" + contact.displayName + "\n\nBio :\n" + contact.statusMessage)
kr.sendText(msg.to,"Profile Picture " + contact.displayName)
kr.sendImageWithURL(msg.to,image)
kr.sendText(msg.to,"Cover " + contact.displayName)
kr.sendImageWithURL(msg.to,path)
elif "Friendpict: " in msg.text:
saya = msg.text.replace('Friendpict: ','')
gid = kr.getAllContactIds()
for i in gid:
h = kr.getContact(i).displayName
gna = kr.getContact(i)
if h == saya:
kr.sendImageWithURL(msg.to,"http://dl.profile.line.naver.jp/"+ gna.pictureStatus)
elif msg.text in ["Friendlistmid"]:
gruplist = kr.getAllContactIds()
kontak = kr.getContacts(gruplist)
num=1
msgs="โโโโโโโโโสฮฏฯฯฏ ฦษพฮฏฮตฮทฮดสฮฏฮดโโโโโโโโโ"
for ids in kontak:
msgs+="\n[%i] %s" % (num, ids.mid)
num=(num+1)
msgs+="\nโโโโโโโโโสฮฏฯฯฏ ฦษพฮฏฮตฮทฮดสฮฏฮดโโโโโโโโโ\n\nTotal Friend : %i" % len(kontak)
kr.sendText(msg.to, msgs)
elif msg.text in ["Blocklist"]:
blockedlist = kr.getBlockedContactIds()
kontak = kr.getContacts(blockedlist)
num=1
msgs="โโโโโโโโโList Blockedโโโโโโโโโ"
for ids in kontak:
msgs+="\n[%i] %s" % (num, ids.displayName)
num=(num+1)
msgs+="\nโโโโโโโโโList Blockedโโโโโโโโโ\n\nTotal Blocked : %i" % len(kontak)
kr.sendText(msg.to, msgs)
elif msg.text in ["Gruplist"]:
gruplist = kr.getGroupIdsJoined()
kontak = kr.getGroups(gruplist)
num=1
msgs="โโโโโโโโโList Grupโโโโโโโโโ"
for ids in kontak:
msgs+="\n[%i] %s" % (num, ids.name)
num=(num+1)
msgs+="\nโโโโโโโโโList Grupโโโโโโโโโ\n\nTotal Grup : %i" % len(kontak)
kr.sendText(msg.to, msgs)
elif msg.text in ["Gruplistmid"]:
gruplist = kr.getGroupIdsJoined()
kontak = kr.getGroups(gruplist)
num=1
msgs="โโโโโโโโโList GrupMidโโโโโโโโโ"
for ids in kontak:
msgs+="\n[%i] %s" % (num, ids.id)
num=(num+1)
msgs+="\nโโโโโโโโโList GrupMidโโโโโโโโโ\n\nTotal Grup : %i" % len(kontak)
kr.sendText(msg.to, msgs)
elif "Grupimage: " in msg.text:
saya = msg.text.replace('Grupimage: ','')
gid = kr.getGroupIdsJoined()
for i in gid:
h = kr.getGroup(i).name
gna = kr.getGroup(i)
if h == saya:
kr.sendImageWithURL(msg.to,"http://dl.profile.line.naver.jp/"+ gna.pictureStatus)
elif "Grupname" in msg.text:
saya = msg.text.replace('Grupname','')
gid = kr.getGroup(msg.to)
kr.sendText(msg.to, "[Nama Grup : ]\n" + gid.name)
elif "Grupid" in msg.text:
saya = msg.text.replace('Grupid','')
gid = kr.getGroup(msg.to)
kr.sendText(msg.to, "[ID Grup : ]\n" + gid.id)
elif "Grupinfo: " in msg.text:
saya = msg.text.replace('Grupinfo: ','')
gid = kr.getGroupIdsJoined()
for i in gid:
h = kr.getGroup(i).name
group = kr.getGroup(i)
if h == saya:
try:
creator = group.creator.mid
msg.contentType = 13
msg.contentMetadata = {'mid': creator}
md = "Nama Grup :\n" + group.name + "\n\nID Grup :\n" + group.id
if group.preventJoinByTicket is False: md += "\n\nKode Url : Diizinkan"
else: md += "\n\nKode Url : Diblokir"
if group.invitee is None: md += "\nJumlah Member : " + str(len(group.members)) + " Orang" + "\nUndangan Yang Belum Diterima : 0 Orang"
else: md += "\nJumlah Member : " + str(len(group.members)) + " Orang" + "\nUndangan Yang Belum Diterima : " + str(len(group.invitee)) + " Orang"
kr.sendText(msg.to,md)
kr.sendMessage(msg)
kr.sendImageWithURL(msg.to,"http://dl.profile.line.naver.jp/"+ group.pictureStatus)
except:
creator = "Error"
elif "Spamtag @" in msg.text:
_name = msg.text.replace("Spamtag @","")
_nametarget = _name.rstrip(' ')
gs = kr.getGroup(msg.to)
for g in gs.members:
if _nametarget == g.displayName:
xname = g.displayName
xlen = str(len(xname)+1)
msg.contentType = 0
msg.text = "@"+xname+" "
msg.contentMetadata ={'MENTION':'{"MENTIONEES":[{"S":"0","E":'+json.dumps(xlen)+',"M":'+json.dumps(g.mid)+'}]}','EMTVER':'4'}
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
print "Spamtag Berhasil."
elif "crashkontak @" in msg.text:
_name = msg.text.replace("crashkontak @","")
_nametarget = _name.rstrip(' ')
gs = kr.getGroup(msg.to)
for g in gs.members:
if _nametarget == g.displayName:
msg.contentType = 13
msg.contentMetadata = {'mid': "ua7fb5762d5066629323d113e1266e8ca',"}
kr.sendMessage(g.mid,msg.to + str(msg))
kr.sendText(g.mid, "hai")
kr.sendText(g.mid, "salken")
kr.sendText(msg.to, "Done")
print " Spammed crash !"
elif "playstore " in msg.text.lower():
tob = msg.text.lower().replace("playstore ","")
kr.sendText(msg.to,"Sedang Mencari boss...")
kr.sendText(msg.to,"Title : "+tob+"\nSource : Google Play\nLinknya : https://play.google.com/store/search?q=" + tob)
kr.sendText(msg.to,"Ketemu boss ^")
elif 'wikipedia ' in msg.text.lower():
try:
wiki = msg.text.lower().replace("wikipedia ","")
wikipedia.set_lang("id")
pesan="Title ("
pesan+=wikipedia.page(wiki).title
pesan+=")\n\n"
pesan+=wikipedia.summary(wiki, sentences=3)
pesan+="\n"
pesan+=wikipedia.page(wiki).url
kr.sendText(msg.to, pesan)
except:
try:
pesan="Teks nya kepanjangan! ketik link dibawah aja\n"
pesan+=wikipedia.page(wiki).url
kr.sendText(msg.to, pesan)
except Exception as e:
kr.sendText(msg.to, str(e))
elif "say " in msg.text.lower():
say = msg.text.lower().replace("say ","")
lang = 'id'
tts = gTTS(text=say, lang=lang)
tts.save("hasil.mp3")
kr.sendAudio(msg.to,"hasil.mp3")
elif msg.text in ["spam gift 25"]:
msg.contentType = 9
msg.contentMetadata={'PRDID': 'ae3d9165-fab2-4e70-859b-c14a9d4137c4',
'PRDTYPE': 'THEME',
'MSGTPL': '8'}
msg.text = None
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
elif msg.text in ["Gcreator:inv"]:
if msg.from_ in admin:
ginfo = kr.getGroup(msg.to)
gCreator = ginfo.creator.mid
try:
kr.findAndAddContactsByMid(gCreator)
kr.inviteIntoGroup(msg.to,[gCreator])
print "success inv gCreator"
except:
pass
elif msg.text in ["Gcreator:kick"]:
if msg.from_ in admin:
ginfo = kr.getGroup(msg.to)
gCreator = ginfo.creator.mid
try:
kr.findAndAddContactsByMid(gCreator)
kr.kickoutFromGroup(msg.to,[gCreator])
print "success inv gCreator"
except:
pass
elif 'lirik ' in msg.text.lower():
try:
songname = msg.text.lower().replace('lirik ','')
params = {'songname': songname}
r = requests.get('http://ide.fdlrcn.com/workspace/yumi-apis/joox?' + urllib.urlencode(params))
data = r.text
data = json.loads(data)
for song in data:
hasil = 'Lyric Lagu ('
hasil += song[0]
hasil += ')\n\n'
hasil += song[5]
kr.sendText(msg.to, hasil)
except Exception as wak:
kr.sendText(msg.to, str(wak))
elif "Getcover @" in msg.text:
print "[Command]dp executing"
_name = msg.text.replace("Getcover @","")
_nametarget = _name.rstrip(' ')
gs = kr.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
ki.sendText(msg.to,"Contact not found")
else:
for target in targets:
try:
contact = kr.getContact(target)
cu = kr.channel.getCover(target)
path = str(cu)
kr.sendImageWithURL(msg.to, path)
except:
pass
print "[Command]dp executed"
elif "idline: " in msg.text:
msgg = msg.text.replace('idline: ','')
conn = kr.findContactsByUserid(msgg)
if True:
msg.contentType = 13
msg.contentMetadata = {'mid': conn.mid}
kr.sendText(msg.to,"http://line.me/ti/p/~" + msgg)
kr.sendMessage(msg)
elif "reinvite" in msg.text.split():
if msg.toType == 2:
group = kr.getGroup(msg.to)
if group.invitee is not None:
try:
grCans = [contact.mid for contact in group.invitee]
kr.findAndAddContactByMid(msg.to, grCans)
kr.cancelGroupInvitation(msg.to, grCans)
kr.inviteIntoGroup(msg.to, grCans)
except Exception as error:
print error
else:
if wait["lang"] == "JP":
kr.sendText(msg.to,"No Invited")
else:
kr.sendText(msg.to,"Error")
else:
pass
elif msg.text.lower() == 'runtime':
eltime = time.time() - mulai
van = "Bot sudah berjalan selama "+waktu(eltime)
kr.sendText(msg.to,van)
elif msg.text in ["Restart"]:
kr.sendText(msg.to, "Bot has been restarted")
restart_program()
print "@Restart"
elif msg.text in ["time"]:
timeNow = datetime.now()
timeHours = datetime.strftime(timeNow,"(%H:%M)")
day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"]
hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"]
bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"]
inihari = datetime.today()
hr = inihari.strftime('%A')
bln = inihari.strftime('%m')
for i in range(len(day)):
if hr == day[i]: hasil = hari[i]
for k in range(0, len(bulan)):
if bln == str(k): bln = bulan[k-1]
rst = hasil + ", " + inihari.strftime('%d') + " - " + bln + " - " + inihari.strftime('%Y') + "\nJam : [ " + inihari.strftime('%H:%M:%S') + " ]"
client.sendText(msg.to, rst)
elif "image " in msg.text:
search = msg.text.replace("image ","")
url = 'https://www.google.com/search?espv=2&biw=1366&bih=667&tbm=isch&oq=kuc&aqs=mobile-gws-lite.0.0l5&q=' + search
raw_html = (download_page(url))
items = []
items = items + (_images_get_all_items(raw_html))
path = random.choice(items)
print path
try:
kr.sendImageWithURL(msg.to,path)
except:
pass
elif 'instagram ' in msg.text.lower():
try:
instagram = msg.text.lower().replace("instagram ","")
html = requests.get('https://www.instagram.com/' + instagram + '/?')
soup = BeautifulSoup(html.text, 'html5lib')
data = soup.find_all('meta', attrs={'property':'og:description'})
text = data[0].get('content').split()
data1 = soup.find_all('meta', attrs={'property':'og:image'})
text1 = data1[0].get('content').split()
user = "Name: " + text[-2] + "\n"
user1 = "Username: " + text[-1] + "\n"
followers = "Followers: " + text[0] + "\n"
following = "Following: " + text[2] + "\n"
post = "Post: " + text[4] + "\n"
link = "Link: " + "https://www.instagram.com/" + instagram
detail = "**INSTAGRAM INFO USER**\n"
details = "\n**INSTAGRAM INFO USER**"
kr.sendText(msg.to, detail + user + user1 + followers + following + post + link + details)
kr.sendImageWithURL(msg.to, text1[0])
except Exception as njer:
kr.sendText(msg.to, str(njer))
elif msg.text in ["Attack"]:
msg.contentType = 13
msg.contentMetadata = {'mid': "ua7fb5762d5066629323d113e1266e8ca',"}
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
kr.sendMessage(msg)
elif msg.text.lower() == '...':
msg.contentType = 13
msg.contentMetadata = {'mid': "ua7fb5762d5066629323d113e1266e8ca',"}
kr.sendMessage(msg)
#=================================KRIS SCRIPT FINISHED =============================================#
elif "Ban @" in msg.text:
if msg.toType == 2:
_name = msg.text.replace("Ban @","")
_nametarget = _name.rstrip()
gs = kr.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
kr.sendText(msg.to,_nametarget + " Not Found")
else:
for target in targets:
try:
wait["blacklist"][target] = True
kr.sendText(msg.to,_nametarget + " Succes Add to Blacklist")
except:
kr.sendText(msg.to,"Error")
elif "Unban @" in msg.text:
if msg.toType == 2:
_name = msg.text.replace("Unban @","")
_nametarget = _name.rstrip()
gs = kr.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
kr.sendText(msg.to,_nametarget + " Not Found")
else:
for target in targets:
try:
del wait["blacklist"][target]
kr.sendText(msg.to,_nametarget + " Delete From Blacklist")
except:
kr.sendText(msg.to,_nametarget + " Not In Blacklist")
elif "Ban:" in msg.text:
nk0 = msg.text.replace("Ban:","")
nk1 = nk0.lstrip()
nk2 = nk1.replace("","")
nk3 = nk2.rstrip()
_name = nk3
gs = kr.getGroup(msg.to)
targets = []
for s in gs.members:
if _name in s.displayName:
targets.append(s.mid)
if targets == []:
sendMessage(msg.to,"user does not exist")
pass
else:
for target in targets:
try:
wait["blacklist"][target] = True
f=codecs.open('st2__b.json','w','utf-8')
json.dump(wait["blacklist"], f, sort_keys=True, indent=4,ensure_ascii=False)
kr.sendText(msg.to,_name + " Succes Add to Blacklist")
except:
kr.sendText(msg.to,"Error")
elif "Unban:" in msg.text:
nk0 = msg.text.replace("Unban:","")
nk1 = nk0.lstrip()
nk2 = nk1.replace("","")
nk3 = nk2.rstrip()
_name = nk3
gs = kr.getGroup(msg.to)
targets = []
for s in gs.members:
if _name in s.displayName:
targets.append(s.mid)
if targets == []:
sendMessage(msg.to,"user does not exist")
pass
else:
for target in targets:
try:
del wait["blacklist"][target]
f=codecs.open('st2__b.json','w','utf-8')
json.dump(wait["blacklist"], f, sort_keys=True, indent=4,ensure_ascii=False)
kr.sendText(msg.to,_name + " Delete From Blacklist")
except:
kr.sendText(msg.to,_name + " Not In Blacklist")
elif msg.text in ["Clear"]:
wait["blacklist"] = {}
kr.sendText(msg.to,"Blacklist Telah Dibersihkan")
elif msg.text in ["Ban:on"]:
wait["wblacklist"] = True
kr.sendText(msg.to,"Send Contact")
elif msg.text in ["Unban:on"]:
wait["dblacklist"] = True
kr.sendText(msg.to,"Send Contact")
elif msg.text in ["Banlist"]:
if wait["blacklist"] == {}:
kr.sendText(msg.to,"Tidak Ada Blacklist")
else:
kr.sendText(msg.to,"Daftar Banlist")
num=1
msgs="*Blacklist*"
for mi_d in wait["blacklist"]:
msgs+="\n[%i] %s" % (num, kr.getContact(mi_d).displayName)
num=(num+1)
msgs+="\n*Blacklist*\n\nTotal Blacklist : %i" % len(wait["blacklist"])
kr.sendText(msg.to, msgs)
elif msg.text in ["Conban","Contactban","Contact ban"]:
if wait["blacklist"] == {}:
kr.sendText(msg.to,"Tidak Ada Blacklist")
else:
kr.sendText(msg.to,"Daftar Blacklist")
h = ""
for i in wait["blacklist"]:
h = kr.getContact(i)
M = Message()
M.to = msg.to
M.contentType = 13
M.contentMetadata = {'mid': i}
kr.sendMessage(M)
elif msg.text in ["Midban","Mid ban"]:
if msg.toType == 2:
group = kr.getGroup(msg.to)
gMembMids = [contact.mid for contact in group.members]
matched_list = []
for tag in wait["blacklist"]:
matched_list+=filter(lambda str: str == tag, gMembMids)
num=1
cocoa = "โโโโโโโโโโList Blacklistโโโโโโโโโ"
for mm in matched_list:
cocoa+="\n[%i] %s" % (num, mm)
num=(num+1)
cocoa+="\nโโโโโโโโโList Blacklistโโโโโโโโโ\n\nTotal Blacklist : %i" % len(matched_list)
kr.sendText(msg.to,cocoa)
elif msg.text.lower() == 'scan blacklist':
if msg.toType == 2:
group = kr.getGroup(msg.to)
gMembMids = [contact.mid for contact in group.members]
matched_list = []
for tag in wait["blacklist"]:
matched_list+=filter(lambda str: str == tag, gMembMids)
if matched_list == []:
kr.sendText(msg.to,"Tidak ada Daftar Blacklist")
return
for jj in matched_list:
try:
kr.kickoutFromGroup(msg.to,[jj])
print (msg.to,[jj])
except:
pass
#==============================================#
if op.type == 17:
if op.param2 not in Bots:
if op.param2 in Bots:
pass
if wait["protect"] == True:
if wait["blacklist"][op.param2] == True:
try:
kr.kickoutFromGroup(op.param1,[op.param2])
G = kr.getGroup(op.param1)
G.preventJoinByTicket = True
kr.updateGroup(G)
except:
try:
kr.kickoutFromGroup(op.param1,[op.param2])
G = kr.getGroup(op.param1)
G.preventJoinByTicket = True
kr.updateGroup(G)
except:
pass
if op.type == 19:
if op.param2 not in Bots:
if op.param2 in Bots:
pass
elif wait["protect"] == True:
wait ["blacklist"][op.param2] = True
kr.kickoutFromGroup(op.param1,[op.param2])
kr.inviteIntoGroup(op.param1,[op.param2])
if op.type == 13:
if op.param2 not in Bots:
if op.param2 in Bots:
pass
elif wait["inviteprotect"] == True:
wait ["blacklist"][op.param2] = True
kr.kickoutFromGroup(op.param1,[op.param2])
if op.param2 not in Bots:
if op.param2 in Bots:
pass
elif wait["inviteprotect"] == True:
wait ["blacklist"][op.param2] = True
kr.cancelGroupInvitation(op.param1,[op.param3])
if op.param2 not in Bots:
if op.param2 in Bots:
pass
elif wait["cancelprotect"] == True:
wait ["blacklist"][op.param2] = True
kr.cancelGroupInvitation(op.param1,[op.param3])
if op.type == 11:
if op.param2 not in Bots:
if op.param2 in Bots:
pass
elif wait["linkprotect"] == True:
wait ["blacklist"][op.param2] = True
G = kr.getGroup(op.param1)
G.preventJoinByTicket = True
kr.updateGroup(G)
kr.kickoutFromGroup(op.param1,[op.param2])
if op.type == 5:
if wait["autoAdd"] == True:
if (wait["message"] in [""," ","\n",None]):
pass
else:
kr.sendText(op.param1,str(wait["message"]))
if op.type == 11:
if wait["linkprotect"] == True:
if op.param2 not in Bots:
G = kr.getGroup(op.param1)
G.preventJoinByTicket = True
kr.kickoutFromGroup(op.param1,[op.param3])
kr.updateGroup(G)
if op.type == 17:
if wait["Wc"] == True:
if op.param2 in Bots:
return
ginfo = kr.getGroup(op.param1)
kr.sendText(op.param1, "โโโโโโโโโโโโโโ\nโSelamat Datang Di " + str(ginfo.name) + "\nโ โโโโโโโโโโโโโ\n" + "โFounder =>>> " + str(ginfo.name) + " :\nโ" + ginfo.creator.displayName + "\nโ โโโโโโโโโโโโโ\n" + "โ๐Semoga Betah Kak ๐ \nโโโโโโโโโโโโโโ")
print "MEMBER HAS JOIN THE GROUP"
if op.type == 15:
if wait["Lv"] == True:
if op.param2 in Bots:
return
kr.sendText(op.param1, "โโโโโโโโโโโโโโ\nโBaper Tuh Orang :v \nโSemoga Bahagia ya ๐ \nโโโโโโโโโโโโโโ")
print "MEMBER HAS LEFT THE GROUP"
#------------------------------------------------------------------------------#
if op.type == 55:
try:
if op.param1 in wait2['readPoint']:
if op.param2 in wait2['readMember'][op.param1]:
pass
else:
wait2['readMember'][op.param1] += op.param2
wait2['ROM'][op.param1][op.param2] = op.param2
with open('sider.json', 'w') as fp:
json.dump(wait2, fp, sort_keys=True, indent=4)
else:
pass
except:
pass
if op.type == 59:
print op
except Exception as error:
print error
def autolike():
count = 1
while True:
try:
for posts in kr.activity(1)["result"]["posts"]:
if posts["postInfo"]["liked"] is False:
if wait["likeOn"] == True:
kr.like(posts["userInfo"]["writerMid"], posts["postInfo"]["postId"], 1001)
print "Like"
if wait["commentOn"] == True:
if posts["userInfo"]["writerMid"] in wait["commentBlack"]:
pass
else:
kr.comment(posts["userInfo"]["writerMid"],posts["postInfo"]["postId"],wait["comment"])
except:
count += 1
if(count == 50):
sys.exit(0)
else:
pass
thread2 = threading.Thread(target=autolike)
thread2.daemon = True
thread2.start()
def likefriend():
for zx in range(0,20):
hasil = kr.activity(limit=20)
if hasil['result']['posts'][zx]['postInfo']['liked'] == False:
try:
kr.like(hasil['result']['posts'][zx]['userInfo']['mid'],hasil['result']['posts'][zx]['postInfo']['postId'],likeType=1001)
kr.comment(hasil['result']['posts'][zx]['userInfo']['mid'],hasil['result']['posts'][zx]['postInfo']['postId'],"๐ฤ
ยตลฃเนโษจะโฌ By C-A_Bot๐\n\nโยบยฐหหโฐ tษวส ฤสษฎษส-วสสส ษฎึ
t โฐยบยฐหหโ๏ผ๏ผพฯ๏ผพ๏ผ\nฤ
ยตลฃเนโษจะโฌ by Kris โญ๐ ยปยปยป http://line.me/ti/p/~krissthea ยซยซยซ")
print "Like"
except:
pass
else:
print "Already Liked Om"
time.sleep(0.60)
def likeme():
for zx in range(0,20):
hasil = kr.activity(limit=20)
if hasil['result']['posts'][zx]['postInfo']['liked'] == False:
if hasil['result']['posts'][zx]['userInfo']['mid'] in mid:
try:
kr.like(hasil['result']['posts'][zx]['userInfo']['mid'],hasil['result']['posts'][zx]['postInfo']['postId'],likeType=1002)
kr.comment(hasil['result']['posts'][zx]['userInfo']['mid'],hasil['result']['posts'][zx]['postInfo']['postId'],"๐ฤ
ยตลฃเนโษจะโฌ By C-A_Bot๐\n\nโยบยฐหหโฐ tษวส ฤสษฎษส-วสสส ษฎึ
t โฐยบยฐหหโ๏ผ๏ผพฯ๏ผพ๏ผ\nฤ
ยตลฃเนโษจะโฌ by Kris โญ๐ ยปยปยป http://line.me/ti/p/~krissthea ยซยซยซ")
print "Like"
except:
pass
else:
print "Status Sudah di Like Om"
while True:
try:
Ops = kr.fetchOps(kr.Poll.rev, 5)
except EOFError:
raise Exception("It might be wrong revision\n" + str(kr.Poll.rev))
for Op in Ops:
if (Op.type != OpType.END_OF_OPERATION):
kr.Poll.rev = max(kr.Poll.rev, Op.revision)
bot(Op)
|
MultiGraph.py | import numpy as np
from collections import defaultdict
import time
import torch
from train_models import robotTrain, robotPreTrain
from traversal.NavigableGraph import HNSW
from traversal.Greedy import GreedyTraversal
from utils import parallelize, test_valid
import json
from torch.multiprocessing import Process, Queue
import argparse
# Multiprocessing function to be called for training
def train_process(q_in, q_out, Net, dist, data_path, model_path):
global n_gpus
id = q_in.get()
if n_gpus > 0:
torch.cuda.set_device(id%n_gpus)
device = 'cuda'
else:
device = 'cpu'
print('Process '+str(id)+' started.')
while True:
got = q_in.get()
if got is None: break
cmd, obj = got
if cmd == 'train':
n, neighbors = obj
L = robotPreTrain(n, neighbors, Net, data_path, model_path)
q_out.put(L)
del n, neighbors, obj
elif cmd == 'dist':
a, b = obj
d = dist(a, b, device)
q_out.put((a, b, d))
del a, b, d, obj
q_out.put(None)
print('Process '+str(id)+' ended.')
class Tester:
def __init__(self, envs, data_path, model_path, k=4, d=10, robots=100000):
self.k = k
self.d = d
self.envs = envs
self.robots = robots
self.data_path = data_path
if self.data_path[-1] != '/': self.data_path += '/'
self.model_path = model_path
if self.model_path[-1] != '/': self.model_path += '/'
self.weights = {}
def load_G(self, path):
edgeDict = defaultdict(list, json.load(open(path)))
G = list(edgeDict.keys())
return edgeDict, G
def test_dist(self, b, a, dev='cuda'):
if((b,a) in self.weights):
return self.weights[(b,a)]
env_b = b.split("_")[0]
robot_b = b.split("_")[1]
model_b = torch.load(self.model_path + env_b + '_model_' + robot_b + '.pt').to(dev)
env_a = a.split("_")[0]
robot_a = a.split("_")[1]
data_a = np.load(self.data_path + env_a + '_train_1000_' + robot_a + '.npy', allow_pickle=True)
edge_wt = test_valid(model_b, data_a)
self.weights[(b,a)] = edge_wt
self.weights[(a,b)] = edge_wt
return edge_wt
def test(self, k, algoClass, Net, n_runs, env, batch=False, G_path=None):
if batch:
return self.test_batch(k, algoClass, Net, n_runs, env, G_path)
else:
return self.test_seq(k, algoClass, Net, n_runs, env, G_path)
def test_seq(self, k, algoClass, Net, n_runs, env, G_path=None):
nodes = []
for i in range(len(envs) * self.robots):
nodes.append(i)
if G_path is None:
# Inserting one node into graph manually
G = [envs[0]+'_'+str(0)]
robotTrain(envs[0], 0, Net, self.data_path, self.model_path)
edgeDict = defaultdict(list)
else:
edgeDict, G = self.load_G(G_path)
algo = algoClass(G, edgeDict, self.test_dist)
start = time.time()
for i in range(len(G), len(self.envs * self.robots)):
t = time.time()
if (i % 500 == 0):
with open(env+"_1.json", "w") as outfile:
json.dump(algo.getEdgeDict(), outfile)
env = envs[i // self.robots]
robot = i % self.robots
# Defining a node by its relation to an env and a robot ID
n = str(env) + "_" + str(robot)
# Collecting Top K neighbors
neighbors = algo.getNeighbors(n, k, n_runs)
neighbor_t = time.time()
# Training Node on these neighbors
robotPreTrain(n, neighbors, Net, self.data_path, self.model_path)
pretrain_t = time.time()
# Adding trained node into the graph by connecting to neighbors
algo.addNode(n, neighbors)
add_t = time.time()
print('Node '+str(i)+' :'+str(round(time.time()-start,3)))
print('\tNeighbors Time: '+str(round(neighbor_t - t,3)))
print('\tPretrain Time: '+str(round(pretrain_t - neighbor_t,3)))
return algo
def test_batch(self, k, algoClass, Net, n_runs, env, G_path=None, max_batch=6):
Q, P = [], []
for i in range(max_batch):
q_in = Queue()
q_out = Queue()
p = Process(target=train_process, args=(q_in, q_out, Net, self.test_dist, self.data_path, self.model_path))
p.start()
q_in.put(i)
Q.append((q_in, q_out))
P.append(p)
nodes = []
for i in range(len(envs) * self.robots):
nodes.append(i)
if G_path is None:
# Inserting one node into graph manually
G = [envs[0]+'_'+str(0)]
robotTrain(envs[0], 0, Net, self.data_path, self.model_path)
edgeDict = defaultdict(list)
else:
edgeDict, G = self.load_G(G_path)
algo = algoClass(G, edgeDict, self.test_dist)
i = len(G)
start = time.time()
while i < len(self.envs) * self.robots:
t = time.time()
N, neighbors = [], []
batch_size = max(min(max_batch, int(np.log(len(G))/np.log(2))), 1)
# Collecting nodes
for j in range(batch_size):
if i >= len(self.envs) * self.robots:
break
env = envs[i // self.robots]
robot = i % self.robots
i += 1
# Defining a node by its relation to an env and a robot ID
n = str(env) + "_" + str(robot)
N.append(n)
if (i % 500 == 0):
with open(env+"_1.json", "w") as outfile:
json.dump(algo.getEdgeDict(), outfile)
# Adding trained node into the graph by connecting to neighbors
for j in range(len(N)):
algo.addNode(N[j],self.k)
# Collecting Top K neighbors
for n in N:
neighbors.append(algo.getNeighbors(n, k, n_runs))
# Training Nodes on their neighbors
inputs = [('train', (N[j], neighbors[j])) for j in range(len(N))]
Ls = parallelize(inputs, P, Q)
print(Ls)
print('Node '+str(len(G))+' :'+str(round(time.time()-start,3)))
print('Process Complete')
for i in range(len(P)):
Q[i][0].put(None)
Q[i][1].get()
return algo
if __name__ == "__main__":
from models.bnn import BNN
# from models.linear import Linear
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--gpus', type=int, default=1) # number of GPUs
parser.add_argument('--env', type=str, default='rand')
parser.add_argument('--robots', type=int, default=10000)
parser.add_argument('--runs', type=int, default=4)
parser.add_argument('--k', type=int, default=4)
parser.add_argument('--n_models', type=int, default=5)
parser.add_argument('--n_elites', type=int, default=5)
parser.add_argument('--load', type=str, default=None)
parser.add_argument('--model-path', type=str, default='trained')
parser.add_argument('--data-path', type=str, default='data/PinkPanther')
args = parser.parse_args()
print('Started At '+str(time.time()))
global n_gpus, device
if args.gpus > 0:
n_gpus = args.gpus
device = "cuda"
else:
n_gpus = torch.cuda.device_count()
if n_gpus == 0:
device = 'cpu'
from models.seq_ensemble import Ensemble
pop_size=args.n_models
n_elites=args.n_elites
Network = lambda state_dim, act_dim: Ensemble([BNN(state_dim, act_dim) for _ in range(pop_size)], pop_size, n_elites)
print('Training on '+args.env)
envs = [args.env]
model_path = args.model_path+'/'+args.env
data_path = args.data_path+'/'+args.env
t = Tester(envs, data_path, model_path, k=args.k, d=10, robots=args.robots)
G = t.test(args.k, HNSW, Network, args.runs, args.env, G_path=args.load, batch=True)
with open(args.env+"_1.json", "w") as outfile:
json.dump(G.edgeDict, outfile)
|
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 os
import pickle
import random
import re
import subprocess
import sys
import sysconfig
import textwrap
import threading
import time
import unittest
from test import support
from test.support import MISSING_C_DOCSTRINGS
from test.support.script_helper import assert_python_failure, assert_python_ok
try:
import _posixsubprocess
except ImportError:
_posixsubprocess = None
# Skip this test if the _testcapi module isn't available.
_testcapi = support.import_module('_testcapi')
# Were we compiled --with-pydebug or with #define Py_DEBUG?
Py_DEBUG = hasattr(sys, 'gettotalrefcount')
def testfunction(self):
"""some doc"""
return self
class InstanceMethod:
id = _testcapi.instancemethod(id)
testfunction = _testcapi.instancemethod(testfunction)
class CAPITest(unittest.TestCase):
def test_instancemethod(self):
inst = InstanceMethod()
self.assertEqual(id(inst), inst.id())
self.assertTrue(inst.testfunction() is inst)
self.assertEqual(inst.testfunction.__doc__, testfunction.__doc__)
self.assertEqual(InstanceMethod.testfunction.__doc__, testfunction.__doc__)
InstanceMethod.testfunction.attribute = "test"
self.assertEqual(testfunction.attribute, "test")
self.assertRaises(AttributeError, setattr, inst.testfunction, "attribute", "test")
def test_no_FatalError_infinite_loop(self):
with support.SuppressCrashReport():
p = subprocess.Popen([sys.executable, "-c",
'import _testcapi;'
'_testcapi.crash_no_current_thread()'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
(out, err) = p.communicate()
self.assertEqual(out, b'')
# This used to cause an infinite loop.
self.assertTrue(err.rstrip().startswith(
b'Fatal Python error:'
b' PyThreadState_Get: no current thread'))
def test_memoryview_from_NULL_pointer(self):
self.assertRaises(ValueError, _testcapi.make_memoryview_from_NULL_pointer)
def test_exc_info(self):
raised_exception = ValueError("5")
new_exc = TypeError("TEST")
try:
raise raised_exception
except ValueError as e:
tb = e.__traceback__
orig_sys_exc_info = sys.exc_info()
orig_exc_info = _testcapi.set_exc_info(new_exc.__class__, new_exc, None)
new_sys_exc_info = sys.exc_info()
new_exc_info = _testcapi.set_exc_info(*orig_exc_info)
reset_sys_exc_info = sys.exc_info()
self.assertEqual(orig_exc_info[1], e)
self.assertSequenceEqual(orig_exc_info, (raised_exception.__class__, raised_exception, tb))
self.assertSequenceEqual(orig_sys_exc_info, orig_exc_info)
self.assertSequenceEqual(reset_sys_exc_info, orig_exc_info)
self.assertSequenceEqual(new_exc_info, (new_exc.__class__, new_exc, None))
self.assertSequenceEqual(new_sys_exc_info, new_exc_info)
else:
self.assertTrue(False)
@unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.')
def test_seq_bytes_to_charp_array(self):
# Issue #15732: crash in _PySequence_BytesToCharpArray()
class Z(object):
def __len__(self):
return 1
self.assertRaises(TypeError, _posixsubprocess.fork_exec,
1,Z(),3,(1, 2),5,6,7,8,9,10,11,12,13,14,15,16,17)
# Issue #15736: overflow in _PySequence_BytesToCharpArray()
class Z(object):
def __len__(self):
return sys.maxsize
def __getitem__(self, i):
return b'x'
self.assertRaises(MemoryError, _posixsubprocess.fork_exec,
1,Z(),3,(1, 2),5,6,7,8,9,10,11,12,13,14,15,16,17)
@unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.')
def test_subprocess_fork_exec(self):
class Z(object):
def __len__(self):
return 1
# Issue #15738: crash in subprocess_fork_exec()
self.assertRaises(TypeError, _posixsubprocess.fork_exec,
Z(),[b'1'],3,(1, 2),5,6,7,8,9,10,11,12,13,14,15,16,17)
@unittest.skipIf(MISSING_C_DOCSTRINGS,
"Signature information for builtins requires docstrings")
def test_docstring_signature_parsing(self):
self.assertEqual(_testcapi.no_docstring.__doc__, None)
self.assertEqual(_testcapi.no_docstring.__text_signature__, None)
self.assertEqual(_testcapi.docstring_empty.__doc__, None)
self.assertEqual(_testcapi.docstring_empty.__text_signature__, None)
self.assertEqual(_testcapi.docstring_no_signature.__doc__,
"This docstring has no signature.")
self.assertEqual(_testcapi.docstring_no_signature.__text_signature__, None)
self.assertEqual(_testcapi.docstring_with_invalid_signature.__doc__,
"docstring_with_invalid_signature($module, /, boo)\n"
"\n"
"This docstring has an invalid signature."
)
self.assertEqual(_testcapi.docstring_with_invalid_signature.__text_signature__, None)
self.assertEqual(_testcapi.docstring_with_invalid_signature2.__doc__,
"docstring_with_invalid_signature2($module, /, boo)\n"
"\n"
"--\n"
"\n"
"This docstring also has an invalid signature."
)
self.assertEqual(_testcapi.docstring_with_invalid_signature2.__text_signature__, None)
self.assertEqual(_testcapi.docstring_with_signature.__doc__,
"This docstring has a valid signature.")
self.assertEqual(_testcapi.docstring_with_signature.__text_signature__, "($module, /, sig)")
self.assertEqual(_testcapi.docstring_with_signature_but_no_doc.__doc__, None)
self.assertEqual(_testcapi.docstring_with_signature_but_no_doc.__text_signature__,
"($module, /, sig)")
self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__doc__,
"\nThis docstring has a valid signature and some extra newlines.")
self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__text_signature__,
"($module, /, parameter)")
def test_c_type_with_matrix_multiplication(self):
M = _testcapi.matmulType
m1 = M()
m2 = M()
self.assertEqual(m1 @ m2, ("matmul", m1, m2))
self.assertEqual(m1 @ 42, ("matmul", m1, 42))
self.assertEqual(42 @ m1, ("matmul", 42, m1))
o = m1
o @= m2
self.assertEqual(o, ("imatmul", m1, m2))
o = m1
o @= 42
self.assertEqual(o, ("imatmul", m1, 42))
o = 42
o @= m1
self.assertEqual(o, ("matmul", 42, m1))
def test_return_null_without_error(self):
# Issue #23571: A function must not return NULL without setting an
# error
if Py_DEBUG:
code = textwrap.dedent("""
import _testcapi
from test import support
with support.SuppressCrashReport():
_testcapi.return_null_without_error()
""")
rc, out, err = assert_python_failure('-c', code)
self.assertRegex(err.replace(b'\r', b''),
br'Fatal Python error: a function returned NULL '
br'without setting an error\n'
br'SystemError: <built-in function '
br'return_null_without_error> returned NULL '
br'without setting an error\n'
br'\n'
br'Current thread.*:\n'
br' File .*", line 6 in <module>')
else:
with self.assertRaises(SystemError) as cm:
_testcapi.return_null_without_error()
self.assertRegex(str(cm.exception),
'return_null_without_error.* '
'returned NULL without setting an error')
def test_return_result_with_error(self):
# Issue #23571: A function must not return a result with an error set
if Py_DEBUG:
code = textwrap.dedent("""
import _testcapi
from test import support
with support.SuppressCrashReport():
_testcapi.return_result_with_error()
""")
rc, out, err = assert_python_failure('-c', code)
self.assertRegex(err.replace(b'\r', b''),
br'Fatal Python error: a function returned a '
br'result with an error set\n'
br'ValueError\n'
br'\n'
br'The above exception was the direct cause '
br'of the following exception:\n'
br'\n'
br'SystemError: <built-in '
br'function return_result_with_error> '
br'returned a result with an error set\n'
br'\n'
br'Current thread.*:\n'
br' File .*, line 6 in <module>')
else:
with self.assertRaises(SystemError) as cm:
_testcapi.return_result_with_error()
self.assertRegex(str(cm.exception),
'return_result_with_error.* '
'returned a result with an error set')
def test_buildvalue_N(self):
_testcapi.test_buildvalue_N()
def test_set_nomemory(self):
code = """if 1:
import _testcapi
class C(): pass
# The first loop tests both functions and that remove_mem_hooks()
# can be called twice in a row. The second loop checks a call to
# set_nomemory() after a call to remove_mem_hooks(). The third
# loop checks the start and stop arguments of set_nomemory().
for outer_cnt in range(1, 4):
start = 10 * outer_cnt
for j in range(100):
if j == 0:
if outer_cnt != 3:
_testcapi.set_nomemory(start)
else:
_testcapi.set_nomemory(start, start + 1)
try:
C()
except MemoryError as e:
if outer_cnt != 3:
_testcapi.remove_mem_hooks()
print('MemoryError', outer_cnt, j)
_testcapi.remove_mem_hooks()
break
"""
rc, out, err = assert_python_ok('-c', code)
self.assertIn(b'MemoryError 1 10', out)
self.assertIn(b'MemoryError 2 20', out)
self.assertIn(b'MemoryError 3 30', out)
def test_mapping_keys_values_items(self):
class Mapping1(dict):
def keys(self):
return list(super().keys())
def values(self):
return list(super().values())
def items(self):
return list(super().items())
class Mapping2(dict):
def keys(self):
return tuple(super().keys())
def values(self):
return tuple(super().values())
def items(self):
return tuple(super().items())
dict_obj = {'foo': 1, 'bar': 2, 'spam': 3}
for mapping in [{}, OrderedDict(), Mapping1(), Mapping2(),
dict_obj, OrderedDict(dict_obj),
Mapping1(dict_obj), Mapping2(dict_obj)]:
self.assertListEqual(_testcapi.get_mapping_keys(mapping),
list(mapping.keys()))
self.assertListEqual(_testcapi.get_mapping_values(mapping),
list(mapping.values()))
self.assertListEqual(_testcapi.get_mapping_items(mapping),
list(mapping.items()))
def test_mapping_keys_values_items_bad_arg(self):
self.assertRaises(AttributeError, _testcapi.get_mapping_keys, None)
self.assertRaises(AttributeError, _testcapi.get_mapping_values, None)
self.assertRaises(AttributeError, _testcapi.get_mapping_items, None)
class BadMapping:
def keys(self):
return None
def values(self):
return None
def items(self):
return None
bad_mapping = BadMapping()
self.assertRaises(TypeError, _testcapi.get_mapping_keys, bad_mapping)
self.assertRaises(TypeError, _testcapi.get_mapping_values, bad_mapping)
self.assertRaises(TypeError, _testcapi.get_mapping_items, bad_mapping)
class TestPendingCalls(unittest.TestCase):
def pendingcalls_submit(self, l, n):
def callback():
#this function can be interrupted by thread switching so let's
#use an atomic operation
l.append(None)
for i in range(n):
time.sleep(random.random()*0.02) #0.01 secs on average
#try submitting callback until successful.
#rely on regular interrupt to flush queue if we are
#unsuccessful.
while True:
if _testcapi._pending_threadfunc(callback):
break;
def pendingcalls_wait(self, l, n, context = None):
#now, stick around until l[0] has grown to 10
count = 0;
while len(l) != n:
#this busy loop is where we expect to be interrupted to
#run our callbacks. Note that callbacks are only run on the
#main thread
if False and support.verbose:
print("(%i)"%(len(l),),)
for i in range(1000):
a = i*i
if context and not context.event.is_set():
continue
count += 1
self.assertTrue(count < 10000,
"timeout waiting for %i callbacks, got %i"%(n, len(l)))
if False and support.verbose:
print("(%i)"%(len(l),))
def test_pendingcalls_threaded(self):
#do every callback on a separate thread
n = 32 #total callbacks
threads = []
class foo(object):pass
context = foo()
context.l = []
context.n = 2 #submits per thread
context.nThreads = n // context.n
context.nFinished = 0
context.lock = threading.Lock()
context.event = threading.Event()
threads = [threading.Thread(target=self.pendingcalls_thread,
args=(context,))
for i in range(context.nThreads)]
with support.start_threads(threads):
self.pendingcalls_wait(context.l, n, context)
def pendingcalls_thread(self, context):
try:
self.pendingcalls_submit(context.l, context.n)
finally:
with context.lock:
context.nFinished += 1
nFinished = context.nFinished
if False and support.verbose:
print("finished threads: ", nFinished)
if nFinished == context.nThreads:
context.event.set()
def test_pendingcalls_non_threaded(self):
#again, just using the main thread, likely they will all be dispatched at
#once. It is ok to ask for too many, because we loop until we find a slot.
#the loop can be interrupted to dispatch.
#there are only 32 dispatch slots, so we go for twice that!
l = []
n = 64
self.pendingcalls_submit(l, n)
self.pendingcalls_wait(l, n)
class SubinterpreterTest(unittest.TestCase):
def test_subinterps(self):
import builtins
r, w = os.pipe()
code = """if 1:
import sys, builtins, pickle
with open({:d}, "wb") as f:
pickle.dump(id(sys.modules), f)
pickle.dump(id(builtins), f)
""".format(w)
with open(r, "rb") as f:
ret = support.run_in_subinterp(code)
self.assertEqual(ret, 0)
self.assertNotEqual(pickle.load(f), id(sys.modules))
self.assertNotEqual(pickle.load(f), id(builtins))
class TestThreadState(unittest.TestCase):
@support.reap_threads
def test_thread_state(self):
# some extra thread-state tests driven via _testcapi
def target():
idents = []
def callback():
idents.append(threading.get_ident())
_testcapi._test_thread_state(callback)
a = b = callback
time.sleep(1)
# Check our main thread is in the list exactly 3 times.
self.assertEqual(idents.count(threading.get_ident()), 3,
"Couldn't find main thread correctly in the list")
target()
t = threading.Thread(target=target)
t.start()
t.join()
class Test_testcapi(unittest.TestCase):
locals().update((name, getattr(_testcapi, name))
for name in dir(_testcapi)
if name.startswith('test_') and not name.endswith('_code'))
class PyMemDebugTests(unittest.TestCase):
PYTHONMALLOC = 'debug'
# '0x04c06e0' or '04C06E0'
PTR_REGEX = r'(?:0x)?[0-9a-fA-F]+'
def check(self, code):
with support.SuppressCrashReport():
out = assert_python_failure('-c', code,
PYTHONMALLOC=self.PYTHONMALLOC)
stderr = out.err
return stderr.decode('ascii', 'replace')
def test_buffer_overflow(self):
out = self.check('import _testcapi; _testcapi.pymem_buffer_overflow()')
regex = (r"Debug memory block at address p={ptr}: API 'm'\n"
r" 16 bytes originally requested\n"
r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n"
r" The [0-9] pad bytes at tail={ptr} are not all FORBIDDENBYTE \(0x[0-9a-f]{{2}}\):\n"
r" at tail\+0: 0x78 \*\*\* OUCH\n"
r" at tail\+1: 0xfb\n"
r" at tail\+2: 0xfb\n"
r" .*\n"
r" The block was made by call #[0-9]+ to debug malloc/realloc.\n"
r" Data at p: cb cb cb .*\n"
r"\n"
r"Enable tracemalloc to get the memory block allocation traceback\n"
r"\n"
r"Fatal Python error: bad trailing pad byte")
regex = regex.format(ptr=self.PTR_REGEX)
regex = re.compile(regex, flags=re.DOTALL)
self.assertRegex(out, regex)
def test_api_misuse(self):
out = self.check('import _testcapi; _testcapi.pymem_api_misuse()')
regex = (r"Debug memory block at address p={ptr}: API 'm'\n"
r" 16 bytes originally requested\n"
r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n"
r" The [0-9] pad bytes at tail={ptr} are FORBIDDENBYTE, as expected.\n"
r" The block was made by call #[0-9]+ to debug malloc/realloc.\n"
r" Data at p: cb cb cb .*\n"
r"\n"
r"Enable tracemalloc to get the memory block allocation traceback\n"
r"\n"
r"Fatal Python error: bad ID: Allocated using API 'm', verified using API 'r'\n")
regex = regex.format(ptr=self.PTR_REGEX)
self.assertRegex(out, regex)
def check_malloc_without_gil(self, code):
out = self.check(code)
expected = ('Fatal Python error: Python memory allocator called '
'without holding the GIL')
self.assertIn(expected, out)
def test_pymem_malloc_without_gil(self):
# Debug hooks must raise an error if PyMem_Malloc() is called
# without holding the GIL
code = 'import _testcapi; _testcapi.pymem_malloc_without_gil()'
self.check_malloc_without_gil(code)
def test_pyobject_malloc_without_gil(self):
# Debug hooks must raise an error if PyObject_Malloc() is called
# without holding the GIL
code = 'import _testcapi; _testcapi.pyobject_malloc_without_gil()'
self.check_malloc_without_gil(code)
class PyMemMallocDebugTests(PyMemDebugTests):
PYTHONMALLOC = 'malloc_debug'
@unittest.skipUnless(support.with_pymalloc(), 'need pymalloc')
class PyMemPymallocDebugTests(PyMemDebugTests):
PYTHONMALLOC = 'pymalloc_debug'
@unittest.skipUnless(Py_DEBUG, 'need Py_DEBUG')
class PyMemDefaultTests(PyMemDebugTests):
# test default allocator of Python compiled in debug mode
PYTHONMALLOC = ''
if __name__ == "__main__":
unittest.main()
|
wsdump.py | #!/Users/annethessen/eco-kg/try2/bin/python3
"""
websocket - WebSocket client library for Python
Copyright (C) 2010 Hiroki Ohtani(liris)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
"""
import argparse
import code
import sys
import threading
import time
import ssl
import gzip
import zlib
from urllib.parse import urlparse
import websocket
try:
import readline
except ImportError:
pass
def get_encoding():
encoding = getattr(sys.stdin, "encoding", "")
if not encoding:
return "utf-8"
else:
return encoding.lower()
OPCODE_DATA = (websocket.ABNF.OPCODE_TEXT, websocket.ABNF.OPCODE_BINARY)
ENCODING = get_encoding()
class VAction(argparse.Action):
def __call__(self, parser, args, values, option_string=None):
if values is None:
values = "1"
try:
values = int(values)
except ValueError:
values = values.count("v") + 1
setattr(args, self.dest, values)
def parse_args():
parser = argparse.ArgumentParser(description="WebSocket Simple Dump Tool")
parser.add_argument("url", metavar="ws_url",
help="websocket url. ex. ws://echo.websocket.org/")
parser.add_argument("-p", "--proxy",
help="proxy url. ex. http://127.0.0.1:8080")
parser.add_argument("-v", "--verbose", default=0, nargs='?', action=VAction,
dest="verbose",
help="set verbose mode. If set to 1, show opcode. "
"If set to 2, enable to trace websocket module")
parser.add_argument("-n", "--nocert", action='store_true',
help="Ignore invalid SSL cert")
parser.add_argument("-r", "--raw", action="store_true",
help="raw output")
parser.add_argument("-s", "--subprotocols", nargs='*',
help="Set subprotocols")
parser.add_argument("-o", "--origin",
help="Set origin")
parser.add_argument("--eof-wait", default=0, type=int,
help="wait time(second) after 'EOF' received.")
parser.add_argument("-t", "--text",
help="Send initial text")
parser.add_argument("--timings", action="store_true",
help="Print timings in seconds")
parser.add_argument("--headers",
help="Set custom headers. Use ',' as separator")
return parser.parse_args()
class RawInput:
def raw_input(self, prompt):
line = input(prompt)
if ENCODING and ENCODING != "utf-8" and not isinstance(line, str):
line = line.decode(ENCODING).encode("utf-8")
elif isinstance(line, str):
line = line.encode("utf-8")
return line
class InteractiveConsole(RawInput, code.InteractiveConsole):
def write(self, data):
sys.stdout.write("\033[2K\033[E")
# sys.stdout.write("\n")
sys.stdout.write("\033[34m< " + data + "\033[39m")
sys.stdout.write("\n> ")
sys.stdout.flush()
def read(self):
return self.raw_input("> ")
class NonInteractive(RawInput):
def write(self, data):
sys.stdout.write(data)
sys.stdout.write("\n")
sys.stdout.flush()
def read(self):
return self.raw_input("")
def main():
start_time = time.time()
args = parse_args()
if args.verbose > 1:
websocket.enableTrace(True)
options = {}
if args.proxy:
p = urlparse(args.proxy)
options["http_proxy_host"] = p.hostname
options["http_proxy_port"] = p.port
if args.origin:
options["origin"] = args.origin
if args.subprotocols:
options["subprotocols"] = args.subprotocols
opts = {}
if args.nocert:
opts = {"cert_reqs": ssl.CERT_NONE, "check_hostname": False}
if args.headers:
options['header'] = list(map(str.strip, args.headers.split(',')))
ws = websocket.create_connection(args.url, sslopt=opts, **options)
if args.raw:
console = NonInteractive()
else:
console = InteractiveConsole()
print("Press Ctrl+C to quit")
def recv():
try:
frame = ws.recv_frame()
except websocket.WebSocketException:
return websocket.ABNF.OPCODE_CLOSE, None
if not frame:
raise websocket.WebSocketException("Not a valid frame %s" % frame)
elif frame.opcode in OPCODE_DATA:
return frame.opcode, frame.data
elif frame.opcode == websocket.ABNF.OPCODE_CLOSE:
ws.send_close()
return frame.opcode, None
elif frame.opcode == websocket.ABNF.OPCODE_PING:
ws.pong(frame.data)
return frame.opcode, frame.data
return frame.opcode, frame.data
def recv_ws():
while True:
opcode, data = recv()
msg = None
if opcode == websocket.ABNF.OPCODE_TEXT and isinstance(data, bytes):
data = str(data, "utf-8")
if isinstance(data, bytes) and len(data) > 2 and data[:2] == b'\037\213': # gzip magick
try:
data = "[gzip] " + str(gzip.decompress(data), "utf-8")
except:
pass
elif isinstance(data, bytes):
try:
data = "[zlib] " + str(zlib.decompress(data, -zlib.MAX_WBITS), "utf-8")
except:
pass
if isinstance(data, bytes):
data = repr(data)
if args.verbose:
msg = "%s: %s" % (websocket.ABNF.OPCODE_MAP.get(opcode), data)
else:
msg = data
if msg is not None:
if args.timings:
console.write(str(time.time() - start_time) + ": " + msg)
else:
console.write(msg)
if opcode == websocket.ABNF.OPCODE_CLOSE:
break
thread = threading.Thread(target=recv_ws)
thread.daemon = True
thread.start()
if args.text:
ws.send(args.text)
while True:
try:
message = console.read()
ws.send(message)
except KeyboardInterrupt:
return
except EOFError:
time.sleep(args.eof_wait)
return
if __name__ == "__main__":
try:
main()
except Exception as e:
print(e)
|
bad_thread_instantiation.py | # pylint: disable=missing-docstring
import threading
threading.Thread(lambda: None).run() # [bad-thread-instantiation]
threading.Thread(None, lambda: None)
threading.Thread(group=None, target=lambda: None).run()
threading.Thread() # [bad-thread-instantiation]
|
web.py | # Electrum - lightweight Bitcoin client
# Copyright (C) 2011 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 limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from decimal import Decimal as PyDecimal # Qt 5.12 also exports Decimal
import os
import re
import shutil
import threading
import urllib
from .address import Address
from . import bitcoin
from . import networks
from .util import format_satoshis_plain
DEFAULT_EXPLORER = "Blockchair.com"
mainnet_block_explorers = {
'Bitcoin.com': ('https://explorer.bitcoin.com/bch',
Address.FMT_CASHADDR,
{'tx': 'tx', 'addr': 'address'}),
'Blockchair.com': ('https://blockchair.com/bitcoin-cash',
Address.FMT_CASHADDR,
{'tx': 'transaction', 'addr': 'address'}),
'Blocktrail.com': ('https://blocktrail.com/BCC',
Address.FMT_LEGACY,
{'tx': 'tx', 'addr': 'address'}),
'BTC.com': ('https://bch.btc.com',
Address.FMT_CASHADDR,
{'tx': '', 'addr': ''}),
'ViaBTC.com': ('https://www.viabtc.com/bch',
Address.FMT_CASHADDR,
{'tx': 'tx', 'addr': 'address'}),
}
DEFAULT_EXPLORER_TESTNET = 'Bitcoin.com'
testnet_block_explorers = {
'Blocktrail.com': ('https://www.blocktrail.com/tBCC',
Address.FMT_LEGACY,
{'tx': 'tx', 'addr': 'address'}),
'Bitcoin.com' : ('https://explorer.bitcoin.com/tbch',
Address.FMT_LEGACY, # For some reason testnet expects legacy and fails on bchtest: addresses.
{'tx': 'tx', 'addr': 'address'}),
}
def BE_info():
if networks.net.TESTNET:
return testnet_block_explorers
return mainnet_block_explorers
def BE_tuple(config):
infodict = BE_info()
return (infodict.get(BE_from_config(config))
or infodict.get(BE_default_explorer()) # In case block explorer in config is bad/no longet valid
)
def BE_default_explorer():
return (DEFAULT_EXPLORER
if not networks.net.TESTNET
else DEFAULT_EXPLORER_TESTNET)
def BE_from_config(config):
return config.get('block_explorer', BE_default_explorer())
def BE_URL(config, kind, item):
be_tuple = BE_tuple(config)
if not be_tuple:
return
url_base, addr_fmt, parts = be_tuple
kind_str = parts.get(kind)
if kind_str is None:
return
if kind == 'addr':
assert isinstance(item, Address)
item = item.to_string(addr_fmt)
return "/".join(part for part in (url_base, kind_str, item) if part)
def BE_sorted_list():
return sorted(BE_info())
def create_URI(addr, amount, message):
if not isinstance(addr, Address):
return ""
scheme, path = addr.to_URI_components()
query = []
if amount:
query.append('amount=%s'%format_satoshis_plain(amount))
if message:
query.append('message=%s'%urllib.parse.quote(message))
p = urllib.parse.ParseResult(scheme=scheme,
netloc='', path=path, params='',
query='&'.join(query), fragment='')
return urllib.parse.urlunparse(p)
# URL decode
#_ud = re.compile('%([0-9a-hA-H]{2})', re.MULTILINE)
#urldecode = lambda x: _ud.sub(lambda m: chr(int(m.group(1), 16)), x)
def parse_URI(uri, on_pr=None):
if ':' not in uri:
# Test it's valid
Address.from_string(uri)
return {'address': uri}
u = urllib.parse.urlparse(uri)
# The scheme always comes back in lower case
if u.scheme != networks.net.CASHADDR_PREFIX:
raise Exception("Not a {} URI".format(networks.net.CASHADDR_PREFIX))
address = u.path
# python for android fails to parse query
if address.find('?') > 0:
address, query = u.path.split('?')
pq = urllib.parse.parse_qs(query, keep_blank_values=True)
else:
pq = urllib.parse.parse_qs(u.query, keep_blank_values=True)
for k, v in pq.items():
if len(v)!=1:
raise Exception('Duplicate Key', k)
out = {k: v[0] for k, v in pq.items()}
if address:
Address.from_string(address)
out['address'] = address
if 'amount' in out:
am = out['amount']
m = re.match(r'([0-9\.]+)X([0-9])', am)
if m:
k = int(m.group(2)) - 8
amount = PyDecimal(m.group(1)) * pow(10, k)
else:
amount = PyDecimal(am) * bitcoin.COIN
out['amount'] = int(amount)
if 'message' in out:
out['message'] = out['message']
out['memo'] = out['message']
if 'time' in out:
out['time'] = int(out['time'])
if 'exp' in out:
out['exp'] = int(out['exp'])
if 'sig' in out:
out['sig'] = bh2u(bitcoin.base_decode(out['sig'], None, base=58))
r = out.get('r')
sig = out.get('sig')
name = out.get('name')
if on_pr and (r or (name and sig)):
def get_payment_request_thread():
from . import paymentrequest as pr
if name and sig:
s = pr.serialize_request(out).SerializeToString()
request = pr.PaymentRequest(s)
else:
request = pr.get_payment_request(r)
if on_pr:
on_pr(request)
t = threading.Thread(target=get_payment_request_thread)
t.setDaemon(True)
t.start()
return out
def check_www_dir(rdir):
if not os.path.exists(rdir):
os.mkdir(rdir)
index = os.path.join(rdir, 'index.html')
if not os.path.exists(index):
print_error("copying index.html")
src = os.path.join(os.path.dirname(__file__), 'www', 'index.html')
shutil.copy(src, index)
files = [
"https://code.jquery.com/jquery-1.9.1.min.js",
"https://raw.githubusercontent.com/davidshimjs/qrcodejs/master/qrcode.js",
"https://code.jquery.com/ui/1.10.3/jquery-ui.js",
"https://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"
]
for URL in files:
path = urllib.parse.urlsplit(URL).path
filename = os.path.basename(path)
path = os.path.join(rdir, filename)
if not os.path.exists(path):
print_error("downloading ", URL)
urllib.request.urlretrieve(URL, path)
|
test_storage.py | import time
import random
import threading
from uuid import uuid4
import hiro
import mock
import sys
from limits.strategies import FixedWindowRateLimiter, MovingWindowRateLimiter
from limits.errors import ConfigurationError
from limits.limits import RateLimitItemPerMinute, RateLimitItemPerSecond
from limits.storage import (
MemoryStorage, RedisStorage, MemcachedStorage, RedisSentinelStorage,
RedisClusterStorage, Storage, GAEMemcachedStorage, storage_from_string
)
from tests import StorageTests, skip_if, RUN_GAE
class StorageTests(StorageTests):
def test_storage_string(self):
self.assertTrue(isinstance(storage_from_string("memory://"), MemoryStorage))
self.assertTrue(isinstance(storage_from_string("redis://localhost:6379"), RedisStorage))
self.assertTrue(isinstance(storage_from_string("memcached://localhost:11211"), MemcachedStorage))
self.assertTrue(isinstance(storage_from_string("redis+sentinel://localhost:26379", service_name="localhost-redis-sentinel"), RedisSentinelStorage))
self.assertTrue(isinstance(storage_from_string("redis+sentinel://localhost:26379/localhost-redis-sentinel"), RedisSentinelStorage))
self.assertTrue(isinstance(storage_from_string("redis+cluster://localhost:7000/"), RedisClusterStorage))
if RUN_GAE:
self.assertTrue(isinstance(storage_from_string("gaememcached://"), GAEMemcachedStorage))
self.assertRaises(ConfigurationError, storage_from_string, "blah://")
self.assertRaises(ConfigurationError, storage_from_string, "redis+sentinel://localhost:26379")
with mock.patch("limits.storage.get_dependency") as get_dependency:
self.assertTrue(isinstance(storage_from_string("redis+sentinel://:foobared@localhost:26379/localhost-redis-sentinel"), RedisSentinelStorage))
self.assertEqual(get_dependency().Sentinel.call_args[1]['password'], 'foobared')
def test_storage_check(self):
self.assertTrue(storage_from_string("memory://").check())
self.assertTrue(storage_from_string("redis://localhost:6379").check())
self.assertTrue(storage_from_string("memcached://localhost:11211").check())
self.assertTrue(storage_from_string("redis+sentinel://localhost:26379", service_name="localhost-redis-sentinel").check())
self.assertTrue(storage_from_string("redis+cluster://localhost:7000").check())
if RUN_GAE:
self.assertTrue(storage_from_string("gaememcached://").check())
def test_in_memory(self):
with hiro.Timeline().freeze() as timeline:
storage = MemoryStorage()
limiter = FixedWindowRateLimiter(storage)
per_min = RateLimitItemPerMinute(10)
for i in range(0,10):
self.assertTrue(limiter.hit(per_min))
self.assertFalse(limiter.hit(per_min))
timeline.forward(61)
self.assertTrue(limiter.hit(per_min))
def test_in_memory_reset(self):
storage = MemoryStorage()
limiter = FixedWindowRateLimiter(storage)
per_min = RateLimitItemPerMinute(10)
for i in range(0,10):
self.assertTrue(limiter.hit(per_min))
self.assertFalse(limiter.hit(per_min))
storage.reset()
for i in range(0,10):
self.assertTrue(limiter.hit(per_min))
self.assertFalse(limiter.hit(per_min))
def test_in_memory_expiry(self):
with hiro.Timeline().freeze() as timeline:
storage = MemoryStorage()
limiter = FixedWindowRateLimiter(storage)
per_min = RateLimitItemPerMinute(10)
for i in range(0,10):
self.assertTrue(limiter.hit(per_min))
timeline.forward(60)
# touch another key and yield
limiter.hit(RateLimitItemPerSecond(1))
time.sleep(0.1)
self.assertTrue(per_min.key_for() not in storage.storage)
def test_in_memory_expiry_moving_window(self):
with hiro.Timeline().freeze() as timeline:
storage = MemoryStorage()
limiter = MovingWindowRateLimiter(storage)
per_min = RateLimitItemPerMinute(10)
per_sec = RateLimitItemPerSecond(1)
for i in range(0,2):
for i in range(0,10):
self.assertTrue(limiter.hit(per_min))
timeline.forward(60)
self.assertTrue(limiter.hit(per_sec))
time.sleep(1)
self.assertEqual([], storage.events[per_min.key_for()])
def test_redis(self):
storage = RedisStorage("redis://localhost:6379")
limiter = FixedWindowRateLimiter(storage)
per_min = RateLimitItemPerSecond(10)
start = time.time()
count = 0
while time.time() - start < 0.5 and count < 10:
self.assertTrue(limiter.hit(per_min))
count += 1
self.assertFalse(limiter.hit(per_min))
while time.time() - start <= 1:
time.sleep(0.1)
self.assertTrue(limiter.hit(per_min))
def test_redis_reset(self):
storage = RedisStorage("redis://localhost:6379")
limiter = FixedWindowRateLimiter(storage)
for i in range(0, 10000):
rate = RateLimitItemPerMinute(i)
limiter.hit(rate)
self.assertEqual(storage.reset(), 10000)
def test_redis_sentinel(self):
storage = RedisSentinelStorage("redis+sentinel://localhost:26379", service_name="localhost-redis-sentinel")
limiter = FixedWindowRateLimiter(storage)
per_min = RateLimitItemPerSecond(10)
start = time.time()
count = 0
while time.time() - start < 0.5 and count < 10:
self.assertTrue(limiter.hit(per_min))
count += 1
self.assertFalse(limiter.hit(per_min))
while time.time() - start <= 1:
time.sleep(0.1)
self.assertTrue(limiter.hit(per_min))
def test_redis_sentinel_reset(self):
storage = RedisSentinelStorage("redis+sentinel://localhost:26379", service_name="localhost-redis-sentinel")
limiter = FixedWindowRateLimiter(storage)
for i in range(0, 10000):
rate = RateLimitItemPerMinute(i)
limiter.hit(rate)
self.assertEqual(storage.reset(), 10000)
def test_redis_cluster(self):
storage = RedisClusterStorage("redis+cluster://localhost:7000")
limiter = FixedWindowRateLimiter(storage)
per_min = RateLimitItemPerSecond(10)
start = time.time()
count = 0
while time.time() - start < 0.5 and count < 10:
self.assertTrue(limiter.hit(per_min))
count += 1
self.assertFalse(limiter.hit(per_min))
while time.time() - start <= 1:
time.sleep(0.1)
self.assertTrue(limiter.hit(per_min))
def test_redis_cluster_reset(self):
storage = RedisClusterStorage("redis+cluster://localhost:7000")
limiter = FixedWindowRateLimiter(storage)
for i in range(0, 10000):
rate = RateLimitItemPerMinute(i)
limiter.hit(rate)
self.assertEqual(storage.reset(), 10000)
def test_pluggable_storage_invalid_construction(self):
def cons():
class _(Storage):
def incr(self, key, expiry, elastic_expiry=False):
return
def get(self, key):
return 0
def get_expiry(self, key):
return time.time()
self.assertRaises(ConfigurationError, cons)
def test_pluggable_storage_no_moving_window(self):
class MyStorage(Storage):
STORAGE_SCHEME = "mystorage"
def incr(self, key, expiry, elastic_expiry=False):
return
def get(self, key):
return 0
def get_expiry(self, key):
return time.time()
storage = storage_from_string("mystorage://")
self.assertTrue(isinstance(storage, MyStorage))
self.assertRaises(NotImplementedError, MovingWindowRateLimiter, storage)
def test_pluggable_storage_moving_window(self):
class MyStorage(Storage):
STORAGE_SCHEME = "mystorage"
def incr(self, key, expiry, elastic_expiry=False):
return
def get(self, key):
return 0
def get_expiry(self, key):
return time.time()
def acquire_entry(self, *a, **k):
return True
def get_moving_window(self, *a, **k):
return (time.time(), 1)
storage = storage_from_string("mystorage://")
self.assertTrue(isinstance(storage, MyStorage))
MovingWindowRateLimiter(storage)
def test_memcached(self):
storage = MemcachedStorage("memcached://localhost:11211")
limiter = FixedWindowRateLimiter(storage)
per_min = RateLimitItemPerSecond(10)
start = time.time()
count = 0
while time.time() - start < 0.5 and count < 10:
self.assertTrue(limiter.hit(per_min))
count += 1
self.assertFalse(limiter.hit(per_min))
while time.time() - start <= 1:
time.sleep(0.1)
self.assertTrue(limiter.hit(per_min))
@skip_if(not RUN_GAE)
def test_gae_memcached(self):
storage = GAEMemcachedStorage("gaememcached://")
limiter = FixedWindowRateLimiter(storage)
per_min = RateLimitItemPerSecond(10)
start = time.time()
count = 0
while time.time() - start < 0.5 and count < 10:
self.assertTrue(limiter.hit(per_min))
count += 1
self.assertFalse(limiter.hit(per_min))
while time.time() - start <= 1:
time.sleep(0.1)
self.assertTrue(limiter.hit(per_min))
def test_large_dataset_redis_moving_window_expiry(self):
storage = RedisStorage("redis://localhost:6379")
limiter = MovingWindowRateLimiter(storage)
limit = RateLimitItemPerSecond(1000)
# 100 routes
fake_routes = [uuid4().hex for _ in range(0,100)]
# go as fast as possible in 2 seconds.
start = time.time()
def smack(e):
while not e.is_set():
self.assertTrue(limiter.hit(limit, random.choice(fake_routes)))
events = [threading.Event() for _ in range(0,100)]
threads = [threading.Thread(target=smack, args=(e,)) for e in events]
[k.start() for k in threads]
while time.time() - start < 2:
time.sleep(0.1)
[k.set() for k in events]
time.sleep(2)
self.assertTrue(storage.storage.keys("%s/*" % limit.namespace) == [])
def test_large_dataset_redis_sentinel_moving_window_expiry(self):
storage = RedisSentinelStorage("redis+sentinel://localhost:26379", service_name="localhost-redis-sentinel")
limiter = MovingWindowRateLimiter(storage)
limit = RateLimitItemPerSecond(1000)
# 100 routes
fake_routes = [uuid4().hex for _ in range(0,100)]
# go as fast as possible in 2 seconds.
start = time.time()
def smack(e):
while not e.is_set():
self.assertTrue(limiter.hit(limit, random.choice(fake_routes)))
events = [threading.Event() for _ in range(0,100)]
threads = [threading.Thread(target=smack, args=(e,)) for e in events]
[k.start() for k in threads]
while time.time() - start < 2:
time.sleep(0.1)
[k.set() for k in events]
time.sleep(2)
self.assertTrue(storage.sentinel.slave_for("localhost-redis-sentinel").keys("%s/*" % limit.namespace) == [])
def test_large_dataset_redis_cluster_moving_window_expiry(self):
storage = RedisClusterStorage("redis+cluster://localhost:7000")
limiter = MovingWindowRateLimiter(storage)
limit = RateLimitItemPerSecond(1000)
# 100 routes
fake_routes = [uuid4().hex for _ in range(0,100)]
# go as fast as possible in 2 seconds.
start = time.time()
def smack(e):
while not e.is_set():
self.assertTrue(limiter.hit(limit, random.choice(fake_routes)))
events = [threading.Event() for _ in range(0,100)]
threads = [threading.Thread(target=smack, args=(e,)) for e in events]
[k.start() for k in threads]
while time.time() - start < 2:
time.sleep(0.1)
[k.set() for k in events]
time.sleep(2)
self.assertTrue(storage.storage.keys("%s/*" % limit.namespace) == [])
|
packet.py | # coding=utf-8
__author__ = 'wang.yuanqiu007@gmail.com'
import pickle
import json
import attr
import socket
import threading
from attr.validators import instance_of, optional
from enum import Enum
# The bytes at the end of the packet
EOF = b'\xFF\xFF\x00\x00'
class PacketParseError(Exception):
def __init__(self, error):
super().__init__(self, error)
def __str__(self):
return f'Packet parse error: {self.error}'
class EventType(Enum):
"""
Packet route type
Attributes:
DIRECT_MSG: Indicate the packet is send to a direct socket.
BROADCAST: Send to all the sockets except itself.
"""
DIRECT_MSG = b'\x01'
BROADCAST = b'\x02'
@staticmethod
def from_int(val=attr.ib(type=int, validator=instance_of(int))):
if val == int(EventType.DIRECT_MSG.value.hex()):
return EventType.DIRECT_MSG
elif val == int(EventType.BROADCAST.value.hex()):
return EventType.BROADCAST
raise PacketParseError('Event type is not legal.')
class DataType(Enum):
"""
Packet data type
"""
RAW = b'\x01' # raw data, no need to decode
PICKLED = b'\x02' # bytes -> python object
STRING = b'\x03' # bytes -> str
JSON = b'\x04' # bytes -> str -> dict
@staticmethod
def from_int(val):
if val == int(DataType.RAW.value.hex()):
return DataType.RAW
elif val == int(DataType.PICKLED.value.hex()):
return DataType.PICKLED
elif val == int(DataType.STRING.value.hex()):
return DataType.STRING
elif val == int(DataType.JSON.value.hex()):
return DataType.JSON
raise PacketParseError(f'Unexpected datatype {str(val)}')
@attr.s
class Packet:
event_type = attr.ib(type=EventType, validator=instance_of(EventType)) # required
data_type = attr.ib(type=EventType, validator=instance_of(DataType)) # required
data = attr.ib(default=None)
class PacketParseError(Exception):
def __init__(self, error):
super().__init__(self, error)
def __str__(self):
return f'Packet parse error: {self.error}'
def encode(self) -> attr.ib(type=bytes, validator=instance_of(bytes)):
if self.data_type == DataType.RAW:
raw = self.data
elif self.data_type == DataType.PICKLED:
raw = pickle.dumps(self.data)
elif self.data_type == DataType.STRING:
raw = self.data.encode('utf-8')
elif self.data_type == DataType.JSON:
raw = json.dumps(self.data).encode('utf-8')
else:
raw = b''
return self.event_type.value + self.data_type.value + raw
@staticmethod
def decode(
raw=attr.ib(type=bytes, validator=instance_of(bytes))
):
if len(raw) < 2:
raise PacketParseError(f'The packet is illegal.')
event_type = EventType.from_int(raw[0])
data_type = DataType.from_int(raw[1])
raw_data = raw[2:]
if data_type == DataType.RAW:
data = raw_data
elif data_type == DataType.PICKLED:
data = pickle.loads(raw_data)
elif data_type == DataType.STRING:
data = raw_data.decode('utf-8')
elif data_type == DataType.JSON:
data = json.loads(raw_data.decode('utf-8'))
else:
raise PacketParseError(f'Cannot decode datatype {data_type.value}.')
return Packet(
event_type=event_type,
data_type=data_type,
data=data
)
@attr.s(init=True)
class PacketReceiver:
"""
The class continuously read buffer from socket.
Attributes:
sock: The socket we receive buffer from. Required.
handler: The packet message handler. Default to None.
chunk_size: The length of bytes we read at one time. Deafult to 1024.
eof: The bytes at the end of packet buffer. Default to packet default eof.
thread: The thread of reading handler. Default to None.
is_alive: Bool indicates whether reading thread is alive. Default to True.
"""
sock = attr.ib(type=socket.socket, validator=instance_of(socket.socket))
handler = attr.ib(default=None)
chunk_size = attr.ib(type=int, validator=instance_of(int), default=1024)
eof = attr.ib(type=bytes, validator=instance_of(bytes), default=EOF)
is_alive = attr.ib(type=bool, validator=instance_of(bool), default=True)
thread = attr.ib(type=threading.Thread, default=None,
validator=optional([instance_of(threading.Thread), instance_of(None)]))
def start_listen(self):
self.is_alive = True
self.thread = threading.Thread(target=self.reading)
self.thread.start()
def close(self):
self.is_alive = False
def reading(self):
buffer = b''
while self.is_alive:
try:
data = self.sock.recv(self.chunk_size)
buffer += data
arr = buffer.split(self.eof)
arr_len = len(arr)
for i in range(arr_len - 1):
self.handler(arr[i], self.sock)
buffer = arr[-1] if arr[-1] else b''
except ConnectionError as e:
pass
|
daqbrokerClient.py | import time
import snowflake
import struct
import serial
import serial.tools.list_ports
import socket as SOCKETS
import zmq
import random
import multiprocessing
import os
import platform
import subprocess
import sys
import traceback
import json
import psutil
import math
import requests
import ftplib
import fnmatch
import ntplib
import argparse
import logging
import sync
import uuid
from datetime import datetime
from getpass import getpass
from numpy import linspace
base_dir = '.'
if getattr(sys, 'frozen', False):
base_dir = os.path.join(sys._MEIPASS)
# Module multiprocessing is organized differently in Python 3.4+
try:
# Python 3.4+
if sys.platform.startswith('win'):
import multiprocessing.popen_spawn_win32 as forking
else:
import multiprocessing.popen_fork as forking
except ImportError:
import multiprocessing.forking as forking
if sys.platform.startswith('win'):
# First define a modified version of Popen.
class _PopenX(forking.Popen):
def __init__(self, *args, **kw):
if hasattr(sys, 'frozen'):
# We have to set original _MEIPASS2 value from sys._MEIPASS
# to get --onefile mode working.
os.putenv('_MEIPASS2', sys._MEIPASS)
try:
super(_PopenX, self).__init__(*args, **kw)
finally:
if hasattr(sys, 'frozen'):
# On some platforms (e.g. AIX) 'os.unsetenv()' is not
# available. In those cases we cannot delete the variable
# but only set it to the empty string. The bootloader
# can handle this case.
if hasattr(os, 'unsetenv'):
os.unsetenv('_MEIPASS2')
else:
os.putenv('_MEIPASS2', '')
# Second override 'Popen' class with our modified version.
forking.Popen = _PopenX
class daqbrokerClient:
"""
Main client application class. This class can be used in the Python CLI to start the client application
or to register a machine with existing DAQBroker servers
:ivar name: (string) name of the machine that will be used to identify it by the users. Defaults to platform.node()
:ivar commport: (integer) the network port for the main part of the client application. Defaults to 9091
:ivar logport: (integer) the network port for the logging process of the application. Defaults to 9094
"""
def __init__(self, name=platform.node(), commport=9091, logport=9094, **kwargs):
self.name = name
self.logport = logport
self.commport = commport
self.shareStr = str(uuid.uuid4())[0:8]
def start(self):
"""
Function to start the main client application
.. warning::
This is a long running process and blocks execution of the main task, it should therefore be called on a separate process.
"""
#shareStr = str(uuid.uuid4())[0:8]
print('SETUP LOGGER')
p4 = multiprocessing.Process(target=logServer, args=(self.logport,))
p4.start()
print('STARTED LOGGER')
time.sleep(1)
print("SETUP MCAST")
p5 = multiprocessing.Process(
target=mCastListen,
args=(
snowflake.make_snowflake(
snowflake_file=os.path.join(base_dir, 'foo')),
self.name,
self.commport,
self.shareStr))
p5.start()
print("STARTED LOGGER")
time.sleep(1)
print('SETUP CONSUMER')
print("Share str : " + self.shareStr)
consumer(self.commport, self.logport)
def register(self, server=None, username=None, password=None):
"""
This function allows registering a client application with a DAQBroker server. This function can
be used to register with servers outside the local network. This function provides an interactive command
line interface to insert the relevant parameters for registering with a server that were not provided
as parameters
:ivar server (optiona): (string) Server URL
:ivar username (optional): (string) DAQBroker login username
:ivar password (optional): (string) DAQBroker login password
:return: (boolean) True if registration was completed successfully. False if not. Prints the error of the
registration request on failure
"""
if server:
serverName = server
else:
serverName = input('Input the server URL (serverName.com | ip.ip.ip.ip)')
if username:
loginU = server
else:
loginU = input('Insert daqbroker username:')
if password:
loginP = password
else:
loginP = getpass('Insert daqbroker password:')
toSend = {
'ID': id,
'name': self.name,
'username': loginU,
'password': loginP,
'port': self.commport}
url = 'http://' + serverName + '/daqbroker/registerNode'
# print(url)
# print(toSend)
r = requests.post(url, data=toSend)
# print(r)
# print(r.text)
# print(r.json())
if r.status_code == 200:
print(
"Successfully registered with " +
serverName +
" at port ")
return True
else:
print(
"There was a problem registering your client, please contact your system administrator\n\n")
print(r.text)
return False
# Gotta deal with new and old. Should also return the myself, don't know
# why, maybe not useful
# Gets all the metadata from an instrument, sorts only the most recent and
# from different example files and parses that data
def syncInst(
servAddr,
sendBackPort,
instMeta,
instrument,
metaid,
metaType,
database,
logPort,
lockList,
backupPort,
backupUser,
backupPass,
serverDB,
engineDB,
metaName):
try:
for i, lock in enumerate(lockList):
if lock['metaid'] == metaid:
break
theInstLock = lockList[i]
theInstLock['locked'] = True
lockList[i] = theInstLock
consumer_sender = False
context = zmq.Context()
theLogSocket = context.socket(zmq.REQ)
theLogSocket.connect("tcp://127.0.0.1:" + str(logPort))
toSend = {
'req': 'LOG',
'type': 'INFO',
'process': 'CONSUMER',
'message': "SYNCING - " + instrument}
theLogSocket.send(json.dumps(toSend).encode())
theLogSocket.close()
consumer_sender = context.socket(zmq.PUSH)
consumer_sender.setsockopt(zmq.LINGER, 1000)
machine = "tcp://" + servAddr + ":" + str(sendBackPort)
consumer_sender.connect(machine)
errors = []
sync.syncDirectory(
servAddr,
database,
instrument,
instMeta,
backupPort,
backupUser,
backupPass,
metaName,
serverDB)
except Exception as e:
# traceback.print_exc()
_, _, tb = sys.exc_info()
tbResult = traceback.format_list(traceback.extract_tb(tb)[-1:])[-1]
filename = tbResult.split(',')[0].replace('File', '').replace('"', '')
lineno = tbResult.split(',')[1].replace('line', '')
funname = tbResult.split(',')[2].replace('\n', '').replace(' in ', '')
line = str(e)
theLogSocket = context.socket(zmq.REQ)
theLogSocket.connect("tcp://127.0.0.1:" + str(logPort))
toSend = {
'req': 'LOG',
'type': 'ERROR',
'process': 'SYNCINST',
'message': str(e),
'filename': filename,
'lineno': lineno,
'funname': funname,
'line': line}
theLogSocket.send(json.dumps(toSend).encode())
theLogSocket.close()
finally:
theInstLock = lockList[i]
theInstLock['locked'] = False
theInstLock['counts'] = 0
lockList[i] = theInstLock
if consumer_sender:
endMessage = {
"server": serverDB,
"engine": engineDB,
"database": database,
"instrument": instrument,
"metaid": metaid,
"metaName": metaName,
"order": "METASYNCOVER",
"errors": errors}
consumer_sender.send_json(endMessage)
consumer_sender.close()
def logServer(port):
logging.basicConfig(
filename=os.path.join(base_dir, 'logFileAgent.log'),
level=logging.DEBUG,
format='')
logging.info(datetime.utcnow().strftime("%Y/%m/%d %H:%M:%S") +
" [LOGGER][INFO][logServer] : started logging server")
context = zmq.Context()
theSocket = context.socket(zmq.ROUTER)
logLvls = {
'info': logging.INFO,
'error': logging.ERROR,
'warning': logging.warning,
'debug': logging.debug}
theSocket.bind("tcp://127.0.0.1:" + str(port))
while True:
# Wait for next request from client
message = False
try:
message = theSocket.recv_json()
logReq = message
if 'req' in logReq:
if logReq['req'] == 'LOG':
if not (logReq['type'] == 'ERROR'):
if 'method' in logReq:
logMessage = datetime.utcnow().strftime("%Y/%m/%d %H:%M:%S") + \
' [' + logReq['process'] + '][' + logReq['method'] + '][' + logReq['type'] + '] : ' + logReq['message']
else:
logMessage = datetime.utcnow().strftime("%Y/%m/%d %H:%M:%S") + \
' [' + logReq['process'] + '][' + logReq['type'] + '] : ' + logReq['message']
else:
logMessage = datetime.utcnow().strftime("%Y/%m/%d %H:%M:%S") + \
' [' + logReq['process'] + '][' + logReq['type'] + '][' + logReq['filename'] + '][' + logReq['lineno'] + '][' + logReq['funname'] + '] : ' + logReq['line']
logging.info(logMessage)
except Exception as e:
if message:
_, _, tb = sys.exc_info()
tbResult = traceback.format_list(
traceback.extract_tb(tb)[-1:])[-1]
filename = tbResult.split(',')[0].replace(
'File', '').replace('"', '')
lineno = tbResult.split(',')[1].replace('line', '')
funname = tbResult.split(',')[2].replace(
'\n', '').replace(' in ', '')
logMessage = datetime.utcnow().strftime("%Y/%m/%d %H:%M:%S") + \
' [LOGGER][ERROR][' + filename + '+][' + lineno + '][' + funname + '] : ' + str(e)
logging.info(logMessage)
def getNTPTIme(server, timeback):
try:
c = ntplib.NTPClient()
timeback.value = c.request(server).tx_time
except BaseException:
# traceback.print_exc()
timeback.value = 0
def getLocalTime(timeback):
timeback.value = time.time()
def getMachineDetails(extra):
if 'serverNTP' in extra:
if not extra['serverNTP'] == '':
try:
serverTime = multiprocessing.Value('d', 0.0)
localTime = multiprocessing.Value('d', 0.0)
time1 = time.time()
p1 = multiprocessing.Process(
target=getNTPTIme, args=(
extra['serverNTP'], serverTime))
p2 = multiprocessing.Process(
target=getLocalTime, args=(localTime,))
p1.start()
p2.start()
p1.join()
p2.join()
time2 = time.time()
theServerTime = serverTime.value
theLocalTime = localTime.value
timeDiff = theServerTime - theLocalTime
timeDiffProcs = time2 - time1
if(platform.system() == 'Windows'): # Running on windows machine
theSetReturn = _win_set_time(timeDiff)
elif(platform.system() == 'Linux'): # Running on linux machine
theSetReturn = _linux_set_time(timeDiff)
if theSetReturn:
theTimeLocal = time.time()
time2 = time.time()
timeDiff = time2 - theTimeLocal
theTimeDifference = timeDiff
else:
theTimeLocal = time.time()
theTimeDifference = 'N/A'
except Exception as e:
# traceback.print_exc()
theTimeDifference = 'N/A'
else:
theTimeDifference = 'N/A'
else:
theTimeDifference = 'N/A'
theTimeLocal = time.time()
psutil.cpu_percent()
result = {}
disks = psutil.disk_partitions()
ram = psutil.virtual_memory()
result["ram"] = {}
result["ram"]["total"] = getSizeData(ram.total)
result["ram"]["available"] = getSizeData(ram.available)
rom = []
result["rom"] = []
temp = []
ioTemp = psutil.disk_io_counters(perdisk=True)
for i, value in enumerate(disks):
try:
rom.append(psutil.disk_usage(disks[i].mountpoint))
result["rom"].append({"total": getSizeData(rom[len(rom) - 1].total),
"free": getSizeData(rom[len(rom) - 1].free),
"device": disks[i].device,
"io": ioTemp[list(ioTemp.keys())[i]]._asdict()})
except BaseException:
poop = 'poop'
result["cpu"] = psutil.cpu_percent(interval=0.5)
result["cpuMulti"] = psutil.cpu_percent(percpu=True)
result["timeInfo"] = {
'localTime': theTimeLocal,
'serverDifference': theTimeDifference}
return result
def getSizeData(number):
result = {}
i = 0
while number / (math.pow(2, 10 * i)) > 1:
i = i + 1
continue
if i == 0:
type = "B"
elif i == 1:
type = "B"
elif i == 2:
type = "kB"
elif i == 3:
type = "MB"
elif i == 4:
type = "GB"
elif i == 5:
type = "TB"
elif i == 6:
type = "PB"
elif i > 6:
type = "FUCKTON"
if i > 0:
result["number"] = number / (math.pow(2, 10 * (i - 1)))
else:
result["number"] = number / (math.pow(2, 10 * i))
result["type"] = type
return result
def getPortData(port, parseInterval, command):
try:
client = SOCKETS.socket(SOCKETS.AF_INET, SOCKETS.SOCK_STREAM)
if(not command == ""):
client.settimeout(5)
else:
client.settimeout(parseInterval)
server_address = ('localhost', port)
client.connect(server_address)
if(not command == ""):
client.send(command.encode())
time.sleep(1)
reply = ""
recieved = client.recv(4096)
reply = reply + recieved.decode()
return {'status': 0, 'error': "", "reply": reply}
except Exception as e:
# traceback.print_exc()
return {'status': -1, 'error': str(e), "reply": ""}
def getCOMData(device, parseInterval, command, baud, par, bytes, stop):
try:
if stop == "0":
stopBits = serial.STOPBITS_ONE
if stop == "1":
stopBits = serial.STOPBITS_ONE_POINT_FIVE
if stop == "2":
stopBits = serial.STOPBITS_ONE_TWO
if(not command == ""):
ser = serial.Serial(
device,
baudrate=baud,
bytesize=bytes,
parity=par,
stopbits=stopBits,
timeout=5)
else:
ser = serial.Serial(
device,
baudrate=baud,
bytesize=bytes,
parity=par,
stopbits=stopBits,
timeout=parseInterval / 2)
ser.flush()
if(not command == ""):
ser.write(command.encode())
while not ser.readable(): # Should stay here before being readable, should leave when becomes readable. Should IMMEDIATELY become readable
continue
data = ser.read(1000000).decode()
return {'status': 0, 'error': "", "reply": data}
except Exception as e:
traceback.print_exc()
return {'status': -1, 'error': str(e), "reply": ""}
def getPeripheralData(
server,
database,
instrument,
meta,
type,
backupPort,
backupUser,
backupPass,
metaName,
metaid,
sendBackPort,
serverDB,
engineDB,
channels,
logPort,
lockList):
try:
for i, lock in enumerate(lockList):
if lock['metaid'] == metaid:
break
theInstLock = lockList[i]
theInstLock['locked'] = True
lockList[i] = theInstLock
errors = []
context = zmq.Context()
timeStart = time.time()
consumer_sender = False
consumer_sender = context.socket(zmq.PUSH)
consumer_sender.setsockopt(zmq.LINGER, 1000)
machine = "tcp://" + server + ":" + str(sendBackPort)
consumer_sender.connect(machine)
if not os.path.isdir(os.path.join('temp', server, instrument)):
os.makedirs(os.path.join('temp', server, instrument))
theFile = open(os.path.join('temp', server, instrument, metaName + '_' + \
str(datetime.now().day) + '_' + str(datetime.now().hour) + '.tmp'), 'a')
if type == 1:
returned = getPortData(int(meta["port"]), int(
meta["parseInterval"]), meta["command"])
timeEnd = time.time()
if returned["status"] == 0:
if 'parsingInfo' in meta:
lines = returned["reply"].split('\n')
for i, line in enumerate(lines):
elements = line.split(meta["parsingInfo"]["separator"])
trueLine = [elements[i][chann["remarks"]["min"]:chann["remarks"]["max"]]
for i, chann in enumerate(channels) if i < len(elements)]
lines[i] = meta["parsingInfo"]["separator"].join(
trueLine)
if not meta["parsingInfo"]["timeProvided"]:
times = list(
linspace(
timeStart,
timeEnd,
len(lines)))
lines[i] = str(
times[i]) + meta["parsingInfo"]["separator"] + lines[i]
theFile.write(lines[i] + '\n')
elif type == 2:
returned = getCOMData(
meta["device"], int(
meta["parseInterval"]), meta["command"], int(
meta["baudRates"]), meta["parity"], int(
meta["dataBits"]), meta["stopBits"])
timeEnd = time.time()
if returned["status"] == 0:
if 'parsingInfo' in meta:
if meta["parsingInfo"]["terminator"] == '':
lines = returned["reply"].split('\n')
else:
lines = returned["reply"].split(
meta["parsingInfo"]["terminator"])
for i, line in enumerate(lines):
elements = line.split(meta["parsingInfo"]["separator"])
trueLine = [elements[i][chann["remarks"]["min"]:chann["remarks"]["max"]]
for i, chann in enumerate(channels) if i < len(elements)]
lines[i] = meta["parsingInfo"]["separator"].join(
trueLine)
if not meta["parsingInfo"]["timeProvided"]:
times = list(
linspace(
timeStart,
timeEnd,
len(lines)))
lines[i] = str(
times[i]) + meta["parsingInfo"]["separator"] + lines[i]
theFile.write(lines[i] + '\n')
toSyncMeta = {
'getNested': False,
'path': os.path.join(
'temp',
server,
instrument),
'extension': 'tmp',
'pattern': metaName}
theFile.close()
sync.syncDirectory(
server,
database,
instrument,
toSyncMeta,
backupPort,
backupUser,
backupPass,
metaName)
except Exception as e:
traceback.print_exc()
errors.append(str(e))
poop = "pooop"
finally:
theInstLock = lockList[i]
theInstLock['locked'] = False
theInstLock['counts'] = 0
lockList[i] = theInstLock
if consumer_sender:
endMessage = {
"server": serverDB,
"engine": engineDB,
"database": database,
"instrument": instrument,
"metaid": metaid,
"metaName": metaName,
"order": "METASYNCOVER",
"errors": errors}
consumer_sender.send_json(endMessage)
consumer_sender.close()
def _win_set_time(timeOffset):
try:
#import pywin32
timestamp = time.time() + timeOffset
import win32api
# http://timgolden.me.uk/pywin32-docs/win32api__SetSystemTime_meth.html
# pywin32.SetSystemTime(year, month , dayOfWeek , day , hour , minute , second , millseconds )
#win32api.SetSystemTime( time_tuple[:2] + (dayOfWeek,) + time_tuple[2:])
year = int(datetime.utcfromtimestamp(int(timestamp)).strftime('%Y'))
month = int(datetime.utcfromtimestamp(timestamp).strftime('%m'))
dayOfWeek = int(datetime.utcfromtimestamp(timestamp).strftime('%w'))
day = int(datetime.utcfromtimestamp(timestamp).strftime('%d'))
hour = int(datetime.utcfromtimestamp(timestamp).strftime('%H'))
minute = int(datetime.utcfromtimestamp(timestamp).strftime('%M'))
second = int(datetime.utcfromtimestamp(timestamp).strftime('%S'))
milliseconds = int((timestamp - int(timestamp)) * 1000)
win32api.SetSystemTime(
year,
month,
0,
day,
hour,
minute,
second,
milliseconds)
return True
except BaseException:
# traceback.print_exc()
return False
def _linux_set_time(timeOffset):
try:
timestamp = time.time() + timeOffset
toRun = 'date +%s -s @' + str(int(timestamp))
# print(toRun)
a = subprocess.call(
toRun.split(' '),
stderr=subprocess.DEVNULL,
stdout=subprocess.PIPE)
if a == 0:
return True
else:
return False
except BaseException:
# print(toRun)
# traceback.print_exc()
return False
def consumer(port, logPort):
context = zmq.Context()
theLogSocket = context.socket(zmq.REQ)
theLogSocket.connect("tcp://127.0.0.1:" + str(logPort))
toSend = {'req': 'LOG', 'type': 'INFO', 'process': 'CONSUMER',
'message': "STARTED CONSUMER ON PORT- " + str(port)}
theLogSocket.send(json.dumps(toSend).encode())
theLogSocket.close()
# recieve work
consumer_receiver = context.socket(zmq.PULL)
machine = "tcp://*:" + str(port)
# print(machine)
consumer_receiver.bind(machine)
# send work
processes = []
manager = multiprocessing.Manager()
lockList = manager.list()
while True:
try:
data = consumer_receiver.recv_json()
if 'order' in data:
if data['order'] == 'update':
theLogSocket = context.socket(zmq.REQ)
theLogSocket.connect("tcp://127.0.0.1:" + str(logPort))
toSend = {
'req': 'LOG',
'type': 'INFO',
'process': 'CONSUMER',
'message': "UPDATING NODE INFO"}
theLogSocket.send(json.dumps(toSend).encode())
theLogSocket.close()
consumer_sender = context.socket(zmq.PUSH)
consumer_sender.setsockopt(zmq.LINGER, 1000)
machine = "tcp://" + \
data['server'] + ":" + str(data['sendBack'])
consumer_sender.connect(machine)
if(not (data['extra']['serverNTP'] == "") and not (data['extra']['serverNTP'] == "NONE") and data['extra']["tSync"] == "1"):
details = getMachineDetails(data['extra'])
if details["timeInfo"]['serverDifference'] == 'N/A':
theLogSocket = context.socket(zmq.REQ)
theLogSocket.connect(
"tcp://127.0.0.1:" + str(logPort))
#toSend={'req':'LOG','type':'ERROR','process':'CONSUMER','message':"could not syncronize computer time"}
toSend = {
'req': 'LOG',
'type': 'ERROR',
'process': 'CONSUMER',
'message': "could not syncronize computer time",
'filename': 'consumer',
'lineno': '317',
'funname': 'getMachineDetails',
'line': "details=getMachineDetails(data['extra'])"}
theLogSocket.send(json.dumps(toSend).encode())
theLogSocket.close()
else:
details = getMachineDetails({})
# details={}
message = {
'order': 'DETAILSOVER',
'theNode': data['theNode'],
'port': port,
'details': details}
consumer_sender.send_json(message)
consumer_sender.close()
elif data["order"] == "SYNC":
insts = []
for directive in data["directives"]:
# print(directive)
foundInstLock = False
for i, lock in enumerate(lockList):
if lock['metaid'] == directive["metaid"]:
foundInstLock = True
break
if not foundInstLock:
lockList.append(
{'metaid': directive["metaid"], 'locked': False, 'counts': 0})
i = len(lockList) - 1
if(not lockList[i]['locked']):
if directive["type"] == 0:
insts.append(directive["instrument"])
g = multiprocessing.Process(
target=syncInst,
args=(
directive['server'],
directive['sendBackPort'],
directive["remarks"],
directive["instrument"],
directive["metaid"],
directive["type"],
directive["database"],
logPort,
lockList,
directive["backupPort"],
directive["backupUser"],
directive["backupPass"],
directive["serverDB"],
directive["engine"],
directive["metaName"]))
if directive["type"] == 1 or directive["type"] == 2:
g = multiprocessing.Process(
target=getPeripheralData,
args=(
directive['server'],
directive["database"],
directive["instrument"],
directive["remarks"],
directive["type"],
directive["backupPort"],
directive["backupUser"],
directive["backupPass"],
directive["metaName"],
directive["metaid"],
directive['sendBackPort'],
directive["serverDB"],
directive["engine"],
directive["channels"],
logPort,
lockList))
# server,database,instrument,meta,type,backupPort,backupUser,backupPass,metaName,metaid,sendBackPort,serverDB,engineDB,channels,logPort,lockList
g.start()
elif data["order"] == "GETPORTDATA":
machine = "tcp://" + \
data['server'] + ":" + str(data['sendBack'])
portData = getPortData(
data["port"], data["parseInterval"], data["command"])
consumer_sender = context.socket(zmq.REQ)
consumer_sender.setsockopt(zmq.LINGER, 1000)
message = {'order': 'PORTDATA', 'portData': portData}
consumer_sender.connect(machine)
consumer_sender.send_json(message)
consumer_sender.close()
elif data["order"] == "GETCOMMPORTS":
machine = "tcp://" + \
data['server'] + ":" + str(data['sendBack'])
consumer_sender = context.socket(zmq.REQ)
consumer_sender.setsockopt(zmq.LINGER, 1000)
portData = []
for port in serial.tools.list_ports.comports():
portData.append({'device': port.device,
'info': port.description,
'hwid': port.hwid,
'vid': port.vid,
'serial': port.serial_number,
'manufacturer': port.manufacturer})
message = {'order': 'COMMPORTS', 'portData': portData}
consumer_sender.connect(machine)
consumer_sender.send_json(message)
consumer_sender.close()
except Exception as e:
_, _, tb = sys.exc_info()
tbResult = traceback.format_list(traceback.extract_tb(tb)[-1:])[-1]
filename = tbResult.split(',')[0].replace(
'File', '').replace('"', '')
lineno = tbResult.split(',')[1].replace('line', '')
funname = tbResult.split(',')[2].replace(
'\n', '').replace(' in ', '')
line = str(e)
theLogSocket = context.socket(zmq.REQ)
theLogSocket.connect("tcp://127.0.0.1:" + str(logPort))
toSend = {
'req': 'LOG',
'type': 'ERROR',
'process': 'CONSUMER',
'message': str(e),
'filename': filename,
'lineno': lineno,
'funname': funname,
'line': line}
theLogSocket.send(json.dumps(toSend).encode())
theLogSocket.close()
def mCastListen(id, node, commport, shareStr):
multicast_group = '224.224.224.224'
server_address = ('', 10090)
# Create the socket
sock = SOCKETS.socket(SOCKETS.AF_INET, SOCKETS.SOCK_DGRAM)
# Bind to the server address
sock.bind(server_address)
# Tell the operating system to add the socket to the multicast group
# on all interfaces.
group = SOCKETS.inet_aton(multicast_group)
mreq = struct.pack('4sL', group, SOCKETS.INADDR_ANY)
sock.setsockopt(SOCKETS.IPPROTO_IP, SOCKETS.IP_ADD_MEMBERSHIP, mreq)
# Receive/respond loop
while True:
data, address = sock.recvfrom(1024)
try:
processed = json.loads(data.decode())
if 'message' in processed:
if processed["message"] == 'show':
details = getMachineDetails(processed["ntp"])
toReply = {
'id': id,
'node': node,
'details': details,
'serverAddr': address[0],
'port': commport}
sock.sendto(json.dumps(toReply).encode(), address)
elif processed["message"] == 'test':
if processed["idTest"] == id and processed["shareStr"] == shareStr:
details = getMachineDetails({})
toReply = {
'result': True,
'id': id,
'node': {
'id': id,
'node': node,
'details': details,
'serverAddr': address[0],
'port': commport}}
sock.sendto(json.dumps(toReply).encode(), address)
except BaseException:
traceback.print_exc()
continue
if __name__ == "__main__":
multiprocessing.freeze_support()
theArguments = ['name', 'commport', 'logport', 'action']
obj = {}
if len(sys.argv) < 6:
for i, val in enumerate(sys.argv):
if i == len(theArguments) + 1:
break
if i < 1:
continue
obj[theArguments[i - 1]] = val
else:
sys.exit(
"Usage:\n\tdaqbrokerClient name commport logport action\nOr:\n\tdaqbrokerClient name commport logport\nOr:\n\tdaqbrokerClient name commport\nOr:\n\tdaqbrokerClient name\nOr:\n\tdaqbrokerClient")
if os.path.isfile(os.path.join(base_dir, 'pid')):
with open(os.path.join(base_dir, 'pid'), 'r') as f:
existingPID = f.read().strip('\n').strip('\r').strip('\n')
processExists = False
if existingPID:
if psutil.pid_exists(int(existingPID)):
processExists = True
print(existingPID)
if not processExists:
with open(os.path.join(base_dir, 'pid'), 'w') as f:
f.write(str(os.getpid()))
f.flush()
newClient = daqbrokerClient(**obj)
if 'action' not in obj:
obj['action'] = None
if obj["action"] == 'register':
newClient.register()
newClient.start()
else:
sys.exit("DAQBroker client application already running, please exit all running clients before starting new ones")
else:
with open(os.path.join(base_dir, 'pid'), 'w') as f:
f.write(str(os.getpid()))
f.flush()
newClient = daqbrokerClient(**obj)
if 'action' not in obj:
obj['action'] = None
if obj["action"] == 'register':
newClient.register()
newClient.start()
|
benchmark_image_sizes.py | from pymatting import load_image, show_images, trimap_split
from pymatting import cf_laplacian, make_linear_system
from config import IMAGE_DIR, ATOL, SOLVER_NAMES, SCALES, INDICES
import scipy.sparse.linalg
import numpy as np
import threading
import multiprocessing
import psutil
import time
import json
import os
def get_memory_usage():
process = psutil.Process(os.getpid())
return process.memory_info().rss
def log_memory_usage(memory_usage, log_interval=0.01):
# Log current memory usage every few milliseconds
thread = threading.currentThread()
while thread.is_running:
memory_usage.append(get_memory_usage())
time.sleep(log_interval)
def build_solver(solver_name, A, Acsr, Acsc, Acoo, AL, b, atol, rtol):
# Construct a solver from matrix A and vector b.
if solver_name == "cg_icholt":
from pymatting import cg, ichol
M = ichol(A, discard_threshold=1e-3, shifts=[0.002])
return lambda: cg(A, b, M=M, atol=atol, rtol=0)
if solver_name == "pyamg":
import pyamg
from pymatting import cg
M = pyamg.smoothed_aggregation_solver(A).aspreconditioner()
return lambda: cg(Acsr, b, M=M, atol=atol, rtol=0)
if solver_name == "mumps":
from solve_mumps import solve_mumps_coo, init_mpi, finalize_mpi
init_mpi()
return lambda: solve_mumps_coo(AL.data, AL.row, AL.col, b, is_symmetric=True)
if solver_name == "petsc":
from solve_petsc import solve_petsc_coo, init_petsc, finalize_petsc
init_petsc()
return lambda: solve_petsc_coo(
Acoo.data, Acoo.row, Acoo.col, b, atol=atol, gamg_threshold=0.1
)
if solver_name == "amgcl":
from solve_amgcl import solve_amgcl_csr
return lambda: solve_amgcl_csr(
Acsr.data, Acsr.indices, Acsr.indptr, b, atol=atol, rtol=0
)
if solver_name == "umfpack":
# Alternatively:
# return lambda: scipy.sparse.linalg.spsolve(Acsc, b, use_umfpack=True)
import scikits.umfpack
return lambda: scikits.umfpack.spsolve(A, b)
if solver_name == "superlu":
# Alternatively:
# scipy.sparse.linalg.spsolve(A, b, use_umfpack=False)
return lambda: scipy.sparse.linalg.splu(Acsc).solve(b)
if solver_name == "eigen_cholesky":
from solve_eigen import solve_eigen_cholesky_coo
return lambda: solve_eigen_cholesky_coo(Acoo.data, Acoo.row, Acoo.col, b)
if solver_name == "eigen_icholt":
from solve_eigen import solve_eigen_icholt_coo
# Choose shift hust large enough to not fail for given images
# (might fail with larger/different images)
initial_shift = 5e-4
return lambda: solve_eigen_icholt_coo(
Acoo.data, Acoo.row, Acoo.col, b, rtol=rtol, initial_shift=initial_shift
)
raise ValueError(f"Solver {solver_name} does not exist.")
def run_solver_single_image(solver_name, scale, index):
# Load images
name = f"GT{index:02d}.png"
image_path = os.path.join(IMAGE_DIR, "input_training_lowres", name)
trimap_path = os.path.join(IMAGE_DIR, "trimap_training_lowres/Trimap1", name)
image = load_image(image_path, "rgb", scale, "bilinear")
trimap = load_image(trimap_path, "gray", scale, "nearest")
# Create linear system
L = cf_laplacian(image)
A, b = make_linear_system(L, trimap)
is_fg, is_bg, is_known, is_unknown = trimap_split(trimap)
atol = ATOL * np.sum(is_known)
rtol = atol / np.linalg.norm(b)
# Compute various matrix representations
Acsr = A.tocsr()
Acsc = A.tocsc()
Acoo = A.tocoo()
AL = scipy.sparse.tril(Acoo)
# Start memory usage measurement thread
memory_usage = [get_memory_usage()]
thread = threading.Thread(target=log_memory_usage, args=(memory_usage,))
thread.is_running = True
# All threads should die if the solver thread crashes so we can at least
# carry on with the other solvers.
thread.daemon = True
thread.start()
# Measure solver build time
# Note that it is not easily possible to separate build time from solve time
# for every solver, which is why only the sum of build_time and solve_time
# should be compared for fairness.
start_time = time.perf_counter()
run_solver = build_solver(solver_name, A, Acsr, Acsc, Acoo, AL, b, atol, rtol)
build_time = time.perf_counter() - start_time
# Measure actual solve time
start_time = time.perf_counter()
x = run_solver()
solve_time = time.perf_counter() - start_time
# Stop memory usage measuring thread
thread.is_running = False
thread.join()
# Compute relative error
r = b - A.dot(x)
norm_r = np.linalg.norm(r)
# Store results
h, w = trimap.shape
result = dict(
solver_name=str(solver_name),
image_name=str(name),
scale=float(scale),
index=int(index),
norm_r=float(norm_r),
build_time=float(build_time),
solve_time=float(solve_time),
atol=float(atol),
rtol=float(rtol),
width=int(w),
height=int(h),
n_fg=int(np.sum(is_fg)),
n_bg=int(np.sum(is_bg)),
n_known=int(np.sum(is_known)),
n_unknown=int(np.sum(is_unknown)),
memory_usage=memory_usage,
)
print(result)
# Ensure that everything worked as expected
assert norm_r <= atol
# Inspect alpha for debugging
if 0:
alpha = np.clip(x, 0, 1).reshape(h, w)
show_images([alpha])
return result
def run_solver(solver_name):
print(f"Running {solver_name}")
results = []
# Dry run to ensure that everything has been loaded
run_solver_single_image(solver_name, 0.1, 4)
for scale in SCALES:
for index in INDICES:
result = run_solver_single_image(solver_name, scale, index)
results.append(result)
path = f"results/solver/{solver_name}.json"
with open(path, "w") as f:
json.dump(results, f, indent=4)
def main():
os.makedirs("results/solver/", exist_ok=True)
# Run each solver in a new process
for solver_name in SOLVER_NAMES:
process = multiprocessing.Process(target=run_solver, args=(solver_name,))
process.start()
print("waiting for join...")
process.join()
print("joined")
if __name__ == "__main__":
main()
|
queue.py | # coding=utf-8
import time
import threading
from random import random
from Queue import Queue
q = Queue()
def double(n):
return n * 2
def producer():
while 1:
wt = random()
time.sleep(wt)
q.put((double, wt))
def consumer():
while 1:
task, arg = q.get()
print arg, task(arg)
q.task_done()
for target in(producer, consumer):
t = threading.Thread(target=target)
t.start()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.